C while loop
The "while" loop in C programming language is a control structure that allows you to repeat a set of statements as long as a certain condition is true. It is a convenient way to execute a block of code multiple times until a specified condition is met. In this article, we will take a look at how to use the "while" loop in C with three examples.
Example 1: Printing numbers from 1 to 10
The first example demonstrates how to use the "while" loop to print the numbers from 1 to 10. In this example, the loop variable "i" is initialized to 1, and the condition "i <= 10" is tested in each iteration. The loop body will be executed as long as the condition is true, and the loop variable "i" is incremented by 1 after each iteration.
1#include <stdio.h> 2 3int main() { 4 int i = 1; 5 while (i <= 10) { 6 printf("%d\n", i); 7 i++; 8 } 9 return 0; 10} 11 12Output: 131 142 153 164 175 186 197 208 219 2210
Example 2: Summing the numbers from 1 to 100
In this example, we will use the "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 while (i <= 100) { 6 sum = sum + i; 7 i++; 8 } 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 "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 "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 while (i <= 10) { 8 j = 1; 9 while (j <= n) { 10 printf("%d x %d = %d\n", j, i, i * j); 11 j++; 12 } 13 printf("\n"); 14 i++; 15 } 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