C For Loop

1. What is a for Loop?

  • The for loop is used when you know how many times you want to repeat a block of code.

  • Syntax:

for (initialization; condition; increment/decrement) {
// code to execute repeatedly
}

Explanation of Parts:

Part Description
Initialization Sets up the loop control variable (executed once)
Condition Checked before each iteration; loop stops if false
Increment/Decrement Updates the loop control variable after each iteration

2. Simple Example – Print 1 to 5

#include <stdio.h>

int main() {
int i;

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

return 0;
}

Output:

1 2 3 4 5

3. Loop in Reverse – Print 5 to 1

#include <stdio.h>

int main() {
int i;

for (i = 5; i >= 1; i--) {
printf("%d ", i);
}

return 0;
}

Output:

5 4 3 2 1

4. Multiplication Table Using for Loop

#include <stdio.h>

int main() {
int n = 7;
int i;

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

return 0;
}

Output:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70

5. 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

6. Nested for Loops – Print a Pattern

#include <stdio.h>

int main() {
int i, j;

for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}

return 0;
}

Output:

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

7. Key Points

  1. for loop is ideal when the number of iterations is known beforehand.

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

  3. Can be nested for patterns, matrices, or complex iterations.

  4. Loop variables 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 *