While and Do While Loop
While and Do While Loop
Loops in C++
PREPARED BY:
DR.NOURHAN MOHSEN
DR.REHAM NASSER
While and do….while loops
➢ In computer programming, loops are used to repeat a block of code.
For example, let's say we want to show a message 100 times. Then instead of writing the print
statement 100 times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and sophistication in our
programs by making effective use of loops.
while (condition) {
// body of the loop
}
➢ How it works??
return 0;
}
• In this program, the user is prompted to enter a number, which is stored in the
variable number.
• In order to store the sum of the numbers, we declare a variable sum and initialize it to
the value of 0.
• The while loop continues until the user enters a negative number. During each iteration,
the number entered by the user is added to the sum variable.
• When the user enters a negative number, the loop terminates. Finally, the total sum is
displayed.
➢ Example 3
// program that takes marks of 10 students as input. It calculates the class average and displays
it on the screen Using while loop.
#include <iostream>
using namespace std;
int main()
{
int marks, sum = 0, count = 0;
double avg;
while (count < 10)
{
cout << "Enter marks for student " << count + 1 << ": ";
cin >> marks;
sum += marks;
count++;
}
avg = double(sum) / count;
cout << "Class average is: " << avg << endl;
return 0;
}
➢ How it works??
1. We first declare variables for marks, sum, count, and avg, where sum and count are
initialized to 0.
2. We use a while loop to take input marks for 10 students. Inside the loop, we prompt
the user to enter marks for each student and add it to the sum variable. We also
increment count by 1.
3. After the loop, we calculate the class average by dividing the sum by the count
(converted to a double to obtain a decimal value).
4. Finally, we display the class average on the screen using the cout statement.
➢ C++ do...while Loop
The do...while loop is a variant of the while loop with one important difference: the body
of do...while loop is executed once before the condition is checked.
Its syntax is:
do {
// body of loop;
}
while (condition);
➢ how it works??
1. The body of the loop is executed at first. Then the condition is evaluated.
2. If the condition evaluates to true, the body of the loop inside the do statement is
executed again.
3. The condition is evaluated once again.
4. If the condition evaluates to true, the body of the loop inside the do statement is
executed again.
5. This process continues until the condition evaluates to false. Then the loop stops.
return 0;
}