C for loop

The "for" loop in C programming language is a control structure that allows you to repeat a set of statements a specified number of times. It is a convenient way to execute a block of code multiple times with a counter that increases or decreases with each iteration. In this article, we will take a look at how to use the "for" loop in C with three examples.

Example 1: Printing numbers from 1 to 10

The first example demonstrates how to use the "for" 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; 5 for (i = 1; i <= 10; i++) { 6 printf("%d\n", i); 7 } 8 return 0; 9}

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 "for" 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, sum = 0; 5 for (i = 1; i <= 100; i++) { 6 sum = sum + i; 7 } 8 printf("The sum of the numbers from 1 to 100 is: %d\n", sum); 9 return 0; 10}

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 "for" 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 "for" 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, j, n; 5 printf("Enter a number: "); 6 scanf("%d", &n); 7 for (i = 1; i <= 10; i++) { 8 for (j = 1; j <= n; j++) { 9 printf("%d x %d = %d\n", j, i, i * j); 10 } 11 printf("\n"); 12 } 13 return 0; 14}

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

for loop is an essential control structure in C programming. It provides a convenient way to repeat a set of statements a specified number of times. With the help of the examples discussed in this article, you can get a better understanding of how to use the "for" loop in C programming.