C For Loop Examples

1. Print Numbers from 1 to 10

#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
printf(“%d “, i);
}
return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10

2. Print Even Numbers from 2 to 20

#include <stdio.h>

int main() {
for (int i = 2; i <= 20; i += 2) {
printf(“%d “, i);
}
return 0;
}

Output:

2 4 6 8 10 12 14 16 18 20

3. Sum of First N Numbers

#include <stdio.h>

int main() {
int n, sum = 0;
printf(“Enter a number: “);
scanf(“%d”, &n);

for (int i = 1; i <= n; i++) {
sum += i;
}

printf(“Sum = %d\n”, sum);
return 0;
}

Sample Input/Output:

Enter a number: 5
Sum = 15

4. Factorial of a Number

#include <stdio.h>

int main() {
int n;
long factorial = 1;

printf(“Enter a number: “);
scanf(“%d”, &n);

for (int i = 1; i <= n; i++) {
factorial *= i;
}

printf(“Factorial of %d = %ld\n”, n, factorial);
return 0;
}

Sample Input/Output:

Enter a number: 5
Factorial of 5 = 120

5. Multiplication Table

#include <stdio.h>

int main() {
int n;
printf(“Enter a number: “);
scanf(“%d”, &n);

for (int i = 1; i <= 10; i++) {
printf(“%d x %d = %d\n”, n, i, n * i);
}

return 0;
}

Sample Input/Output:

Enter a number: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70

6. Nested for Loop Example – Pattern

Print a right-angle triangle:

#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
printf(“* “);
}
printf(“\n”);
}
return 0;
}

Output:

*
* *
* * *
* * * *
* * * * *

7. Key Points

  1. for loops are ideal when the number of iterations is known.

  2. Initialization, condition, and increment/decrement are in one line.

  3. Can be nested for patterns, tables, or multi-dimensional tasks.

  4. Loop variable can be declared inside or outside the loop.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *