Chapter 5: Loops. Slide 5- 2 Outline Increment and Decrement while loop do-while loop for loop.

Slides:



Advertisements
Similar presentations
CS0004: Introduction to Programming Repetition – Do Loops.
Advertisements

Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Starting Out with C++, 3 rd Edition 1 Chapter 5. Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Chapter 5: Loops and Files.
Objectives You should be able to describe:
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 6: Repetition  Some additional operators increment and decrement.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
Chapter 4: Loops and Files. The Increment and Decrement Operators  There are numerous times where a variable must simply be incremented or decremented.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Control Structures Repetition or Iteration or Looping Part II.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
A First Book of ANSI C Fourth Edition Chapter 5 Repetition.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: The while Statement cin within a while Loop The for.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5 Repetition. 2 Objectives You should be able to describe: The while Statement cin within a while Loop The for Statement The do Statement Common.
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter 6: Looping. Objectives Learn about the loop structure Create while loops Use shortcut arithmetic operators Create for loops Create do…while loops.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Computer Programming -1-
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Loops and Files.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
TOPIC 4: REPETITION CONTROL STRUCTURE
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Alternate Version of STARTING OUT WITH C++ 4th Edition
Chapter 6: Repetition Statements
Computing Fundamentals
Alternate Version of STARTING OUT WITH C++ 4th Edition
Objectives You should be able to describe: The while Statement
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Chapter 5: Loops

Slide 5- 2 Outline Increment and Decrement while loop do-while loop for loop

Slide 5- 3 The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix) a variable: ++val; val++;

Slide 5- 4 The Increment and Decrement Operators -- is the decrement operator. It subtracts one from a variable. val--; is the same as val = val - 1; -- can be also used before (prefix) or after (postfix) a variable: --val; val--;

Slide 5- 5 (Program Continues)

Slide 5- 6

Slide 5- 7 Prefix vs. Postfix ++ and -- operators can be used in complex statements and expressions In prefix mode ( ++val, --val ) the operator increments or decrements, then returns the value of the variable In postfix mode ( val++, val-- ) the operator returns the value of the variable, then increments or decrements

Slide 5- 8 Prefix vs. Postfix - Examples int num, val = 12; cout << val++; // displays 12, // val is now 13; cout << ++val; // sets val to 14, // then displays 14 num = --val; // sets val to 13, // stores 13 in num num = val--; // stores 13 in num, // sets val to 12

Slide 5- 9 Outline Increment and Decrement while loop do-while loop for loop

Slide Introduction to Loops: The while Loop Loop: a control structure that causes a statement or statements to repeat General format of the while loop: while (expression) statement; statement; can also be a block of statements enclosed in { }

Slide The general form of the while statement is: while (expression) statement; OR while (expression) { statement1; statement2; } Introduction to Loops: The while Loop

Slide 5- 12

Slide The process used by the computer in evaluating a while statement is: 1. test the expression 2. if the expression has a nonzero (true) value a. execute the statement following the parentheses b. go back to step 1 else exit the while statement

Slide while Loop – How It Works while (expression) statement; expression is evaluated – if true, then statement is executed, and expression is evaluated again – if false, then the loop is finished and program statements following statement execute

Slide The Logic of a while Loop

Slide 5- 16

Slide How the Loop in Lines 9 through 13 Works

Slide Flowchart of the Loop

Slide while is a Pretest Loop expression is evaluated before the loop executes. The following loop will never execute: int number = 6; while (number <= 5) { cout << "Hello\n"; number++; }

Slide An Infinite Loop int number = 1; while (number <= 5) { cout << "Hello\n"; }

Slide Watch Out for Infinite Loops The loop must contain code to make expression become false Otherwise, the loop will have no way of stopping Such a loop is called an infinite loop, because it will repeat an infinite number of times

Slide Example: void main ( void ) { int count = 1; while(count <= 10) { cout << count << " "; count = count + 1; //count++; //count += 1; } } Output:

Slide void main ( void ) { int i; i = 10; while(i >= 1 ) { cout << i << " "; i = i - 1; //count--; count -= 1; } What is the output from the next segment of code? Output:

The Power of the while statement To illustrate the power of the while statement, consider the task of printing a table of numbers from 1 to 10 with their squares and cubes. This can be done with a simple while statement: void main ( void ) { int num = 1; //Display Heading cout << "Number Square Cube\n" << " \n"; while (num < 11) { cout << num << " " << pow(num, 2) << " " << pow(num, 3) << " "<< endl; num = num + 1; } }

The Power of the while statement Note: The expression (num <= 10) could have been used in place of (num < 11). Number Square Cube If we wanted to use the previous program to produce a table of 1000 numbers, all we have to do is change the expression in the while statement from (num < 11) to (num < 1001).

cin within a while loop Combining interactive data entry with the repetition capabilities of the while statement produces very adaptable and powerful programs. To understand the concept involved consider the following program which asks the user to enter a user specified amount of numbers and then displays the total of those numbers. Prompt user for how many numbers to be entered. Prompt user for the numbers. Add each number to a variable named total which accumulates the total of all numbers entered. Initialize total to zero before the loop begins. Accumulate the numbers (total = total + number)

int main ( void ) { int numbers_entered = 0, total = 0, number = 0; int counter = 1; cout << "How many numbers do you wanted added?" << endl; cin >> numbers_entered; while (counter <= numbers_entered) { cout << "Please enter a number: "; cin >> number; total = total + number; //total += number; counter = counter + 1; //counter++; counter += 1; } cout << "\nThe total of the numbers entered is " << total; return 0; }

Slide Outline Increment and Decrement while loop do-while loop for loop

Slide The do-while Loop do-while : a posttest loop – execute the loop, then test the expression General Format: do statement; // or block in { } while (expression); Note that a semicolon is required after (expression)

Slide The do statement allows us to execute some statements before an expression is evaluated. The general form of the do statement is: do statement; while(expression); //don ’ t forget the ; OR do { statement1; statement2; }while(expression); //don ’ t forget the ; The do-while Loop

Slide The Logic of a do - while Loop

Slide do - while Example int x = 1; do { cout << x << endl; } while(x < 0); Although the test expression is false, this loop will execute one time because do - while is a posttest loop.

Slide do-while Loop Notes Loop always executes at least once Execution continues as long as expression is true, stops repetition when expression becomes false Useful in menu-driven programs to bring user back to menu to make another choice (see Program in the next slide)

Slide 5- 35

Slide Validity Checks (Data Validation) The do statement is particularly useful in filtering user-entered input and providing data validity checks. For example, assume that an operator is required to enter a valid customer identification number between the numbers 100 and A number outside this range is to be rejected and a new request for a valid number made. The following section of code provides the necessary data filter to verify the entry of a valid identification number. do { cout << "\nEnter an identification number: "; cin >> ident_number; }while(ident_number 1999);

Slide Here, a request for an identification number is repeated until a valid number is entered. This section of code is "bare bones" in that it neither alerts the operator to the cause of the new request for data nor allows premature exit from the loop if a valid identification number cannot be found. An alternative that removes the first drawback is do { cout << "\nEnter an identification number: "; cin >> ident_number; if (ident_number 1999) { cout << "\nAn invalid number was just entered"; cout << "\nPlease check the ID number and re-enter."; } }while(ident_number 1999);

Slide Outline Increment and Decrement while loop do-while loop for loop

Slide Loop There are two types of the loop: – Conditional loop: executes as long as a particular condition exists (you don’t know how many times of the loop will continue). – Count-controlled loop: when you know the exact number of iterations that a loop must perform.

Slide The for Loop Useful for counter-controlled loop General Format: for(initialization; test; update) statement; // or block in { } No semicolon after 3 rd expression or after the )

Slide The for Loop General Format: for(initialization; test; update) statement; // or block in { } for Loop - Mechanics 1)Perform initialization 2)Evaluate test expression If true, execute statement If false, terminate loop execution 3)Execute update, then re-evaluate test expression

Slide for Loop - Example int count; for (count = 1; count <= 5; count++) cout << "Hello" << endl;

Slide A Closer Look at the Previous Example

Slide Flowchart for the Previous Example

while initializing statements; while (expression) { loop statements;. expression-altering statements; }

Examples While int count = 1; while (count <= 10) { cout << count ; count++; //or count += 1; or count = count + 1; } Same loop as above but coded using the for statement: for (int count = 1; count <= 10; count++) cout << count;

Excercise While int count = 2; while(count <= 20) { cout << count ; count = count + 2; //or count += 2; } Same loop as above but coded using the for statement: for (int count = 2; count <= 20; count += 2) cout << count;

Example What is produced from the following segments of programs? const int MAXNUMS = 10; int main ( void ) { int num; cout << "Number Square Cube\n" << " \n" << endl; for (num = 1; num <= MAXNUMS; num++) cout << num << " " << num * num << " " << num * num * num << endl; return 0; }

Example - Output Number Square Cube

Slide for loop – pretest loop When to Use the for Loop? – In any situation that clearly requires an initialization a false condition to stop the loop an update to occur at the end of each iteration The for loop tests its test expression before each iteration, so it is a pretest loop. The following loop will never iterate: for (count = 11; count <= 10; count++) cout << "Hello" << endl;

Slide for Loop - Modifications You can have multiple statements in the initialization expression. Separate the statements with a comma: int x, y; for (x=1, y=1; x <= 5; x++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } Initialization Expression

Slide for Loop - Modifications You can also have multiple statements in the update expression. Separate the statements with a comma: int x, y; for (x=1, y=1; x <= 5; x++, y++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } Update Expression

Slide for Loop - Modifications You can omit the initialization expression if it has already been done: int sum = 0, num = 1; for (; num <= 10; num++) sum += num;

Slide for Loop - Modifications You can declare variables in the initialization expression: int sum = 0; for (int num = 0; num <= 10; num++) sum += num; The scope of the variable num is the for loop.

Slide Keeping a Running Total running total: accumulated sum of numbers from each repetition of loop accumulator: variable that holds running total int sum=0, num=1; // sum is the accumulator while (num <= 10) { sum += num; num++; } cout << "Sum of numbers 1 – 10 is" << sum << endl;

int main ( void ) { int total_numbers, number, total = 0 ; // total is the accumulator cout << "How many numbers would you like to total?" << endl; cin >> total_numbers; for(int counter = 0; counter < total_numbers; counter++) { cout << "Please enter a number: " << endl; cin >> number; total = total + number; //or total += number; } cout << "\nThe total of the numbers you entered is: "<< total; cout <<"\nThe average of the numbers you entered is: " << total/double (total_numbers); return 0; }

Output How many numbers would you like to total? 4 Please enter a number: 56 Please enter a number: 45 Please enter a number: 85 Please enter a number: 43 The total of the numbers you entered is: 229 The average of the numbers you entered is: 57.25

Slide (Program Continues)

Slide 5- 59

Slide Sentinels sentinel: value in a list of values that indicates end of data Special value that cannot be confused with a valid value, e.g., -999 for a test score Used to terminate input when user may not know how many values will be entered

Slide 5- 61

Slide 5- 62

Slide Outline Increment and Decrement while loop do-while loop for loop nested for loop

Slide Nested Loops A nested loop is a loop inside the body of another loop Inner (inside), outer (outside) loops: for (row=1; row<=3; row++) //outer for (col=1; col<=3; col++)//inner cout << row * col << endl;

Example for (int i = 1; i <= 5; i++) // start outer loop { cout << "\n i is now " << i << endl; for (int j = 1; j <= 4; j++) // start inner loop cout << " j = " << j; // end of inner loop } // end of outer loop The first loop, controlled by the value of i, is called the outer loop. The second loop, controlled by the value of j, is called the inner loop. For each single trip through the outer loop, the inner loop runs through its entire sequence. Thus, each time the i counter increases by 1, the inner for loop executes completely.

Output Below is the output from the previous nested loop: i is now 1 j = 1 j = 2 j = 3 j = 4 i is now 2 j = 1 j = 2 j = 3 j = 4 i is now 3 j = 1 j = 2 j = 3 j = 4 i is now 4 j = 1 j = 2 j = 3 j = 4 i is now 5 j = 1 j = 2 j = 3 j = 4

Example Use a nested loop to compute the average grade for each student in a class of 20 students. Each student has taken four exams during the course of the semester. The final grade is calculated as the average of these examination grades.

Example The outer loop in our program will consist of 20 passes. Each pass through the outer loop is used to compute the average for one student. The inner loop will consist of 4 passes. One examination grade is entered in each inner-loop pass. As each grade is entered, it is added to the total for the student, and at the end of the loop, the average is calculated and displayed.

const int NUMGRADES = 4; const int NUMSTUDENTS = 20; int main ( void ) { double grade = 0.0, total = 0.0, average = 0.0; for (int i = 1; i <= NUMSTUDENTS; i++) // start outer loop { total = 0; for (int j = 1; j <= NUMGRADES; j++) // start inner loop { cout << "Enter an exam grade for this student: "; cin >> grade; total = total + grade; } // end inner loop average = total / NUMGRADES; cout << "\nThe average for student " << i << " is " << average << "\n\n"; } // end of outer loop return 0; }

Note: Pay attention to the initialization of total within the outer loop, before the inner loop in entered. Total is initialized 20 times, once for each student. Also note that the average is calculated and displayed immediately after the inner loop is finished. Because the statements that compute and print the average are also contained within the outer loop, 20 averages are calculated and displayed. Output: Enter an exam grade for this student: 99 Enter an exam grade for this student: 87 Enter an exam grade for this student: 56 Enter an exam grade for this student: 78 The average for student 1 is 80 Enter an exam grade for this student: 100 Enter an exam grade for this student: 99 Enter an exam grade for this student: 98 Enter an exam grade for this student: 97 The average for student 2 is 98.5 Etc…..

Slide Nested Loops - Notes Inner loop goes through all repetitions for each repetition of outer loop Inner loop repetitions complete sooner than outer loop Total number of repetitions for inner loop is product of number of repetitions of the two loops.

Slide Breaking Out of a Loop Can use break to terminate execution of a loop Use sparingly if at all – makes code harder to understand and debug When used in an inner loop, terminates that loop only and goes back to outer loop

Slide Breaking Out of a Loop Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end.

Breaking Out of a Loop The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown:

Fixed Repetition Versus Variable Condition Loops Fixed repetition loops are used when it can be determined in advance how often a segment of code needs to be repeated. For instance, you might know that you need a predetermined number of repetitions of a segment of code for a program that adds the integers from 1 to 100 or for a program that uses a fixed number of data lines, for example, game statistics for a team of 12 basketball players. The for loop is considered a fixed repetition loop.

Fixed Repetition Versus Variable Condition Loops Variable condition loops are needed to solve problems for which conditions change within the body of the loop. These conditions can involve sentinel values or arithmetic expressions. A variable condition loop provides more power than a fixed repetition loop. The while and the do-while loops are variable condition loops.

Choosing the Correct Loop “Which type of loop should I choose?” – A question often faced by programmers. A partial answer is: if a loop is to be repeated a predetermined number of times during execution, a for loop is preferable. If the number of repetitions is not known, one of the variable control loops is preferred.

Choosing the Correct Loop “Which type of loop should I choose?” The more difficult part of the answer is deciding which variable control loop is appropriate. Simply stated: – if a control check is needed before the loop is executed, use a while loop. – If the check is needed at the end of the loop, use a do- while loop. Remember, however, that a do-while loop must always be executed at least once. – Therefore, if there is a possibility that the loop will never be executed, a while loop must be used.

Slide Deciding Which Loop to Use while : pretest loop; loop body may not be executed at all do-while : posttest loop; loop body will always be executed at least once for : pretest loop with initialization and update expression; useful with counters, or if precise number of repetitions is needed

String Input with getline The >> (extraction operator) cannot be used to enter a string containing spaces. #include using namespace std; int main() { string name; cout << “Please enter your full name: “; cin >> name; cout << “Your name is: “ << name; return 0; } I/O: Please enter your full name: Mary Jones Your name is: Mary

String Input with getline To solve this problem, the string library provides the function getline. This function reads characters, including tabs and spaces, from an input stream into a string variable until a newline (‘\n’) character is detected. The newline character is not stored in the string variable. The syntax for the getline function is: getline(, );

String Input with getline Thus the following segment of code would allow a name containing spaces to be entered from the keyboard. int main() { string name; cout << “Please enter your full name: “; getline(cin, name); cout << “Your name is: “ << name; return 0; } I/O: Please enter your full name: Mary Jones Your name is: Mary Jones

String Input with getline Because getline does not ignore leading white space characters, you should take special care when using it in conjunction with >> (extraction operator). Consider the following example: int main( ) { string name; int age; cout << "Please enter your age: "; cin >> age; cout << "Please enter your full name: "; getline(cin, name); cout << name << ", you are " << age << endl; return 0; } I/O: Please enter your age: 25 Please enter your full name:, you are 25

String Input with getline This program segment will allow the user to enter the age. It then prompts for the name but displays the results immediately without pausing for the input of the name. The reason is that >> (extraction operator) reads and stores characters up to the newline character in age. getline then detects this newline character as the first character “in” the input of the name, so it returns with an empty string before the user can enter any characters. There are two ways to avoid this problem: Reverse the order of the inputs, with getline being called before >>. A call to getline can come after another call to getline, but never after a call to >>. Thus, you can correct the code as follows:

String Input with getline int main( ) { string name; int age; cout << "Please enter your full name: "; getline(cin, name); cout << "Please enter your age: "; cin >> age; cout << name << ", you are " << age << endl; return 0; } I/O: Please enter your full name: Mary Jones Please enter your age: 25 Mary Jones, you are 25

String Input with getline In cases where at least one call of >> must come before a call of getline, you must “consume” the trailing newline character first. A simple way to do this is to declare a “dummy” string variable and run getline with it after the >> operation. This has the effect of “throwing away” the extra newline character before the next call to getline. A correct code segment that uses this method is:

int main( ) { string name, dummy; int age; cout << "Please enter your age: "; cin >> age; getline(cin,dummy); cout << "Please enter your full name: "; getline(cin, name); cout << name << ", you are " << age << endl; return 0; } I/O: Please enter your age: 25 Please enter your full name: Mary Jones Mary Jones, you are 25 *Note: We use >> when we want to read a single word into a string variable, and we use getline when we want to read an entire line of words into a string variable.