C

Simplified tutorials to learn the popular basic language C

VB.Net

Learn the basic desktop development application language

CodeIgniter

One of the popular PHP three tier (MVC) framework

Do While Loop in C Programming


Abstraction:
        This programming tutorial explains the working of Do While loop in the concept of C programming



               We learnt 'while loop' in previous lesson. do while loop is almost same as while loop. Difference between while loop and do-while loop is a usual question in exams.

Like the name indicate 'do while' loop do something first while the condition is hold.
General format of do-while loop:
  
  do
    {
       Body of the loop;   
    }
   while (condition);


If you can’t understand anything, then this example will help you…

  • Program to print first 5 number using do while loop:
 #include<stdio.h>
 #include <conio.h>   
 int main()
  {
   int n=1;
  do
   {
    printf("%d\n",n);
    n++;
   }
  while (n<=5);
  getch();
 }

How this work?

At first, in ‘do’ block, printf and n++ works without checking any condition. After executing this block of codes, then ‘while’ condition is considered.

Difference between while loop and do while loop:

In while loop, body of the loop will execute if and only if the 'while' condition is satisfied, where as in do-while loop, body of the condition will execute at least once even the condition does not satisfied.

Example:

What will be the output of this program:

#include<stdio.h>
#include <conio.h>   
int main()
{
  int n=5;
  while (n<0)
  {
   printf("%d\n",n);
   n++;
  }
  getch();
 }
The condition ‘while(n<0)’ does not hold, because the value of n is 5.
So program does not display anything.
while loop in C: output

Same program in do while loop:


#include<stdio.h>
#include <conio.h>   
int main()
{
  int n=5;
  do
  {
   printf("%d\n",n);
   n++;
  }
  while (n<0);
  getch(); 
}


Here what will the output?
do
{
printf("%d\n",n);
}
Here ‘do’ block first print the value of n, ie 5,
Difference between while and do while loop

Then execute:   while (n<0);
Now check the condition. Here the while condition does not satisfied. But the 'do-loop' block should be executed its body at least once. So we got the output as 5 even the condition is false. But never print next numbers (due to n++), because the condition does not hold any more.

Another example for do while loop:

  • Print odd numbers between 20 and 35:
#include<stdio.h>
#include <conio.h>  
int main()
{
int n=20;
do
{
if(n%2==1)
printf("%d\n",n);
n++;
}
while (n<=35);
getch();
}

if(n%2==1)

we leant already about modules operator (%) in a previous lesson. Here program check every number in between 20 and 35, if a number % 2 become 1, then number should be an odd and prints that number.

while(n<=35);
Check the number limitation exceeding 35.


No comments:

Post a Comment