Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Introduction to Loop

2 Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while (condition) { statement(s); } The {} can be omitted if there is only one statement in the body of the loop 5-2 No ; here

3 How the while Loop Works while (condition) { statement(s); } condition is evaluated – if (condition) is true, the statement(s) are executed, and then condition is evaluated again – if (condition) is false, the loop is exited 5-3

4 while Loop Flow of Control 5-4 true statement(s) false condition

5 while Loop Example int val = 5; while (val >= 0) { cout << val << " "; val--; } produces output: 5 4 3 2 1 0 5-5

6 while Loop is a Pretest Loop while is a pretest loop ( condition is evaluated before the loop executes) If the condition is initially false, the statement(s) in the body of the loop are never executed If the condition is initially true, the statement(s) in the body continue to be executed until the condition becomes false 5-6

7 Exiting the Loop The loop must contain code to allow condition to eventually become false so the loop can be exited Otherwise, you have an infinite loop (i.e., a loop that does not stop) Example infinite loop: x = 5; while (x > 0) // infinite loop because cout 0 5-7

8 Common Loop Errors Don’t forget the { } : int numEntries = 1; while (numEntries <=3) cout << "Still working … "; numEntries++; // not in the loop body Don’t use = when you mean to use == while (numEntries = 3) // always true { cout << "Still working … "; numEntries++; } 5-8

9 Using the while Loop for Input Validation Here's the general approach, in pseudocode Read an item of input. While the input is invalid Display an error message. Read the input again. End While 5-9

10 Input Validation Loop Example cout << "Enter a number (1-100) and" << " I will guess it. "; cin >> number; while (number 100) { cout << "Number must be between 1 and 100." << " Re-enter your number. "; cin >> number; } // Code to use the valid number goes here. 5-10

11 Flowchart

12 Input Validation Example

13 In-Class Exercise Do Lab 7, Exercise 1, No. 1 – pg. 105 Do Lab 7, Exercise 1, No. 2 – pg. 105

14 Refer to Lab 7, Exe. 2, No. 1 in pg. 120. Solve the problem Change the input validation to use the following psuedocode Read an item of input. While the input is invalid Display an error message. Read the input again. End While In-class Exercise

15 Counter-Controlled Loop Initialization of counter before entering the loop: for example: counter = 0 Testing of counter value: counter > n Updating of counter value (increment or decrement of counter) during each iteration: for example: counter=counter+1 5-15

16 Pseudo code to C++ 1.Start 2.Set sum=0, counter = 0 3.While (counter <10) 1.Sum=sum+counter 2.Counter=counter+1 4.End_While 5.Display sum 6.End #include using namespace std; int main() { int sum = 0, counter=0; while(counter<10) { sum+=counter; counter++; } cout<<sum; return 0; }

17 In-Class Exercise Do Lab 7, Exercise 1, No. 3, pg – 125 Develop a program to calculate an average weight of 15 students input by the user. Develop a program to print even numbers between 1 to 50.

18 Letting the User Control the Loop Program can be written so that user input determines loop repetition Can be used when program processes a list of items, and user knows the number of items User is prompted before loop. Their input is used to control number of repetitions 5-18

19 User Controls the Loop Example int num, limit; cout << "Table of squares\n"; cout << "How high to go? "; cin >> limit; cout << "\n\nnumber square\n"; num = 1; while (num <= limit) { cout << setw(5) << num << setw(6) << num*num << endl; num++; } 5-19

20 In-Class Exercise Convert the following pseudo code to C++ 1.Start 2.Set product = 1, number = 1, count = 20 3.Calculate: lastNumber = 2 * count – 1 4. while (number <= lastNumber) 1.Product = product * number 2.Number = number + 2 5.End_While 6.Display product

21 Sentinel Value 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

22 Example #include using namespace std; int main() { int data, sum=0; cin>>data; while (data !=0) { sum+=data; cin>>data; } cout<<"The sum" <<sum<<endl; return 0; }

23 In-Class Exercise #include using namespace std; int main() { int num1, num2; char again; while(again=='y' || again=='Y') cin>>num1 ; cin>> num2; cout<< (num1+num2); cin>>again; return 0; }

24 In-Class Exercise Do Lab 7, Exercise 1, No. 4 – pg. 106 Write a program to read a character and a number. The program will print number of copies for the input character. – Input Example: Enter a character: F Enter a number: 4 -Output Example: F F F F

25 5.5 The do-while Loop do-while : a post test loop ( condition is evaluated after the loop executes) Format: do { 1 or more statements; } while (condition); 5-25 Notice the required ;

26 do-while Flow of Control 5-26 statement(s) condition false true

27 do-while Loop Notes Loop always executes at least once Execution continues as long as condition is true ; the loop is exited when condition becomes false Useful in menu-driven programs to bring user back to menu to make another choice 5-27

28 In-Class Exercise Using the do..while loop, write a program to read a character and a number. The program will print number of copies for the input character. – Input Example: Enter a character: F Enter a number: 4 -Output Example: F

29 5.6 The for Loop Pretest loop that executes zero or more times Useful for counter-controlled loop Format: for( initialization; test; update ) { 1 or more statements; } 5-29 No ; goes here Required ;

30 for Loop Mechanics 5-30

31 for Loop Flow of Control 5-31 true statement( s) false test initialization code update code

32 for Loop Example int sum = 0, num; for (num = 1; num <= 10; num++) sum += num; cout << "Sum of numbers 1 – 10 is " << sum << endl; 5-32

33 for Loop Notes If test is false the first time it is evaluated, the body of the loop will not be executed The update expression can increment or decrement by any amount Variables used in the initialization section should not be modified in the body of the loop 5-33

34 for Loop Modifications Can define variables in initialization code – Their scope is the for loop Initialization and update code can contain more than one statement – Separate statements with commas Example: for (int sum = 0, num = 1; num <= 10; num++) sum += num; 5-34

35 Example : for Loop int num1= 0, num2= 10; cout << "NUM1" << "\tNUM2" << endl; cout << "====" << "\t====" << endl; for (; num1<= 10; num1++, num2--) cout << num1 << "\t" << num2 << endl;

36 More for Loop Modifications (These are NOT Recommended) Can omit initialization if already done int sum = 0, num = 1; for (; num <= 10; num++) sum += num; Can omit update if done in loop for (sum = 0, num = 1; num <= 10;) sum += num++; Can omit test – may cause an infinite loop for (sum = 0, num = 1; ; num++) sum += num; 5-36

37 Can omit loop body if all work is done in header counter = 1; for(; ;) { if(counter<=number) { sum += counter; counter++; } else break; }

38 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 5-38

39 Sentinel Example int total = 0; cout << "Enter points earned " << "(or -1 to quit): "; cin >> points; while (points != -1) // -1 is the sentinel { total += points; cout << "Enter points earned: "; cin >> points; } 5-39

40 Using for loop for Sentinel- Controlled loop char answer; cout<<"\nDo you want to continue? (y/n): "; for(cin>>answer; answer!='y' && answer !='Y'&&answer!='n' &&answer!='N'; cin>>answer) cout<<"Please type y or n: ";

41 In-Class Exercise Do Lab 7, Exercise 1, No 10 (pg. 112) Do Lab 7, Exercise 1, No. 12 (pg. 112) Do Lab 7, Exercise 1, No. 14 (pg. 114) Do Lab 7, Exercise 1, No. 15 (pg. 114) Do Lab 7, Exercise 2, No. 2 (pg. 122) Do Lab 7, Exercise 2, No. 3 (pg. 123)

42 In-Class Exercise The distance a vehicle travels can be calculated as follows: distance = speed * time For example, if a train travels 40 miles per hour for 3 hours, the distance traveled is 120 miles. Write a program that asks the user for the speed of a vehicle (in miles per hour) and how many hours it has traveled. The program should then use a loop to display the distance the vehicle has traveled for each hour of that time period. Here is an example of the output: What is the speed of the vehicle in mph? 40 How many hours has it traveled? 2 HourDistance Traveled --------------------- 1 40 2 80

43 Using a Loop to Read Data From a File A Loop can be used to read in each piece of data from a file It is not necessary to know how much data is in the file Several methods exist to test for the end of the file 5-43

44 Using the eof() Function to Test for the End of a File eof() member function returns true when the previous read encountered the end of file; returns false otherwise Example: datafile >> score; while (!datafile.eof()) { sum += score; datafile >> score; } 5-44

45 Problems Using eof() For the eof() function to work correctly using this method, there must be a whitespace (space, tab, or [Enter] ) after the last piece of data Otherwise the end of file will be encountered when reading the final data value and it will not be processed 5-45

46 Using the >> Operation The stream extraction operator ( >> ) returns a value indicating if a read is successful This can be tested to find the end of file since the read “fails” when there is no more data Example: while (datafile >> score) sum += score; 5-46

47 Deciding Which Loop to Use while : pretest loop (loop body may not be executed at all) do-while : post test loop (loop body will always be executed at least once) for : pretest loop (loop body may not be executed at all); has initialization and update code; is useful with counters or if precise number of repetitions is known 5-47

48 Nested Loops A nested loop is a loop inside the body of another loop Example: for (row = 1; row <= 3; row++) { for (col = 1; col <= 3; col++) { cout << row * col << endl; } 5-48 outer loop inner loop

49 Notes on Nested Loops Inner loop goes through all its 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. In previous example, inner loop repeats 9 times 5-49

50 In-Class Exercise How many times the outer loop is executed? How many times the inner loop is executed? What is the output? #include using namespace std; int main() { int x, y; for(x=1;x<=8;x+=2) for(y=x;y<=10;y+=3) cout<<"\nx = " <<x << " y = "<<y; return 0; }

51 Breaking Out of a Loop Can use break to terminate execution of a loop Use sparingly if at all – makes code harder to understand When used in an inner loop, terminates that loop only and returns to the outer loop 5-51

52 Example 1 : use of break int count = 0; while (count++ < 10) { cout << count << endl; if (count == 5) break; } cout << “end of while loop\n”;

53 Example 2 : use of break for (int row = 0; row < 5; row++) { for (int star = 0; star < 20; star++) { cout << '*'; if (star == 8) break; } cout << endl; }

54 The continue Statement Can use continue to go to end of loop and prepare for next repetition – while and do-while loops go to test and repeat the loop if test condition is true – for loop goes to update step, then tests, and repeats loop if test condition is true Use sparingly – like break, can make program logic hard to follow 5-54

55 Example : use of continue int testVal = 0; while (testVal++ < 10) { if (testVal == 4) continue; cout << testVal << " "; } output of the loop is 1 2 3 5 6 7 8 9 10

56 Creating Good Test Data When testing a program, the quality of the test data is more important than the quantity. Test data should show how different parts of the program execute Test data should evaluate how program handles: – normal data – data that is at the limits the valid range – invalid data 5-56

57 In-Class Exercise Do Lab 7, Exercise 1, No. 17 (pg. 115) Do Lab 7, Exercise 1, No. 19 (pg. 116) Do Lab 7, Exercise 1, No. 20 (pg. 117) Do Lab 7, Exercise 2, No. 5 (pg. 124) Do Lab 7, Exercise 3, No. 7 (pg. 128)

58 In-Class Exercise Do Lab 7, Exercise 1, No. 24 (pg. 119) Do Lab 7, Exercise 1, No. 25 (pg. 120) Do Lab 7, Exercise 2, No. 6 (pg. 125)


Download ppt "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."

Similar presentations


Ads by Google