Lecture 15 – Loops (do-while)

do-while loop

There’s a drawback in the while loop, that is if we need to execute the loop for at least one time then we cannot do it unless the condition is true. C provides us with a construct which helps us achieve this.

Syntax

do

{

// Statements to be executed

}while(condition);

A labeled diagram . . .

 


Figure 4 - Breakup of a do-while loop

With while loop
With do-while loop
Example 27 - Display name five times using do-while loop

Output
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
#include <stdio.h>


#include <conio.h>
void main()
{
int count=1;
clrscr();
while(count<=5)
                {
                printf(“\nHammad Naqvi”);
                count++;
                }
getch();
}

Output
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
#include <stdio.h>
#include <conio.h>
void main()
{
int count=1;
clrscr();
do
                {
                printf(“\nHammad Naqvi”);
                count++;
                }while(i<=5);
getch();
}

Table 10 - Comparison of while and do-while loop

In above example you can see the difference of the syntax; but the true potential of do-while loop is shown in the following example. Consider a scenario where you want to create a calculator which will be iterative in nature. It would only be able to add the numbers entered by user.

Let’s code it

#include <stdio.h>

#include <conio.h>

void main()

{

char option=’y’;

float a, b;


Output
Welcome to my calculator
Enter first number (A) : 5
Enter second number (B) : 25
5 + 25 = 30
 
Do you want to continue adding numbers (y/n)? : y
Enter first number (A) : 52
Enter second number (B) : 7
52 + 7 = 30
 
Do you want to continue adding numbers (y/n)? : n
 
clrscr();

printf(“\nWelcome to my calculator”);

do

                {

                printf(“\nEnter first number (A) :”);

                scanf(“%f”, &a);

                printf(“\nEnter second number (B) :”);

                scanf(“%f”, &b);

                printf(“\n %f + %f = %f”, a, b, a+b);

printf(“\n\nDo you want to continue adding numbers (y/n)? :”);

                scanf(“%c”, &option);

                }while(option==’y’ || option ==’Y’);

getch();

}

Example 28 - Iterative calculator using do-while loop

 

 

Now! We’ve discussed all loop constructs which are available in C; let’s compare all of these so that we would be able to see what the differences between these three loop constructs are?

 

 

For
While
do-while

Table 11 - Comparison of for while and do-while loops

Comments

Popular posts from this blog

Lecture 17 – Functions (continued)

Lecture 6 – Operators in C (continued)

Lecture 10 – Decisions (if-else-if)