for loops in C Language:
For Loops in C
The for
loop in C is a control flow statement for specifying iteration, which allows code to be executed repeatedly. The syntax of a for
loop is:
for (initialization; condition; increment) {
// statements
}
Basic For Loop
A basic for
loop consists of an initialization, a condition, and an increment/decrement.
#include
int main() {
for (int i = 0; i < 5; i++) {
printf("i = %d\n", i);
}
return 0;
}
For Loop with Multiple Variables
You can use multiple variables in the initialization and increment parts of a for
loop.
#include
int main() {
for (int i = 0, j = 5; i < j; i++, j--) {
printf("i = %d, j = %d\n", i, j);
}
return 0;
}
Infinite For Loop
A for
loop can run indefinitely if the condition is always true.
#include
int main() {
for (;;) {
printf("This loop will run forever.\n");
break; // Remove this break statement to see the infinite loop
}
return 0;
}
For Loop with Empty Body
A for
loop can have an empty body, which is useful for performing operations within the initialization, condition, or increment parts.
#include
int main() {
int sum = 0;
for (int i = 1; i <= 10; sum += i, i++);
printf("Sum of first 10 natural numbers is %d\n", sum);
return 0;
}
Nesting of For Loops
You can nest for
loops within each other to perform more complex iterations.
#include
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("i = %d, j = %d\n", i, j);
}
}
return 0;
}
Examples
Here are some additional examples demonstrating the usage of for
loops in C:
Example: Printing an Array
#include
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Example: Multiplication Table
#include
int main() {
int n = 5;
for (int i = 1; i <= 10; i++) {
printf("%d * %d = %d\n", n, i, n * i);
}
return 0;
}
Example: Matrix Multiplication
#include
int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{2, 0}, {1, 2}};
int c[2][2] = {0};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}