do while loop in c


Explanation of do while loop in c programming language by examples, questions and answers


It is also called as post tested loop. It is used when it is necessary to execute the loop at least one time. Syntax:

do {
Loop body
} while (Expression);

Example:

void main(){
    int num,i=0;
    clrscr();
    do{
         printf("To enter press 1\n");
         printf("To exit press  2");
         scanf("%d",&num);
         ++i;
         switch(num){
             case 1:printf("You are welcome\n");break;
             default : exit(0);
         }
    }
         while(i<=10);
    getch();
}

Output: 3 3 4 4

If there is only one statement in the loop body then braces is optional. For example:

(a)
void main(){
    double i=5.5678;
    clrscr();
    do
         printf("hi");
    while(!i);

    getch();
}

Output: 3 3 4 4

(b)
void main(){
    double i=5.63333;
    clrscr();
    do
         printf("hi");
    while(!i);

    getch();
}

Output: hi

(c)
void main(){
       int x=25,y=1;
       do
     if(x>5)
         printf(" ONE");
     else if(x>10)
         printf(" TWO");
     else if(x==25)
         printf(" THREE");
     else
         printf(" FOUR");
       while(y--);
    getch();
}

Output: ONE ONE

break keyword in c:

It is keyword of c programming. Task of this keyword is to bring the control from out of the loop in the case of looping. For example:

void main(){
    int i;
    clrscr();
    for(i=0;i<=4;i++){
         printf("%d",i);
         break;
         printf("Label 1");
    }
    printf("Label 2");
    getch();
}

Output: 0Label2

Another task of break keyword is to switch the control from one case to another case in case of switch case control statement. For example:

void main(){
    int i=0;
    clrscr();
    ++i;
    switch(i){
         case 1:printf("case 1");
         case 2:printf("case 2");break;
         case 3:printf("case 3");
         default: printf("default");
    }
    getch();
}

Output: case 1case 2

In any other case we cannot use break keyword.

void main(){
    float a=5.5f;
    clrscr();
    if(a==5.5){
         printf("equal");
    }
    else{
         break;
    }

    getch();
}

Output: Compilation error

For loop
While loop
break and continue
Nested loop

C tutorial home.

2 comments:

  1. why we can not use break in else block
    it give error ...???

    ReplyDelete
  2. Could you please give me more explanation? Why the output of the first example is 3 3 4 4 and the first example of 'break keyword in c' is 0Label2.

    ReplyDelete