c do while loop

www.lau‮tt‬uri.com
c do while loop

The do while loop is very similar to the while loop, but with one difference.
In a while loop, we first check the conditions, and then execute the loop body if the conditions are met.
In the do while loop, we first execute the body of the loop, and then check the conditions.
Therefore, a do while loop ensures that the loop body executes at least once.
The following is the syntax of the do while loop.

do {
  //code...
} while (condition);

We use the 'do' and 'while' keywords to create a do while loop.
As long as the condition is met, the body of the loop is executed.
In the following example, we will use a do while loop to print 1 to 5.

#include <stdio.h>
int main(void)
{
  //variable
  int count = 1;
  
  //loop
  do {
    printf("%d\n", count);
    
    //update
    count++;
    
  } while (count <= 5);
  
  printf("End of code\n");
  return 0;
}
1
2
3
4
5
End of code

The difference between a while loop and a do-while loop

In the following example, we will get an integer value from the user.
If the value is less than or equal to 10, we execute the body of the loop.

while loop

#include <stdio.h>
int main(void)
{
  //variable
  int count;
  
  //user input
  printf("Enter an integer: ");
  scanf("%d", &count);
  
  //loop
  while (count <= 10) {
    printf("%d\n", count);
    count++;
  }
  
  printf("End of code\n");
  return 0;
}

run it

Enter an integer: 10
10
End of code

run it again:

Enter an integer: 11
End of code

do-while

#include <stdio.h>
int main(void)
{
  //variable
  int count;
  
  //user input
  printf("Enter an integer: ");
  scanf("%d", &count);
  
  //loop
  do {
    printf("%d\n", count);
    count++;
  } while (count <= 10);
  
  printf("End of code\n");
  return 0;
}

run:

Enter an integer: 10
10
End of code

excute it second time:

Enter an integer: 11
11
End of code
Created Time:2017-08-22 15:35:00  Author:lautturi