C For Loop

The for loop is used when you know how many times to repeat. It keeps the start, the condition and the change in one line.

Syntax

for (initialization; condition; update) {
    // code to repeat
}
  • initialization runs once at the start.
  • condition is checked before each round.
  • update runs after each round.

Print 1 to 5

#include <stdio.h>

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

Output:

Output of the above program is

1 2 3 4 5

Multiplication table

#include <stdio.h>

int main(void) {
    int n = 7;

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

Output:

Output of the above program is

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

Sum of first 10 numbers

#include <stdio.h>

int main(void) {
    int sum = 0;

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

Output:

Output of the above program is

Sum = 55

Counting down and two variables

#include <stdio.h>

int main(void) {
    for (int i = 5; i >= 1; i--) {
        printf("%d ", i);
    }
    printf("\n");

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

Output:

Output of the above program is

5 4 3 2 1
i=0 j=10
i=3 j=7

Note: Declaring the variable inside the loop (for (int i = 0; ...)) works in C99 and later. It is limited to the loop only.

Next: C Nested Loops.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.