Similar presentations:
Introduction to programming – Lecture 4: iteration statements (loops)
1. Introduction to programming – Lecture 4: iteration statements (loops)
INTRODUCTION TO PROGRAMMING –LECTURE 4: ITERATION STATEMENTS (LOOPS)
Aigerim Aibatbek - Senior Lecturer
aigerim.aibatbek@astanait.edu.kz
2. Iteration Statement
ITERATION STATEMENTSuppose that you need to display a message "Welcome to C++!” 100 times.
100 times
100 times
…
…
It would be tedious to write the above statements 100 times! So, how do you solve the problem?
3. Iteration Statement
ITERATION STATEMENTUse Iteration statements (loops)!
The statement which forces another statement or a
group of statements to be executed repeatedly
Loops can execute a block of code as long as a
specified condition is reached.
Entry
Check the condition
If false -Exit
4. loops
LOOPSLoop types
For loop
While loop
Do while
loop
5. The For Loop
THE FOR LOOPSyntax:
Update counter
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1(Initialization): is executed (one time) before the
execution of the code block.
Statement 2 (Condition): defines the condition for executing the
code block.
Statement 3 (Incrementation): is executed (every time) after the
code block has been executed (the last action at each iteration)
The for-loop flow chart
6. The For Loop
THE FOR LOOPSuppose that you need to display a message "Welcome to C++!” 100 times.
100 times
…
7. The For Loop
THE FOR LOOPSome more examples:
Output:
Output:
Output:
8. The While Loop
THE WHILE LOOPSyntax:
while (condition) {
// code block to be executed
}
Update counter
The most straightforward looping structure
Any control variable manipulations are made inside of the
loop`s body
Initializations of control variables must be outside of the loop
The while-loop flow chart
9. The While Loop
THE WHILE LOOP1. Display message "Welcome to C++!” 100 times.
3. Display numbers in reversed order
2. Display counter values
4. Display the odd numbers between 1 and 10
10. The Do-While Loop
THE DO-WHILE LOOPSyntax:
do {
// code block to be executed
}
while (condition);
True
This loop will execute the code block first (at least once), before
checking if the condition is true
Then it will repeat the loop as long as the condition is true.
false
Any control variable manipulations are made inside of the loop`s body
Initializations of control variables must be outside of the loop
11. The Do-While Loop
THE DO-WHILE LOOP1. Display message "Welcome to C++!” 100 times.
3. Display numbers in reversed order
2. Display counter values
4. Display the odd numbers between 1 and 10
12. loops
LOOPSExample: Find the sum of the numbers from 1 to 100?
1 + 2 + 3 + 4 + …. + 100 = ?
31
2
6
1
3
0
And so on...
programming