C for loop

A for loop in C is a control flow statement used to repeatedly execute a block of code a specified number of times. It is commonly used when you know in advance how many times the loop should run.

Syntax:


for (initialization; condition; update) {
    // Code to execute repeatedly
}

Explanation:

1. Initialization: Defines and initializes the loop control variable (this is executed only once at the beginning).

2. Condition: The loop keeps running as long as this condition is true.

3. Update: Updates the loop control variable after each iteration (e.g., increments or decrements it).

Example:


#include <stdio.h>

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

    return 0;
}

Output:

0
1
2
3
4

Example: Print the table of 2 through for loop


#include <stdio.h>

int main() {
        for (int i = 2; i <=20; i=i+2) 
        {
            printf("%d\n", i); // Prints the current value of i
        }

    return 0;
}

Output:

2
4
6
8
10
12
14
16
18
20

C for loop – Interview Questions

Q 1: What is a for loop in C?
Ans: A loop used when the number of iterations is known in advance.
Q 2: What are the three parts of a for loop?
Ans: Initialization, condition, and increment/decrement.
Q 3: Can a for loop run without all three expressions?
Ans: Yes, but semicolons must be present.
Q 4: Can we nest for loops?
Ans: Yes, one for loop can be inside another.
Q 5: What happens if the condition is false initially?
Ans: The loop body is not executed.

C for loop – Objective Questions (MCQs)

Q1. What is the correct syntax of a for loop in C?






Q2. How many times will this loop execute?

for (int i = 0; i < 5; i++) {
printf("%d", i);
}






Q3. What happens if the condition in a for loop is always true?






Q4. In a for loop, which part executes only once?






Q5. What is the output of this code?

for (int i = 1; i <= 3; i++)
printf("Hi ");






Related C for loop Topics