Professional Documents
Culture Documents
While loop
• Syntax of while Loop
int main()
{
int num, i = 1, factorial = 1;
while (i<=num)
{
factorial *=i;
i++;
}
cout<< "Factorial of "<<num<<" is "<<factorial;
return 0;
}
Using break to stop the while loop
while (nam1 !=nam2)
#include <iostream> {
cout<<"You entered a wrong name\n\n";
#include <string> i ++;
cout<<"Try again: ";
using namespace std; cin>>nam1;
int i =1 ; }
return 0;
do while loop
• Unlike for and while loops, which test the loop
condition at the top of the loop,
the do...while loop checks its condition at the
bottom of the loop.
• A do...while loop is similar to a while loop,
except that a do...while loop is guaranteed to
execute at least one time
The syntax of a do...while loop in C++ is
• do
{
statement(s);
}while( condition );
.
do while loop cont.
• Notice that the conditional expression
appears at the end of the loop, so the
statement(s) in the loop execute once before
the condition is tested
• If the condition is true, the flow of control
jumps back up to do, and the statement(s) in
the loop execute again. This process repeats
until the given condition becomes false
#include <iostream> Example
using namespace std;
Value of a: 10
int main () Value of a: 11
{ Value of a: 12
// Local variable declaration:
int a = 10; Value of a: 13
// do loop execution Value of a: 14
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 15 );
return 0;
}
Condition is not met but code executes once
#include <iostream>
using namespace std; Value of a: 10
int main ()
{
int a = 10;
// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 9 );
return 0;
#include <iostream>
Example 2
using namespace std; If the grade entered is ‘b’
You got distinction would
int main ()
{
be displayed before the
char grade; code terminates
// do loop execution
do
{
cout<<"please enter your grade: ";
cin>>grade;
cout<<"You got a distintion \n";
}while( grade == 'a' );
return 0;
Do while, cont, do
{
#include <iostream> cout<<"Enter your name: ";
using namespace std; cin>>name;
}while(name != "Amanda");
return 0;
}
Assignment
• What is the output of the program when embedded
in a correct program with x declared to be of
variable type int.
• X = 10
while (x > 0)
{ cout<<x<<endl;
X -=3;
}
What output would be produced if > is changed to <?