For Loop
The for
loop in C provides a concise way to repeatedly execute a block of code. It is particularly useful when the number of iterations is known in advance. Let's explore the syntax and usage of the for
loop.
Basic Syntax of For Loop
Explanation of the Program:
The
for
loop is initialized with three parts:Initialization (
int i = 1
): It is executed only once at the beginning of the loop.Condition (
i <= 5
): The loop continues as long as this condition is true.Update (
i++
): Executed after each iteration.
The body of the loop contains the code to be executed in each iteration.
In this example, the loop prints "Iteration 1" to "Iteration 5" since
i
starts at 1 and increments by 1 in each iteration.
Looping Through Arrays
Here, the for
loop is used to iterate through an array (numbers
) and print each element along with its index.
Practical Tips
The loop variable (
i
in the examples) is typically used to control the number of iterations.Ensure that the loop condition has a clear termination point to avoid infinite loops.
The loop variable can be used for various purposes within the loop body.
Understanding and utilizing the for
loop is essential for efficient and concise iteration in C programming. If you have specific questions or if there are additional topics you'd like to explore, feel free to ask. Happy coding!