C++ Session 5
C++ Session 5
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 main() if (nam1==nam2)
{
{ cout<<"You got it right this time \n\n";
string nam1, nam2 = }
break;
"araba"; if(i == 3)
{
cout<<"Enter your name: "; cout<<"Sorry you done ";
break;
cin>> nam1; }
}
cout<<endl<<endl; cout<<endl<<endl;
cout<<"You entered: "<<nam1<<endl;
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
{
// Local variable declaration: Value of a: 12
int a = 10;
// do loop execution
Value of a: 13
do Value of a: 14
{
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’
int main () You got distinction would
{ 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
{
cout<<"Enter your name: ";
#include <iostream> cin>>name;
using namespace std;
cout<<"You are welcome "<<name;
counter++;
int main () cout<<endl;
{ if(name != "Amanda")
cout<<"Try again"<<endl;
string name; if(counter == 4)
int counter = 0; {
cout<<"You have entered " <<counter<<" times";
break;
// do loop execution }
}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 <?