C For

Complete guidance of C 'for' loop.

C For Loop:

A 'for' loop is a control flow statement that allows you to repeatedly execute a block of code a specified number of times. The syntax of a for loop in C is as follows:

for (initialization; condition; increment/decrement) {
    // Code to be executed repeatedly
}

Here's an explanation of each part of the for loop:

Initialization: This part is typically used to initialize a loop control variable. It is executed only once when the loop begins.

Condition: This is a Boolean expression that determines whether the loop should continue executing or not. If the condition evaluates to true, the loop continues; if it evaluates to false, the loop terminates.

Increment/Decrement: This part is used to modify the loop control variable after each iteration. It is executed at the end of each iteration, just before the condition is checked again. You can use either an increment (i++) or a decrement (i--) operator here.

Here's an example of a for loop that counts from 1 to 5 and prints each number:

c Copy Code
#include <stdio.h>

int main() {
    int i;

    for (i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }

    return 0;
}

Explanation:

  • 'i' is initialized to 1.
  • The loop continues as long as 'i' is less than or equal to 5.
  • After each iteration, 'i' is incremented by 1.
  • The loop prints the value of 'i' and repeats until 'i' becomes 6, at which point the condition becomes false, and the loop terminates.
Output:
1
2
3
4
5

Note: You can customize the 'for' loop to fit your specific needs by adjusting the initialization, condition, and increment/decrement expressions.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.