• Home
  • For Loop in C with Example

For Loop in C with Example

The for loop is a control flow construct that allows you to execute a block of code repeatedly, with a specified number of iterations. The syntax for a for loop is as follows:

for (initialization; condition; increment/decrement) {
// code to execute
}

The initialization expression is executed once, before the loop starts. It is typically used to initialize a loop counter variable. The condition expression is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop is terminated. The increment/decrement expression is executed after each iteration of the loop. It is typically used to increment or decrement the loop counter variable.

Here is an example of a for loop in C:

#include <stdio.h>

int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d ", i);
}
printf("\n");
return 0;
}

In this example, the for loop iterates 10 times, from 0 to 9. The loop counter variable (i) is initialized to 0 before the loop starts, and is incremented by 1 after each iteration. The loop terminates when the value of i becomes 10 (i < 10 is false). The output of this code is “0 1 2 3 4 5 6 7 8 9”.

You can use a for loop to iterate through an array, as well. Here is an example:

#include <stdio.h>

int main() {
int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int i;
for (i = 0; i < 10; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}

In this example, the for loop iterates through the elements of the array, and prints out the values. The output of this code is “0 1 2 3 4 5 6 7 8 9”.

You can also use a for loop to iterate through a string, as shown in the following example:

#include <stdio.h>
#include <string.h>

int main() {
char str[10] = "Hello";
int i;
for (i = 0; i < strlen(str); i++) {
printf("%c", str[i]);
}
printf("\n");
return 0;
}

In this example, the for loop iterates through the characters of the string, and prints out the values. The output of this code is “Hello”.