Topic 3 - Control Structure (Part 2) - 230726 - 105926
Topic 3 - Control Structure (Part 2) - 230726 - 105926
The initial statement usually initializes a variable (called the for loop
control, or for indexed, variable).
In C++, for is a reserved word.
THE for LOOP (CONT.)
Output:
THE for LOOP (CONT.)
1 2 4
for (int i = 1; i <= 3; i++)
Example (cont.)
Example (cont.)
Example (cont.)
Write a program segment that display all the numbers from 1 to 20.
Write a program segment that display all the even numbers from 10 to 50.
Outer loop
Inner loop
THE NESTED for LOOP (CONT.)
Output:
THE NESTED for LOOP (CONT.)
while (condition)
statement;
If you know exactly how many pieces of data need to be read, the while
loop becomes a counter-controlled loop
COUNTER-CONTROLLED while LOOP
(CONT.)
Output:
COUNTER-CONTROLLED while LOOP
(CONT.)
Write a program segment that display all the numbers from 1 to 20.
Write a program segment that display all the even numbers from 10 to 50.
Sentinel variables is tested in the condition and loop ends when sentinel
is countered
SENTINEL-CONTROLLED while LOOP
(CONT.)
Exercise 1: Write a segment to repeat a statement until the user enter the
sentinel value of ‘N’. The repeated statement is “Do you want to continue?
Y for Yes, N for No”
Exercise 2: Write a program segment that asks the user to input any
numbers until it reads 999 to stop. Then display the total of the numbers.
THE do...while LOOP
do
statement;
while (expression);
Example:
Output:
EXERCISES