You are on page 1of 12

Programming Fundamentals

Lab
Lecture 5

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Do-while loop

 It’s a conditional loop statement


 Its like a while loop, but the condition is tested after executing the statements of the loop
 Do while loop execute one or more times
 The body of the loop is executed at least once before the condition is tested.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Syntax

do
{
statements ;

}
while ( condition ) ;

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Flow control

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Example
Print first ten natural numbers on screen by using do-while loop.

int main()
{
int n =1;
do
{
cout<<“Number is”<<n<<endl;
n++;
}
While(n<=10)
return 0;
}
Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
Task

 Write a program using do-while loop and print the sum of series given below
1 + ½ + 1/3 + ¼ + 1/5+ …. 1/45

 Write a program to print even numbers between 1-40 using do-while loop.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


int main()
{
float sum, n;
sum=0.0;
n=1.0;
do
{
sum=sum +1.0/n;
n++;
}
while(n<=45)
cout<<“The sum of series is :”<<sum;
return 0;
}

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Nested do-while

Write a program to print the output shown below using do-while loop.

11
12
13
21
22
23
31
32
33

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Nested do-while
#include <iostream>  
using namespace std;  
int main() {  
     int i = 1;    
         do{    
              int j = 1;          
              do{    
                cout<<i<<"\n";        
                  j++;    
              } while (j <= 3) ;    
              i++;    
          } while (i <= 3) ;     
}  
Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
Nested While

 Write a nested while loop program and display the loop execution cycle number.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


int main ()
{
int i = 0;
while(i < 3)
{
int j = 0;
while(j < 5)
{
cout << "i = " << i << " and j = " << j << endl;
j++;
}
i++;
}
return 0;
}Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
Task

Write a program to print the following pattern

*
* *
* * *
* * * *

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar

You might also like