For Loop in C: Efficient Iteration for Precise Control
The for loop in C language is used to iterate the statements or a part of the program several times.
For Loop in C
A for
loop in C is a control flow statement used to execute a block of code repeatedly until a specified condition becomes false. It's a common and efficient way to iterate over a sequence of values.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed
}
- Initialization: This part is executed once before the loop starts. It's typically used to initialize a loop variable.
- Condition: This expression is evaluated before each iteration. If it's true, the loop body is executed. If it's false, the loop terminates.
- Increment/Decrement: This part is executed after each iteration. It's typically used to update the loop variable.
Example:
for (int i = 0; i < 5; i++) {
printf("Hello, world!\n");
}
In this example:
i = 0
initializes the loop variablei
.i < 5
is the condition that checks ifi
is less than 5.i++
incrementsi
after each iteration.
Common Uses:
- Iterating over arrays or strings.
- Counting or summing values.
- Generating sequences of numbers.
- Implementing algorithms like bubble sort or selection sort.
Nested For Loops:
You can use nested for
loops to create more complex patterns or perform tasks that require multiple levels of iteration.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("(%d, %d)\n", i, j);
}
}
Key Points:
- The
for
loop is a control flow statement used for iteration. - It has three parts: initialization, condition, and increment/decrement.
- The loop body is executed as long as the condition is true.
- Nested
for
loops can be used to create complex patterns.