For Loop
Introduction to C
Structure of a C Program
Variables and Data Types
Input and Output
Operators in C
Decision Making
If Statement
if...else Statement
Nested if Statement
Nested if...else Statement
Switch Statement
Loops
For Loop
While Loop
Do While Loop
Loop Comparison
Arrays
Strings
Functions
Function Types
Library Functions
User-Defined Functions
Recursion Function
Pointers
Structures
File Handling
Common Mistakes
Ideas
For Loop
The for Loop
What is a for Loop?
The for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. It is the most preferred loop when the number of iterations is known before entering the loop.
The for loop is unique because it manages the counter variable, the condition, and the update (increment/decrement) all in one place, making the code very readable.
Syntax
for (initialization; condition; increment/decrement) {
// Code to be repeated
}
// Code to be repeated
}
- Initialization: Executed only once at the start. Used to set the starting value of the counter.
- Condition: Evaluated before every loop. If True, the loop continues; if False, the loop ends.
- Increment/Decrement: Updates the counter after the code block has finished running.
Practical Examples
Example 1: Printing Numbers 1 to 5
for (int i = 1; i <= 5; i++) { printf("Count: %d\n", i); }
Example 2: Printing Even Numbers (Decrementing)
// Counting down from 10 to 2 for (int i = 10; i >= 2; i -= 2) { printf("%d is even\n", i); }
Quick Note: The variable
i is commonly used in loops (it stands for "index" or "iterator"), but you can name it anything that makes sense for your program!