4 - Structured Programming 1-11-2023
4 - Structured Programming 1-11-2023
Presented by:
1
Agenda
2
C++ For Loop
C++ For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:
C++ For Loop
C++ For Loop
• Statement 1 is executed (one time) before the execution of the code block.
• Statement 3 is executed (every time) after the code block has been executed.
C++ For Loop
C++ For Loop
Example explained
• Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true,
the loop will start over again, if it is false, the loop will end.
• Statement 3 increases a value (i++) each time the code block in the loop has been executed.
C++ For Loop
Another Example
This example will only print even values between 0 and 10:
C++ For Loop
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
C++ For Loop
The foreach Loop
There is also a "for-each loop" (introduced in C++ version 11 (2011), which is used exclusively to loop
through elements in an array (or other data sets):
C++ For Loop
The foreach Loop
The following example outputs all elements in an array, using a "for-each loop":
C++ Break and Continue
C++ Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.