A do...while loop is a post tested loop that means, the body of do...while loop is executed at least once whether the condition is true or false. Then, the condition is checked. Let's first see the syntax of a do...while loop.
- How does a do...while loop work in C?
- Example 1: Printing numbers using do...while loop
- Example 2: printing multiplication table using do...while loop
- Read more about loop
Quick links:
Syntax: of do...while loop
do
{
//Statements inside the body of the loop
//increment (++) or decrement (--) operator
}while(condition test);
How does a do...while loop work in C?
Steps 1: The program control first executes the set of instructions within the do while block and then it validates the condition.
Steps 2: If the condition evaluates to true, then the set of instructions within the do while loop are executed again.
Steps :3 This execution of do while block is re-iterated until the condition evaluates to false. Once, the condition becomes false, the program control exits out of the do while loop and executes the other statements if any. Let's see the below example to understand it better.
Flow Chart of do...while loop:
do...while loop | welcome2protec.com |
Example 1: Printing numbers using do...while loop
#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of j is: %d\n", j);
j++;
}while (j<=3);
return 0;
}
Output:
Value of j is: 0
Value of j is: 1
Value of j is: 2
Value of j is: 3
Example 2: Program to print multiplication table using do...while loop
/*Program to print multiplication table of a number using do...while loop*/
#include <stdio.h>
#include <conio.h>
void main()
{
int num, limit;
int i = 1;
clrscr();
printf("Enter a number to print it's table: ");
scanf("%d", &num);
printf("Enter limit: ");
scanf("%d", &limit);
printf("\nHere is the multiplication table of %d: ", num);
do{
printf("%d * %d = %d\n", num, i, num * i);
i++;
}while(i <= limit);
getch();
}
Output:
Enter a number to print it's table: 5
Enter limit: 5
Here is the multiplication table of 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
- What is loop?
- For loop
- Nested for loop
- while loop
- Infinite or endless loop
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.