Do... While Loop Notes
Do... While Loop Notes
INTRODUCTION
Like
conditional,
loop
is
while Loop
whether
the
test
The
variable
i (known as the loop control variable) is used in
three ways: it is initialized, tested, and updated.
int i = 0;
// Initialize
while (i < n)
// Test
{
cout << *\n;
i++;
// Update
}
All three things must be coordinated in order for
Exercise 1
1)
2)
do...while
The do...while Loop is similar to while loop with
one very important difference.
In while loop, check expression is checked at first
before body of loop but in case of do...while loop,
body of loop is executed first then only test
expression is checked.
That's why the body of do...while loop is executed
at least once.
Syntax:
The syntax of a do...while loop in C++ is:
do
{
statement(s);
}while( condition );
Example 1:
#include <iostream>
using namespace std;
int main ()
{
int a = 10;
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the
following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example 2:
C++ program to add numbers entered by user until user enters 0.
#include <iostream>
using namespace std;
int main() {
float number, sum = 0.0;
{
do
cout<<"Enter a number: ";
cin>>number;
sum += number;
} while(number != 0.0);
cout<<"Total sum = "<<sum;
return 0;
}
Output
Enter a number: 4.5
Enter a number: 2.34
Enter a number: 5.63
Enter a number: 6.34
Enter a number: 4.53
Enter a number: 5
Enter a number: 0
Total sum = 28.34
Exercise
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"Enter the Number :";
cin>>a;
int counter = 1;
do
{
cout<<"Execute Do While "<<counter<<" time"<<endl;
counter++;
}while (counter <= a);
return 0;
}
Sample Output
Enter the Number :6
Execute Do While 1 time
Execute Do While 2 time
Execute Do While 3 time
Execute Do While 4 time
Execute Do While 5 time
Execute Do While 6 time