Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loops A loop is a repetition control structure.

Similar presentations


Presentation on theme: "Loops A loop is a repetition control structure."— Presentation transcript:

1 Loops A loop is a repetition control structure.
body - statements to be repeated control statement - decides whether another repetition needs to be made leading decision loop - control statement before body trailing decision loop - control statement after body Counted loop- for Logical loop – while or do..while

2 Leading Decision prime the loop //START while (condition) //TEST {
body of loop – //ACTION group of one or more statements indent one level //RESTART } loops

3 When the expression is tested and found to be false, the loop is exited and control passes to the statement which follows the loop body. while LOOP FALSE Expression TRUE body statement

4 1-2-3-4 for While Loops Initial condition //START TEST - while(…)
ACTION (steps needed to solve the problem) RESTART (often the same as step 1) loops

5 Example cout <<"Do you want to play?(y/n)"; //START
cin >> ans; while ((ans == 'y') || (ans == 'Y'))// TEST { … //body // ACTION cout <<"Do you want to continue(y/n)?";//RESTART } cout <<"Thanks for playing! " << endl; loops

6 Loops Sentinel controlled
keep processing data until a special value is entered to indicate that processing should stop Read blood pressures until a special value (like -1) selected by you is read. Count Controlled keep processing data for a specified number of times Read 100 blood pressures. End-of-file Controlled keep processing data as long as there is more data in the file Read all the blood pressures from a file no matter how many are there Flag Controlled keep processing data while a flag condition is true Read blood pressures until a dangerously high BP (200 or more) is read. loops

7 A Sentinel-controlled Loop
Read numbers until -1, 999 Not always easy to determine sentinel value requires a "priming read" "priming read" means you read one set of data before the while

8 1-2-3-4 Sentinel Value Initial condition (START) TEST - while(…)
Get first value TEST - while(…) while (val != sentinel) ACTION RESTART- often the same as step 1 Get next value loops

9 // Sentinel controlled loop
total = 0; cout << "Enter the price of the item (-1 to stop ) ";//START cin >> itemPrice; while (itemPrice > 0) // while not sentinel TEST { total = total + itemPrice; // ACTION cout <<"Enter item price(-1 to stop ) "; // RESTART } cout << total;

10 Example cin >> number; while (number < 0) {
cout << "Enter positive values only! "; } loops

11 Reading from a file first open file (later)
infile points to file (can be any name) infile >> fahrTemp; 1 infile >> cityName >> fahrTemp; loops

12 Reading from a file with a sentinel value
infile >> fahrTemp; //read from a file start while (fahrTemp != 999) //test { celsTemp = (5 * (fahrTemp – 32))/9 ; //action cout << fahrTemp << celsTemp; infile >>fahrTemp; //restart } loops

13 End-of-File Controlled Loop
depends on fact that a file goes into fail state when you try to read a data value beyond the end of the file No trailer record while (there is a record) while (not end of file) while (infile) // this is c Computer indicates there are no more records by sending a signal to the program Must read record before entering loop – there may be no records

14 1-2-3-4 Reading from file START : Read first record
TEST- while (infile) ACTIONS RESTART - Read next record- often the same as step 1 loops

15 Example infile >> fahrTemp; //start while (infile) //test {
celsTemp = (5 * (fahrTemp – 32))/9;//actions cout << fahrTemp <<celsTemp; infile >> fahrTemp ; //restart } loops

16 // End-of-file controlled loop
//Open file total = 0; infile >> thisBP; // priming read Start while (infile) //test { total = total + thisBP; //action infile >> thisBP; // read another - restart loop } cout << total;

17 Do something a set number of times Need counter
Count-controlled loop Do something a set number of times Need counter initialize increment iteration counter - incremented during each iteration of the loop event counter - incremented each time a particular event occurs

18 1-2-3-4 Count Start: Initialize counter
Test - while (counter < limit) Actions Restart: Increment counter loops

19 Known Count //Print Hello 10 times int count ; count = 0; //start
while (count < 10) //test { cout << "Hello "; //action count = count + 1; //restart }

20 variable count //Print Hello 10 times int count ;
cout << "How many times should we print Hello?" cin >> count; while (count > 0) { cout << "Hello "; 3 count = count -1 ; 4 }

21 Accumulators and Counters
To find the average of a group of numbers-need running total and how many numbers Counter – storage area in which we count Initialize: count = 0; Increment: count = count + 1 or count++ Accumulator – storage area for keeping cumulative or running totals Initialize: total = 0; Update: total = total + number total_wages_paid = total_wages_paid + net_pay loops

22 Counter: initialize : count = 0; increment : count++;

23 Sentinel-Controlled While Loop
Adding a Counter to a Sentinel-Controlled While Loop int count; count = 0; // initialize cin >> item; while (item != sentinel) { count++; // increment Process(item); }

24 Accumulator: Initialize: total = 0; Update: total = total + num;

25 Adding a Running Total to a Sentinel-Controlled While Loop
cin >> item; while (item != Sentinel) { total = total + item; }

26 int thisBP, total, count ; //Open file count = 0; // initialize 1
infile >>thisBP ; while ( count < 100 && infile) { total = total + thisBP ; count= count + 1 infile >> thisBP; 4 } cout << "The total = " << total << endl; if (count != 0) cout << "The average is " << (float)total/count ; 26

27 Infinite Loop index = 1; while (index < 5)
cout << "Good Morning!“ << endl; loops

28 Never executed while (ans == "yes" ) { ….
cout << “Add another number? "; cin >> answer; } loops

29 Don't forget to prime the loop!
Initialize initial condition by reading in or setting value cin >> ans while (ans == 'y') index = 0 while (index < 10) infile >> name >> ssNum >>phone; //read record while (infile) loops

30 cout << "No numbers entered“ << endl; else
int count; float total, avg, num; total = 0; count = 0; infile >> num; while (infile) { total = total + num; count = count + 1; } if (count == 0) cout << "No numbers entered“ << endl; else avg = total/count; cout << "The average is “ << avg << endl; loops

31 Flag Controlled Loop countGoodReadings = 0;
isDangerous = false; // initialize Boolean flag while (!isDangerous)                                              //test {      cin >> thisBP;                                                  //action      if ( thisBP >= 200 )           isDangerous = true; // change flag value else           countGoodReadings++; } cout << countGoodReadings << endl;

32 Trailing Decision Loop
do { Body } while (condition); Test at the bottom Statements are executed at least once loops

33 Trailing decision loop
Body condition TRUE FALSE loops

34 Example do { cout << "Enter two numbers“;
cin >> num1 >>num2; cout <<num1 << " + " << num2 << " = " << num1+num2 << endl; cout << "Do you want to enter two numbers again? "; cin >> ans; } while (ans == "yes" ); loops

35 do { DisplayMenu(); cin >> choice; switch (choice) case 1: PlayBeginner(); break; case 2: PlayAdvBeginner(); break case 3: PlayIntermediate(); case 4: default: cout << “ Invalid option” << endl; } } while (choice != 4);

36 Counted loop Fixed number of iterations
Use a variable as a counter which starts at a specified number and increments the variable each time the loop is processed Repeats until the counter is greater than an ending number Beginning value, ending value, increment value loops

37 Counted Loop 1 2 4 for (initial step; cond; expression) body (3)
for (initial step; cond; expression) body (3) Automatic: initial step: counter = initVal Check cond: counter < finalVal 3. If true execute body, else exit 4. Expression: counter++ Back to 2 loops

38 Examples for (count = 1; count <= 10; count++)
cout <<"Hello“ << endl; cout << count << endl; for (num = 10; num > 0; num--) cout >>num cout << "Blast off“ << endl; loops

39 Nested Loops placing of one loop inside the body of another loop is called nesting. When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop.   All types of loops may be nested, the most commonly nested loops are for loops. When working with nested loops, the outer loop changes only after the inner loop is completely finished

40 NESTED LOOPS

41 Exercises: Show screen output: for (outer = 0; outer < 2; outer++) {      for (inner = 0; inner <=2; inner++)     {         cout<< outer<< '\t' << inner << '\n';      } } Show screen output: for (outer = 0; outer < 3; outer++) {      for(inner = 2; inner <=4; inner++)     {           cout<< inner << ' ';      }      cout<< '\n'; }

42 3. The following set of nested loops is NOT working
3. The following set of nested loops is NOT working. Can you find what is wrong?? for (ctr1 = 1; ctr1 <=10; ctr1++); {       for(ctr2 = 1; ctr2 <=5; ctr2++)      {            number = ctr1 * ctr2;            cout<< number << '\n';      } }   4.  Show the output for the following program fragment: for (ctr1 = 8; ctr1 > 5; ctr1--) {      for(ctr2 = 1; ctr2 < 3; ctr2++)      {            cout<<ctr1<<" "<<ctr2<<" ";       }       cout<<"\n"; } 5.  Show the output: for(j=0; j<=5; j++) {      for(k=1; k<=j; k++)      {           cout<<"&";      }      cout<<"\n"; } 

43 6.  Write a program using nested loops to produce the following design:
     *      **      ***      ****      *****      ****** 7.  Write a program using nested loops to produce the following design:      A      AB      ABC      ABCD      ABCDE      ABCDEF    8.  Write a program using nested loops to produce a rectangle of *'s with 6 rows and  20 *'s per row.


Download ppt "Loops A loop is a repetition control structure."

Similar presentations


Ads by Google