05 Lecture 05
05 Lecture 05
05 Lecture 05
Structured Programming
Dr. Mostafa Ibrahim El- Khalil
2022 - 2023
Lecture
Loop and Decisions
5
2
C++ Fundamentals
While Loop
The do Loop
If-else statement
Switch statement
3
While Loop
While loop is used when you don’t know how many times you want to do
something before you start the loop.
While Structure:
Test Expression
Loop Body
The body of the Loop is the code to be executed each time through the loop
4
While Loop
Create program asks the user to enter a series of numbers. When the number
entered is 0, the loop terminates.
5
While Loop
Create program asks the user to enter a series of numbers. When the number
entered is 0, the loop terminates.
6
While Loop
The loop variable (n in ENDON0) must be initialized before the loop begins
The loop body must also contain some statement that changes the value of the
loop variable; otherwise the loop would never end.
7
Do-While Loop
In a while loop, the test expression is evaluated at the beginning of the loop. If
the test expression is false when the loop is entered, the loop body won’t be
executed at all.
Sometimes you want to guarantee that the loop body is executed at least once,
no matter what the initial state of the test expression. When this is the case
you should use the do loop, which places the test expression at the end of the
loop.
8
Do-While Loop
Test Expression
9
Do-While Loop
Create program asks the user to enter to enter two numbers: a dividend (the
top number in a division) and a divisor (the bottom number). It then calculates
the quotient (the answer) and the remainder using the / and % operators, and
prints out the result.
10
Do-While Loop
11
«Decisions»
12
Decisions
if...else statement
Decisions
switch statement
13
The If statement
Test Expression
if Body
15
The If statement
If the number entered is not greater than 100, the program will terminate
without printing the second line !!!
16
The If…else statement
Test Expression
if ( )
{
if Body
}
else
{
else Body
}
17
The If…else statement
18
The If…else statement
19
The nested If…else statement
20
The nested If…else statement
21
The switch statement
If you have a large decision tree, and all the decisions depend on the value of
the same variable, then It is preferable to use the Switch statement instead of
the nested if-else statement.
22
The switch statement
23
The switch statement
24
25