C do while loop

The "do-while" loop in C programming is a control structure that allows you to repeat a set of statements at least once and then repeatedly execute the statements as long as a certain condition is true. The "do-while" loop is useful when you want to execute a block of code at least once before checking the condition. In this article, we will take a look at how to use the "do-while" loop in C with three examples.

Example 1: Printing numbers from 1 to 10

The first example demonstrates how to use the "do-while" loop to print the numbers from 1 to 10. In this example, the loop variable "i" is initialized to 1, and the loop body is executed first before the condition "i <= 10" is tested. The loop will terminate when the condition is false, and the loop variable "i" is incremented by 1 after each iteration.

1#include <stdio.h> 2 3int main() { 4 int i = 1; 5 do { 6 printf("%d\n", i); 7 i++; 8 } while (i <= 10); 9 return 0; 10}

Output:

11 22 33 44 55 66 77 88 99 1010

Example 2: Summing the numbers from 1 to 100

In this example, we will use the "do-while" loop to calculate the sum of the numbers from 1 to 100. The loop variable "sum" is initialized to 0, and in each iteration, the value of "sum" is incremented by the value of "i". The loop will terminate when "i" reaches 101.

1#include <stdio.h> 2 3int main() { 4 int i = 1, sum = 0; 5 do { 6 sum = sum + i; 7 i++; 8 } while (i <= 100); 9 printf("The sum of the numbers from 1 to 100 is: %d\n", sum); 10 return 0; 11}

Output:

1The sum of the numbers from 1 to 100 is: 5050

Example 3: Printing the multiplication table of a number

In this example, we will use the "do-while" loop to print the multiplication table of a number entered by the user. The user will enter a number, and the program will use a nested "do-while" loop to print the multiplication table of that number. The outer loop will run 10 times, and the inner loop will run the number of times entered by the user.

1#include <stdio.h> 2 3int main() { 4 int i = 1, j, n; 5 printf("Enter a number: "); 6 scanf("%d", &n); 7 do { 8 j = 1; 9 do { 10 printf("%d x %d = %d\n", j, i, i * j); 11 j++; 12 } while (j <= n); 13 printf("\n"); 14 i++; 15 } while (i <= 10); 16 return 0; 17}

Output:

1Enter a number: 5 21 x 1 = 1 31 x 2 = 2 41 x 3 = 3 51 x 4 = 4 61 x 5 = 5 7 82 x 1 = 2 92 x 2 = 4 102 x 3 = 6 112 x 4 = 8 122 x 5 = 10 13 14... 15 1610 x 1 = 10 1710 x 2 = 20 1810 x 3 = 30 1910 x 4 = 40 2010 x 5 = 50