In this tutorial, we will learn about for loops in C. We will cover the basics of iterative execution using for loops.
A for loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop is typically used when the number of iterations is known before entering the loop.
The syntax for the for loop in C is:
for (initialization; condition; increment) {
// Code block to be executed
}
The for loop evaluates the initialization statement, then the condition. If the condition is true, the code block inside the loop is executed. After each iteration, the increment statement is executed, and the condition is re-evaluated. This process repeats until the condition becomes false.
i
.#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d ", i);
}
return 0;
}
1 2 3 4 5 6 7 8 9 10
n
and factorial
.n
.factorial
to 1.n
.#include <stdio.h>
int main() {
int n = 5;
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
printf("Factorial of %d is %d", n, factorial);
return 0;
}
Factorial of 5 is 120
arr
and an integer variable sum
.sum
to 0.arr
.#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += arr[i];
}
printf("Sum of the elements in the array is %d", sum);
return 0;
}
Sum of the elements in the array is 15