What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be..."

Transcription

1 What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control iteration Loop continues as long as condition is TRUE Types of Loop Testing Pretest Loops in C++ Endless loop Begin loop Pretest loop Test Condition true false Posttest loop Begin loop One pretest loop in C++ is the while loop A condition is used to control the loop The condition is put between parentheses Statements in loop End loop Statements in loop End loop Statements in loop Test Condition false true while (condition) statement; while (condition) statement ; statement ;... Loops can be... Count controlled repeat a specified number of times Event-controlled some condition within the loop body changes and this causes the repeating to stop Count-controlled loops They contain: An initialization of the loop control variable A condition to test for continuing the loop An update of the loop control variable to be executed with each iteration of the body 5 6

2 = ; // initialize loop variable while ( > 0) // test condition // repeated action --; // update loop variable = ; while ( > 0) --; 7 8 = ; while ( > 0) --; = ; while ( > 0) --; 9 0 = ; while ( > 0) --; = ; while ( > 0) --;

3 = ; while ( > 0) --; = ; while ( > 0) --; = ; while ( > 0) --; = ; while ( > 0) --; 5 6 = ; while ( > 0) --; = ; while ( > 0) --; 7 8

4 = ; while ( > 0) --; = ; while ( > 0) --; 9 0 = ; while ( > 0) --; 0 False = ; while ( > 0) --; 0 Event-controlled Loops = ; while ( > 0) --; 0 Done Sentinel controlled keep processing data until a special value which is not a possible data value is entered to indicate that processing should stop End-of-file controlled keep processing data as long as there is more data in the file Flag controlled keep processing data until the value of a flag changes in the loop body

5 s of Kinds of Loops A Sentinel-controlled Loop Count controlled loop Sentinel controlled loop End-of-file controlled loop Flag controlled loop Read exactly 00 blood pressures from the user. Read blood pressures until a special value (like -) selected by you is read. Read all the blood pressures from a file no matter how many are there. Read blood pressures until a dangerously high BP (00 or more) is read. 5 Sentinel value A special value of input that causes the program to stop a loop Must be a value that would not occur in the normal course of operation Requires a priming read if done with a while loop priming read means you read one set of data before the while 6 End-of-File Controlled Loop int bloodpressure, total = 0; cout << "Enter a blood pressure (- to stop ): "; cin >> bloodpressure; while (bloodpressure!= -) // while not sentinel total = total + bloodpressure; cout << "Enter a blood pressure (- to stop): "; cin >> bloodpressure; Depends on fact that a file goes into fail state when you try to read a data value beyond the end of the file Several ways to accomplish cout << total << endl; 7 8 Using the ifstream variable Combining the steps Uses a priming read The variable alone is the loop control variable If the stream has entered a fail state, it has a false, otherwise it has a true ifstream infile( data.txt ); int x; infile >> x; while(infile) //Statements infile >> x; The priming read can be done as part of the condition The logic is still the same as the previous slide ifstream infile( data.txt ); int x; while(infile >> x) //statements 9 0 5

6 eof Function eof function returns a true if the program has read past the end of the file; otherwise it returns a false Requires priming read ifstream infile( data.txt ); int x; infile >> x; while(!infile.eof()) //Statements infile >> x; Assignment With a partner write two loops that would read from the same file, money.dat, and print the contents to the screen. The program should loop until the end of the file is reached. Each of the two loops should use a different method Flag-controlled Loops Use a bool type flag variable and initialize it (to true or false) Use meaningful name for the flag A condition in the loop body changes the value of the flag Test for the flag in the loop test condition int bloodpressure, GoodReadings = 0; bool issafe = true; // initialize Boolean flag while (issafe) cin >> bloodpressure; if (bloodpressure >= 00) issafe = false; // change flag value else GoodReadings++; cout << GoodReadings << endl; Posttest Loops in C++ Posttest done with the do while statement. Also uses a condition placed in parentheses. do statement; while (condition); do statement ; statement ;... while (condition); 5 // display the numbers from to 0 // using the posttest do while loop = ; // initialize loop variable do // repeated action --; // update loop variable while ( > 0); // test condition 6 6

7 Sentinel-controlled loops with do while while vs. do while Does not require a priming read int bloodpressure = 0, total = 0; do total = total + bloodpressure; cout << "Enter a blood pressure (- to stop): "; cin >> bloodpressure; while (bloodpressure!= -); // while not sentinel cout << total << endl; while It is a Pretest loop. The loop condition is tested before executing the loop body. Loop body may not be executed at all. do while It is a Posttest loop. The loop condition is tested after executing the loop body. Loop body is always executed at least once. 7 8 Accumulating Loops often used to Count data values Sum data values Keep track of previous and current values This requires accumulating and ing 9 Accumulating (Cont..) Accumulating is keeping a running result Take the value of a variable, modify the value, and store it back in the original variable total = total + new; Any arithmetic operator (+ * / %) can be part of an accumulation total = total * new; Counting is a simple form of accumulation = + ; Make sure you INITIALIZE accumulation or ing variables 0 Accumulating (Cont..) Accumulation operators Shorthand for performing accumulation Same precedence & associativity as assignment // calculate the sum of the integers from to 0 // Initialize the ing and accumulating variables int number =, sum = 0; total += new; total -= new; total *= new; total /= new; total %= new; Equivalent statement total = total + new; total = total - new; total = total * new; total = total / new; total = total % new; while ( number <= 0) sum += number; // accumulating the sum // sum = sum + number; number += ; // ing, number = number + ; cout << "The sum is " << sum << endl; 7

8 Assignment Write a C++ program to calculate the factorial of 0. The for loop A specially designed -controlled loop for (initialization; test; updateer) statement; for (initialization; test; updateer) statement ; statement ;... The for loop Actions of the for spread out around the loop initialization occurs only ONCE at the start testing is the first repeated action of the loop (it gets done before the body each iteration) updateer occurs at the end of the loop body Initialization Test Updateer for ( = ; <= ; ++) Body cout << "Count = " << << endl; End 5 6 for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; 7 8 8

9 for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; 9 50 for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; 5 5 for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; 5 5 9

10 for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; False for ( = ; <= ; ++) cout << "Count = " << << endl; for ( = ; <= ; ++) cout << "Count = " << << endl; When the loop control condition is evaluated and has value false, the loop is said to be satisfied and control passes to the statement following the for structure Assignment for ( = ; <= ; ++) cout << "Count = " << << endl; Count = Write a program to ask the user to enter 5 integers and then find the maximum value

11 Programming Error I What output do you expect from this loop? for ( = 0; < 0; ++) cout << "*"; What about this one? for ( = 0; < 0; ++); cout << "*"; Programming Error I (Cont..) The second loop in the previous slide does not produce any output. Why? The ; right after the ( ) means that the body statement is a null statement In general, the Body of the for loop is whatever statement immediately follows the ( ) That statement can be a single statement, a block, or a null statement Actually, the second code segment in the previous slide outputs one * after the loop completes its ing to Programming Error II C++ will accept any simple data type as a er, but floating-point ers can lead to unexpected results Floating-point values are stored in E- notation and approximated to decimal values So the value.0 might be approximated to or Programming Error II (Cont..) float ; cout << "Values from 0 to in steps of 0.\n" << endl; cout << fixed << setprecision(); for ( = 0; <= ; += 0.) cout << << " "; cout << endl << "Final : " << << endl; Possible Values from 0 to in steps of Final :.00 6 Programming Error II (Cont..) cout << "Values from 0 to in steps of 0.\n" << endl; cout << fixed << setprecision(); for ( = 0; <= 0; ++) cout << /0.0 << " "; cout << endl << "Final : " << /0.0 << endl; Values from 0 to in steps of Final :.0 65 Nested Loops A loop within another is a nested loop Nest as deep as you want, but An inner loop must be entirely contained within an outer one If the loops are er controlled, each loop must have a different loop er variable Nested loops used often for rows and columns Outer loop controls the rows Inner loop controls the columns 66

12 of Nested Loops int column, row; for (row = ; row <= ; row++) for (column = ; column <= 5; column++) cout << setw() << row * column << " "; cout << endl; : Assignment Write a program to display the following output: Validation Loops Sometimes you may need to check for validity of input data The user can enter negative value where it is supposed to be positive (year) The user can enter a value that is outside the range of possible values (entering 0 for a test score) This can be done with validation loops Continue prompting the user for valid value as long as invalid value is entered 69 int score; cout << "Enter the test score: "; cin >> score; // test score should be between 0 and 00 while ( score > 00 score < 0) cout << "Invalid input, enter again: "; cin >> score; cout << endl << "The test score is " << score << endl; 70 Enter the test score: -8 Invalid input, enter again: 0 Invalid input, enter again: 89 The test score is 89 The break statement The break statement can be used with switch or any of the looping structures. It causes an immediate exit from the switch, while, do while, or for structure in which it appears. If the break is inside nested structures, control exits only the innermost structure containing it. 7 7

13 The continue statement The continue statement is valid only within loops. It terminates the current loop iteration, but not the entire loop. In a for or while loop, continue causes the rest of the body statement to be skipped - in a for statement, the update is done. In a do while loop, the exit condition is tested, and if true, the next loop iteration starts. Loop Testing and Debugging Beware of infinite loops - program doesn t stop Check loop termination condition, and watch for off-by- problem Trace execution of loop by hand with code walk-through Use debug output statements 7 7

While Loop. 6. Iteration

While Loop. 6. Iteration While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true

More information

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

while for ! do while ! set an accumulator variable to 0 ! add the next number to it inside the loop

while for ! do while ! set an accumulator variable to 0 ! add the next number to it inside the loop Week 7: Advanced Loops while Loops in C++ (review) while (expression) statement statement may be a compound statement (a block: {statements) Gaddis: 5.7-12 CS 1428 Fall 2014 Jill Seaman 1 for if expression

More information

UEE1302 (1102) F10 Introduction to Computers and Programming

UEE1302 (1102) F10 Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming Programming Lecture 03 Flow of Control (Part II): Repetition while,for & do..while Learning

More information

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops

More information

cin >> num1 >> num2 >> num3 >> num4 >> num5; sum = num1 + num2 + num3 + num4 + num5; average = sum / 5.

cin >> num1 >> num2 >> num3 >> num4 >> num5; sum = num1 + num2 + num3 + num4 + num5; average = sum / 5. Lesson Outcomes At the end of this chapter, student should be able to: Understand the requirement of a loop Understand the Loop Control Variable (LCV) Use increment (++) and decrement (--) operators Program

More information

Chapter 6 Repetition

Chapter 6 Repetition Chapter 6 Repetition 6-1 Repetition in C++ The final control/logic structure is repetition: Repetition repeating a block of code until a condition is met There are three repetition statements available

More information

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream

More information

6. Control Structures

6. Control Structures - 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

More information

4.2 The while Loop. ***Same as Fig 3.6 in intro5e p91

4.2 The while Loop. ***Same as Fig 3.6 in intro5e p91 Chapter 4 Loops Objectives To use while, do-while, and for loop statements to control the repetition of statements ( 4.2-4.4). To understand the flow of control in loop statements ( 4.2-4.4). To use Boolean

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 3 Control Structures 1 Control structures Algorithm Development Conditional Expressions Selection Statements Repetition Statements Structuring

More information

Final Exam Review. CS 1428 Fall Jill Seaman. Final Exam

Final Exam Review. CS 1428 Fall Jill Seaman. Final Exam Final Exam Review CS 1428 Fall 2011 Jill Seaman 1 Final Exam Friday, December 9, 11:00am to 1:30pm Derr 241 (here) Closed book, closed notes, clean desk Comprehensive (covers entire course) 25% of your

More information

Chapter 5. Selection 5-1

Chapter 5. Selection 5-1 Chapter 5 Selection 5-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

More information

6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011

6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011 6.096 Lab 1 Due: 7 January 1:30:00 September 0, 011 1 Additional Material 1.1 Constants A constant is an expressions with a fixed value. Kinds of constants: Literals: used to express particular values

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

Basics of I/O Streams and File I/O

Basics of I/O Streams and File I/O Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading

More information

Chapter 4 Operators & Arithmetic

Chapter 4 Operators & Arithmetic Chapter 4 Operators & Arithmetic 4-1 Arithmetic in C++ Arithmetic expressions can be made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition)

More information

Introduction to C++ Programming

Introduction to C++ Programming 2 Introduction to C++ Programming OBJECTIVES In this chapter you will learn: To write simple computer programs in C++. To write simple input and output statements. To use fundamental types. Basic computer

More information

Control Structures in C++: Selection and Repetition Statements

Control Structures in C++: Selection and Repetition Statements Control Structures in C++: Selection and Repetition Statements 1. Log in to your account as usual and start up the Bloodshed Dev C/C++ System as described in Lab No. 1. Click on File New Source File. 2.

More information

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.

Loops In Python. In this section of notes you will learn how to rerun parts of your program without having to duplicate the code. Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code. The Need For Repetition (Loops) Writing out a simple counting program (1

More information

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++ MS Visual C++ Introduction 1 Quick Introduction The following pages provide a quick tutorial on using Microsoft Visual C++ 6.0 to produce a small project. There should be no major differences if you are

More information

Introduction to Programming

Introduction to Programming Introduction to Programming SS 2012 Adrian Kacso, Univ. Siegen adriana.dkacsoa@duni-siegena.de Tel.: 0271/740-3966, Office: H-B 8406 Stand: April 25, 2012 Betriebssysteme / verteilte Systeme Introduction

More information

Chapter 8 Selection 8-1

Chapter 8 Selection 8-1 Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

More information

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Example Assume the following specification: Input: read a number N > 0 Output:

More information

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification: Example Introduction to Programming (in C++) Loops Assume the following specification: Input: read a number N > 0 Output: write the sequence 1 2 3 N (one number per line) Jordi Cortadella, Ricard Gavaldà,

More information

Repetition and Loops. Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed.

Repetition and Loops. Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed. New Topic Repetition and Loops Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed. These constructs are the 1. while loop and

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore

More information

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays

A First Book of C++ Chapter 2 Data Types, Declarations, and Displays A First Book of C++ Chapter 2 Data Types, Declarations, and Displays Objectives In this chapter, you will learn about: Data Types Arithmetic Operators Variables and Declarations Common Programming Errors

More information

[Page 70 (continued)] a. are used to document a program and improve its readability. [Page 71]

[Page 70 (continued)] a. are used to document a program and improve its readability. [Page 71] [Page 70 (continued)] Exercises 2.7 Discuss the meaning of each of the following objects: a. std::cin b. std::cout 2.8 Fill in the blanks in each of the following: a. are used to document a program and

More information

Common Syntax and Semantic Errors

Common Syntax and Semantic Errors C H A P T E R 2 Common Syntax and Semantic Errors 2.1 CHAPTER OBJECTIVES To understand the fundamental characteristics of syntax and semantic errors To be able to identify specific common syntax and semantic

More information

The While Loop. Objectives. Textbook. WHILE Loops

The While Loop. Objectives. Textbook. WHILE Loops Objectives The While Loop 1E3 Topic 6 To recognise when a WHILE loop is needed. To be able to predict what a given WHILE loop will do. To be able to write a correct WHILE loop. To be able to use a WHILE

More information

Module I Basic elements in C++

Module I Basic elements in C++ Module I Basic elements in C++ Objectives In this topic, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic

More information

CS 101: Computer Programming and Utilizati on

CS 101: Computer Programming and Utilizati on CS 101: Computer Programming and Utilizati on Jul-Nov 2016 Bernard Menezes (cs101@cse.iitb.ac.in) Lecture 5: Conditional Execution About These Slides Based on Chapter 6 of the book An Introduction to Programming

More information

Passing 1D arrays to functions.

Passing 1D arrays to functions. Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

Lecture 14 Loop Structures and Boolean Algebra

Lecture 14 Loop Structures and Boolean Algebra CITS1401 & CITS4406 Problem Solving & Programming Ghulam Mubashar Hassan Lecture 14 Loop Structures and Boolean Algebra (Based on John Zelle s powerpoint lectures) 15 September 2016 Important Announcement

More information

Control Structure. Pseudocode: Input number If number is even Then Print even Else print odd. Flowchart: Begin. End. Print Odd. number even?

Control Structure. Pseudocode: Input number If number is even Then Print even Else print odd. Flowchart: Begin. End. Print Odd. number even? Control Structure Normally, a program is executed in a sequential manner.however, in many cases, a program has to choose among alternative statements C++ provides constructs that enable the programmer

More information

Chapter 4 C Program Control

Chapter 4 C Program Control Chapter 4 C Program Control Objectives of this chapter: Repetitions will be considered in greater detail for.. repetition do while repetition Also multiple selection switch case statement will be learned.

More information

Answers to Review Questions Chapter 7

Answers to Review Questions Chapter 7 Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element

More information

Branching. We ll continue to look at the basics of writing C++ programs including. Overview

Branching. We ll continue to look at the basics of writing C++ programs including. Overview Branching Overview We ll continue to look at the basics of writing C++ programs including Boolean Expressions (need to know this before we can using branching and looping!) Branching J.S. Bradbury CSCI

More information

Selection: if Statement

Selection: if Statement : if Statement The simplest selection structure in C++ is the if statement. Syntactically: 1 if The Boolean expression must be enclosed in parentheses, and

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 2: Basic Elements of C++

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with the basic components of a C++ program,

More information

Conditions & Boolean Expressions

Conditions & Boolean Expressions Conditions & Boolean Expressions 1 In C++, in order to ask a question, a program makes an assertion which is evaluated to either true (nonzero) or false (zero) by the computer at run time. Example: In

More information

5 Let s all move one place on. Lewis Carroll

5 Let s all move one place on. Lewis Carroll Control Statements: Part 2, Solutions 5 Let s all move one place on Lewis Carroll The wheel is come full circle William Shakespeare How many apples fell on Newton s head before he took the hint! Robert

More information

Problem Solving With C++

Problem Solving With C++ Dept. of Geomatics Eng. University of Tehran Cell: 0912 132 5823 Email: marajabi@ut.ac.ir http://www.marajabi.com Unfinished Business Casts (force an expression to be of a specific type) #include

More information

OUTCOMES BASED LEARNING MATRIX

OUTCOMES BASED LEARNING MATRIX Course: CTIM371 Programming in C++ OUTCOMES BASED LEARNING MATRIX Department: Computer Technology and Information Management Course Description: This is the first course in the C++ programming language.

More information

14 MAKING DECISIONS IN C

14 MAKING DECISIONS IN C 14 MAKING DECISIONS IN C 14.1 INTRODUCTION So far we have seen that in C programs the instructions are executed in the same order in which they appear in the program. Each instruction is executed once

More information

A relational operator is used to make comparison between two expressions. All these operators are binary and require two operands.

A relational operator is used to make comparison between two expressions. All these operators are binary and require two operands. Control Structures in C++ Index Control Structures in C++ 3.1 Relational Operators A relational operator is used to make comparison between two expressions. All these operators are binary and require two

More information

Boolean Variables and Expressions

Boolean Variables and Expressions Boolean Variables and Expressions 1 Recall Standard C++ supports a simple data type specialized for representing logical values. bool type variables can have either of two values: or The identifiers and

More information

Part IA Computing Course Tutorial Guide to C++ Programming

Part IA Computing Course Tutorial Guide to C++ Programming Part IA Computing Course Tutorial Guide to C++ Programming Roberto Cipolla Department of Engineering University of Cambridge September 1, 2004 This document provides an introduction to computing and the

More information

Chapter 4 Intro to Programming in C++

Chapter 4 Intro to Programming in C++ Chapter 4 Intro to Programming in C++ 4-1 Computer Programming Earlier we defined an algorithm to be a step by step process for solving a problem. Computer programming is the process of implementing the

More information

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Dr. KHALIL The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Problem Solving & Assignment (2) Programming in C++ Group 1 Write a C++ program

More information

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output: 1 2 3 4 5 6 7 8 9 10

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output: 1 2 3 4 5 6 7 8 9 10 Java Loops & Methods The while loop Syntax: while ( condition is true ) { do these statements Just as it says, the statements execute while the condition is true. Once the condition becomes false, execution

More information

Chapter 5 Looping. At a Glance. Overview. Objectives. Quick Quizzes. Additional Resources. Key Terms

Chapter 5 Looping. At a Glance. Overview. Objectives. Quick Quizzes. Additional Resources. Key Terms Chapter 5 Looping At a Glance Overview Objectives Quick Quizzes Additional Resources Key Terms Lecture Notes Overview Chapter 5 covers loops in detail. Students learn the advantages of looping. They also

More information

Adjusted/Modified by Nicole Tobias. Chapter 2: Basic Elements of C++

Adjusted/Modified by Nicole Tobias. Chapter 2: Basic Elements of C++ Adjusted/Modified by Nicole Tobias Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types

More information

Chapter 9. Sorting and Searching Arrays. Contents. Introduction. Sorting with the Bubble Sort

Chapter 9. Sorting and Searching Arrays. Contents. Introduction. Sorting with the Bubble Sort Sorting and Searching Arrays Chapter 9 A portion of this lab is to be done during the scheduled lab time. The take-home programming assignments are to be completed on your own; see the lab website for

More information

JavaScript: Control Statements I

JavaScript: Control Statements I 1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can

More information

7.7 Case Study: Calculating Depreciation

7.7 Case Study: Calculating Depreciation 7.7 Case Study: Calculating Depreciation 1 7.7 Case Study: Calculating Depreciation PROBLEM Depreciation is a decrease in the value over time of some asset due to wear and tear, decay, declining price,

More information

PIC 10A. Lecture 7: Graphics II and intro to the if statement

PIC 10A. Lecture 7: Graphics II and intro to the if statement PIC 10A Lecture 7: Graphics II and intro to the if statement Setting up a coordinate system By default the viewing window has a coordinate system already set up for you 10-10 10-10 The origin is in the

More information

Moving from C++ to VBA

Moving from C++ to VBA Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry

More information

Essentials of Counter-Controlled Repetition. Counter-controlled repetition requires:

Essentials of Counter-Controlled Repetition. Counter-controlled repetition requires: Lecture 5 Slide 1 Essentials of Counter-Controlled Repetition Counter-controlled repetition requires: Name of control variable (loop counter) Initial value of control variable Increment/decrement of control

More information

Looping Exercises Deciding Which Loop to Use

Looping Exercises Deciding Which Loop to Use Looping Exercises Deciding Which Loop to Use At this time you have learned four looping constructs (also called repetition statements). Each of these four loops are ideal to use in different situations.

More information

Chapter 2: Problem Solving Using C++

Chapter 2: Problem Solving Using C++ Chapter 2: Problem Solving Using C++ 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common

More information

Visual Logic Instructions and Assignments

Visual Logic Instructions and Assignments Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.

More information

Exercise 1 : Write a C++ program to calculate Fubanaci numbers X n, n=1,2,,1000 X n+1 = X n + X n-1, X 0 =1,, X 1 =1, n=1,2,

Exercise 1 : Write a C++ program to calculate Fubanaci numbers X n, n=1,2,,1000 X n+1 = X n + X n-1, X 0 =1,, X 1 =1, n=1,2, Programming problems Exercise 1 : Write a C++ program to calculate Fubanaci numbers X n, n=1,2,,1000 X n+1 = X n + X n-1, X 0 =1,, X 1 =1, n=1,2, Exercise 2: Write a C++ program TO REARRANGE A LIST OF

More information

2. Place the following computers in order from oldest to most recent. _middle ABC _oldest Analytical Engine _newest ENIAC

2. Place the following computers in order from oldest to most recent. _middle ABC _oldest Analytical Engine _newest ENIAC Chapter 1 1. Match the following people with their contribution to the field of Computer Science, where a name can be used more than once. A. John Atanasoff and Cilfford Berry B. Augusta Ada Byron C. Charles

More information

Two-way selection. Branching and Looping

Two-way selection. Branching and Looping Control Structures: are those statements that decide the order in which individual statements or instructions of a program are executed or evaluated. Control Structures are broadly classified into: 1.

More information

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition Chapter 2: Algorithm Discovery and Design Invitation to Computer Science, C++ Version, Third Edition Objectives In this chapter, you will learn about: Representing algorithms Examples of algorithmic problem

More information

The Fundamentals of C++

The Fundamentals of C++ The Fundamentals of C++ Basic programming elements and concepts JPC and JWD 2002 McGraw-Hill, Inc. Program Organization Program statement Definition Declaration Action Executable unit Named set of program

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

F ahrenheit = 9 Celsius + 32

F ahrenheit = 9 Celsius + 32 Problem 1 Write a complete C++ program that does the following. 1. It asks the user to enter a temperature in degrees celsius. 2. If the temperature is greater than 40, the program should once ask the

More information

Formatting Numbers with C++ Output Streams

Formatting Numbers with C++ Output Streams Formatting Numbers with C++ Output Streams David Kieras, EECS Dept., Univ. of Michigan Revised for EECS 381, Winter 2004. Using the output operator with C++ streams is generally easy as pie, with the only

More information

3/13/2012. ESc101: Multiple statement execution using loops. Loops are used when instructions are repeated. while statement can be used for a loop

3/13/2012. ESc101: Multiple statement execution using loops. Loops are used when instructions are repeated. while statement can be used for a loop ESc101: Multiple statement execution using loops Instructor: Krithika Venkataramani Semester 2, 2011-2012 The content of most of these slides are taken from the lecture slides of Prof. Arnab Bhattacharya

More information

C++ Basics. C++ Basics: Names: Identifiers. Names: Identifiers. Display 2.1 A C++ Program (1 of 2) Display 2.1 A C++ Program (2 of 2)

C++ Basics. C++ Basics: Names: Identifiers. Names: Identifiers. Display 2.1 A C++ Program (1 of 2) Display 2.1 A C++ Program (2 of 2) C++ Basics C++ Basics: 2.1 Variables and Assignments Variables and Assignments Input and Output Data Types and Expressions Simple Flow of Control Program Style A C++ variable can hold a number or other

More information

1. A(n) structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d.

1. A(n) structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d. Chapter Four MULTIPLE CHOICE 1. A(n) structure is a logical design that controls the order in which a set of statements execute. a. function b. control c. sequence d. iteration 2. The decision structure

More information

Tutorial 9 Income Tax Calculator Application: Introducing the switch Multiple-Selection Statement

Tutorial 9 Income Tax Calculator Application: Introducing the switch Multiple-Selection Statement Tutorial 9 Income Tax Calculator Application: Introducing the switch Multiple-Selection Statement Outline 9.1 Test-Driving the Income Tax Calculator Application 9.2 Introducing the switch Multiple-Selection

More information

Appendix K Introduction to Microsoft Visual C++ 6.0

Appendix K Introduction to Microsoft Visual C++ 6.0 Appendix K Introduction to Microsoft Visual C++ 6.0 This appendix serves as a quick reference for performing the following operations using the Microsoft Visual C++ integrated development environment (IDE):

More information

Loops. 4.4 Problem Solving: Special Topic 4.3: Special Form of the print Function 188 Worked Example 4.1: Average Exam Grades 188.

Loops. 4.4 Problem Solving: Special Topic 4.3: Special Form of the print Function 188 Worked Example 4.1: Average Exam Grades 188. Loops C h a p t e r 4 C h a p t e r G o a l s To implement while and for loops To hand-trace the execution of a program To become familiar with common loop algorithms To understand nested loops To process

More information

Iteration CHAPTER 6. Topic Summary

Iteration CHAPTER 6. Topic Summary CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many

More information

FORM 1 (Please put your name, section # (10am- 001/2pm-002, and form # on the scantron!!!!) CS 161 Exam I:

FORM 1 (Please put your name, section # (10am- 001/2pm-002, and form # on the scantron!!!!) CS 161 Exam I: FORM 1 (Please put your name, section # (10am- 001/2pm-002, and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each): 1. The following statement is legal: cout >> Hello, my name is

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Sequential Program Execution

Sequential Program Execution Sequential Program Execution Quick Start Compile step once always g++ -o Realtor1 Realtor1.cpp mkdir labs cd labs Execute step mkdir 1 Realtor1 cd 1 cp../0/realtor.cpp Realtor1.cpp Submit step cp /samples/csc/155/labs/1/*.

More information

Introduction to Programming (in C++) Conclusions. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Programming (in C++) Conclusions. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Introduction to Programming (in C++) Conclusions Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Why is programming hard? Part of the difficulty is that we have many requirements.

More information

Outline. Repetition (Loops) Types of Loops. Repetitions with Loops. Terminating Loops. PreTest vs. PostTest Loops. II.

Outline. Repetition (Loops) Types of Loops. Repetitions with Loops. Terminating Loops. PreTest vs. PostTest Loops. II. Repetition (Loops) Outline Want to do some repetitive sequence of actions: print vertical line of s Corresponding program: printf( \n ); printf( \n ); printf( \n ); printf( \n ); printf( \n ); II. Program

More information

Input and Output! Objectives" (and predefined functions)" 1E3! Topic 4! n Learn what a stream is and examine input and output streams!

Input and Output! Objectives (and predefined functions) 1E3! Topic 4! n Learn what a stream is and examine input and output streams! Input and Output! (and predefined functions)" 1E3! Topic 4! 4 I/O 1 Objectives" n Learn what a stream is and examine input and output streams! n Explore how to read data from the standard input device!

More information

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley 2016/17.

Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley 2016/17. Lecture 11: while loops CS1068+ Introductory Programming in Python Dr Kieran T. Herley Python s while loop. Summary Department of Computer Science University College Cork 2016/17 KH (02/11/16) Lecture

More information

Member Functions of the istream Class

Member Functions of the istream Class Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,

More information

Lecture 2 Notes: Flow of Control

Lecture 2 Notes: Flow of Control 6.096 Introduction to C++ January, 2011 Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation Normally, a program executes statements from first to last. The

More information

ALGORITHMS AND FLOWCHARTS

ALGORITHMS AND FLOWCHARTS ALGORITHMS AND FLOWCHARTS A typical programming task can be divided into two phases: Problem solving phase produce an ordered sequence of steps that describe solution of problem this sequence of steps

More information

Binary Adders: Half Adders and Full Adders

Binary Adders: Half Adders and Full Adders Binary Adders: Half Adders and Full Adders In this set of slides, we present the two basic types of adders: 1. Half adders, and 2. Full adders. Each type of adder functions to add two binary bits. In order

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

Statements and Control Flow

Statements and Control Flow Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

More information

Chapter 9 Text Files User Defined Data Types User Defined Header Files

Chapter 9 Text Files User Defined Data Types User Defined Header Files Chapter 9 Text Files User Defined Data Types User Defined Header Files 9-1 Using Text Files in Your C++ Programs 1. A text file is a file containing data you wish to use in your program. A text file does

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Java iteration statements

Java iteration statements Java iteration statements Iteration statements are statements which appear in the source code only once, but it execute many times. Such kind of statements are called loops. Almost all the programming

More information

Model Paper Computer Science Objective. Paper Code Time Allowed: 20 minutes

Model Paper Computer Science Objective. Paper Code Time Allowed: 20 minutes Note: This is Model Paper for guidance of students & teachers. Q. Model Paper Computer Science Objective Intermediate Part II ( th Class) Examination Session -4 and onward Total marks: 7 Paper Code Time

More information

Using C++ File Streams

Using C++ File Streams Using C++ File Streams David Kieras, EECS Dept., Univ. of Michigan Revised for EECS 381, 9/20/2012 File streams are a lot like cin and cout In Standard C++, you can do I/O to and from disk files very much

More information