C do while loop

do while loop

In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of do while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using  statement. It means that the body of the loop will be executed at least once, even though the starting condition inside while is initialized to be false.The do-while statement is also known as the Exit control looping statement.

 Syntax

do 

{

statements; 

}while(condition);

 


 
Example

To add  integer number  until user enters zero.

#include <stdio.h>
#include <conio.h>
void main()
{
    int number, sum = 0;

    do
    {
        printf("\n Enter a number: ");
        scanf("%d", &number);
        sum += number;
    }
    while(number != 0);

    printf("\n Sum = %d",sum);

    getch();

Output


 Nested do while loop

In C programming language, one do-while loop inside another do-while loop is known as nested do -while loop

Syntax

statements

do
    {
      statements;
       do
         {
          statements;
         }while(condition);
    statements;
  }while(condition);



Example

Print multiplication table using nested do-while loop

 #include <stdio.h>
#include <conio.h>

int main()
{
    int i,j;
    i=1;
    printf("Multiplication table\n\n");
 do{
    j=1;
 do{
    printf("%d\t",i*j);
    j++;
 }while(j<=10);
    printf("\n");
    i++;
    }while(i<=10);
    getch();
    return 0;
    getch();
    }

 Output


 

 



No comments:

Post a Comment