Download presentation
Presentation is loading. Please wait.
1
Looping III (do … while statement)
2
Outline do … while statement Review of looping
break and continue in loops CSCE 106
3
Repetition Repetition or looping provides for the repeated execution of part of the algorithm. CSCE 106
4
do … while Statement The do - while statement is similar to the while loop, but the do - while loop has the test at the end. General syntax: do { statement; } while ( loop repetition condition ) ; Notice the iterative part executes before the loop-test Convenient when at least one repetition of the loop body is required CSCE 106
5
Data-validation Loop do prompt for and read a data item
while data item is invalid E.g. { cout << “Enter number of employees: “; cin >> numEmp; } while (numEmp <= 0); do … while is very useful in validating input and only continue with the algorithm when correct range of input is provided. CSCE 106
6
Data-validation Loop (cont’d)
do { cout << “Please enter a number between 0 and 255”; cin >> number; } while (number < 0 || number > 255); This loop keeps repeating until a number is input between 0 and 255. CSCE 106
7
do … while and Menus do … while is also very useful to control a menu-driven program Displaying a list of choices for user to select from E.g. list of edit operations: D - Delete a substring F - Find a string I - Insert a string R - Replace a substring Q - Quit Enter D, F, I, R, or Q as your selection: Write the loop for the above menu in your notes. CSCE 106
8
Review of Looping C++ provides three statements for implementing loops
Use for to implement counting loops Use do … while to implement loops that must execute at least once Use while to code other conditional loops Remember that you could nest all types of loop statements when necessary. CSCE 106
9
break and continue in Loops
break and continue are two C++ reserved words. You have seen break before with the switch statement. It could be used in the body of a loop to give the same effect of jumping out of the body of the loop. continue reserved word is used to jump to the loop testing condition, and hence ignoring anything else in the rest of the loop body. Using break and continue in loops is considered to be bad programming practice. Please don’t use them. You are only requested to understand their effect. CSCE 106
10
break and continue in Loops (cont’d)
int k = 40; while (k < 100) { k += 10; if (k == 70) continue; if (k == 80) break; cout << "k = " << k <<'\n'; } cout << "Finished looping" << endl; Output k = 50 k = 60 Finished looping This slide gives you an example of a while loop with break and continue reserved words. CSCE 106
11
Next lecture will be about
Arrays CSCE 106
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.