FP Lecture 8
FP Lecture 8
By
Abdullah Khan Shahani
• Note: The braces enclosing the loop body can be omitted only if the
loop body contains one statement or none.
While Loop
• The variable count is initially 0. The loop checks whether (count <
100) is true. If so, it executes the loop body to display the message
Welcome to C++! and increments count by 1. It repeatedly executes
the loop body until (count < 100) becomes false (i.e., when count
reaches 100). At this point, the loop terminates and the next
statement after the loop statement is executed
• Loops are constructs that control repeated executions of a block of
statements. The concept of looping is fundamental to programming.
C++ provides three types of loop statements: while loops, do-while
loops, and for loops.
Flow Chart for while Loop
While loop
A for loop performs an initial action once, then repeatedly executes the statements in the loop
body, and performs an action after an iteration when the loop-continuation-condition evaluates
to true.
For Loop
• The loop control variable can be declared and initialized in
the for loop. Here is an example:
for (int i = 0; i < 100; i++)
{
cout << "Welcome to C++!\n";
}
The do-while loop executes the loop body first, then checks the loop-continuation-condition
to determine whether to continue or terminate the loop.
Do while loop
• Run this program and differentiate between while and do while
loop
Important: Which Loop to Use?
• You can use a for loop, a while loop, or a do-while loop, whichever
is convenient.
• In general, a for loop may be used if the number of repetitions is
known in advance, as, for example, when you need to display
message 100 times.
• A while loop may be used if the number of repetitions is not fixed,
as in the case of reading the numbers until the input is 0.
Task 2:
• Write a c++ code using for loop which print values from 1 to 5
using while loop
• Write a c++ code using for loop which print table of 2 using while
loop
• Write a c++ code which print first sum of ist five natural
numbers using for loop
• Write a code which reverse a number entered by user and
print original number and reverse number.
Next
Lecture
Nested
loop