The for loop in C is a control flow statement that allows you to execute a block of code repeatedly for a fixed number of times or based on a condition. It is particularly useful for iterating over arrays, lists, and performing repetitive tasks.
for (initialization; condition; increment/decrement) {
// Code to be executed
}
• Initialization: Sets up the loop control variable.
• Condition: Evaluated before each iteration; if true, the loop continues; if false, the loop ends.
• Increment/Decrement: Updates the loop control variable after each iteration.
he flowchart for a for loop in C illustrates the process:
1. Initialization: Set up the loop control variable.
2. Condition Check: Evaluate the loop condition.
• If true, proceed to execute the loop body.
• If false, exit the loop.
3. Execution: Execute the loop body.
4. Update: Modify the loop control variable.
5. Repeat: Go back to the condition check.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d\\n", i);
}
return 0;
}
1
2
3
4
5
#include <stdio.h>
int main() {
int i, number;
// Prompt user for input
printf("Enter a number: ");
// Check if input is successfully read
if (scanf("%d", &number) != 1) {
printf("Invalid input. Please enter an
integer.\\n");
return 1; // Return error code
}
// Print multiplication table
for (i = 1; i <= 10; i++) {
printf("%d x %d = %d\\n", number, i, number *
i);
}
return 0;
}
Enter a number: 3
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 5; i++) { // Number of rows
for (j = 1; j <= i; j++) { // Print stars in each
row
printf("*");
}
printf("\\n"); // Move to the next line
}
return 0;
}
*
**
***
****
*****
• Initialization: Typically used to set a loop control variable.
• Condition: Evaluated before each iteration; if false, the loop terminates.
• Increment/Decrement: Used to update the loop control variable each iteration.
• Scope of Variables: The loop control variable is local to the for loop block unless defined outside.