Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
The do-while StatementFEROL JOHN NOHAY
do-while Statement• In this statement, the logical expression is tested in the end of each iteration instead of at the beginning.
• Post-Test loop – logical expression in each iteration is tested after the body of the loop.
• The do-while statement has 5 parts:• The reserved word (do)
• The statement on the body of loop
• The reserved word (while)
• The logical expression in the parenthesis
• Semicolon (required)
do-while Statement• Event-Controlled Loop
• At least One Iteration
The do-while loop is the recommended solution when a problem that the body of the loop be executed at least once.
do-while StatementExample: We want to write a program that extracts and prints the left-most digit of any nonnegative integer.
do-while Statement• Data Validation – should be included in a program whenever a user enters a data that must match a set of criteria.
• It ensures that the user have entered all of the required data in the proper format.
do-while StatementExample: when we change a numeric score to a grade, test scores are usually in the range of 0 and 100
Result: if value is valid
Result: if value is invalid.
More about Loops
Comparison of Three LoopsFeature While loop For loop Do-while loop
Test type Pre-test Pre-test Post-test
Primary Design
event-controlled counter-controlled event-controlled
Minimum Iterations
0 0 1
Number of test
n+1 n+1 n
Nested loop• Nested loop – a loop inside another loop. The inside loop does not have to be of the same type as the outside loop.
• Most used nested loop: for loop
• for loop (outer) : rows
• for loop (inner) : columns
Nested loopExample 1:
Nested LoopExample 2:
Other Related Statements
The return Statement• return statement – terminates the current function immediately and returns control to the function caller
• return statement in a loop – causes the loop to terminate and the function in which the loop is iterating to be terminated.
•Example: Determine if a number is composite or prime number. • Step 1: If the number is 1, the number is not a prime number.
• Step 2: If the number is divisible by any number less than itself, it is composite
The return StatementExample:
Result 1:
Result 2:
Result 3
The break Statement• Break statement – can be used in a loop or a switch statement.
- to come out a loop prematurely when we need to.
The continue Statement• The continue Statement – skips the remaining statements in the body of that statement and proceeds with the next iteration of the loop.
Try this!!• Using nested loop: for-loop
• Create a multiplication table wherein the user must input the size from 2 to 10.
• NOTE: use manipulator: setw(4) to set the field width.
• Hint: use do-while loop for Data Validation wherein it will ask the user if he/she has input the size greater than 10 or less than 2.
Try this!!Sample output:
NOTE: the first 2 lines accepts input (cin) from the user