C programming - for loop

https://w‮tfigi.ww‬idea.com

In C programming, the for loop is used for iterative or repetitive purposes. It allows a program to execute a set of statements repeatedly for a specified number of times. The basic syntax of the for loop is as follows:

for (initialization; condition; increment/decrement)
{
    // statements to be executed in each iteration
}

Here, the initialization expression is executed only once, at the beginning of the loop. It typically initializes a loop counter variable. The condition expression is tested at the beginning of each iteration, and if it evaluates to true, the statements within the loop are executed. The increment/decrement expression is executed at the end of each iteration, typically to increment or decrement the loop counter variable.

It's important to note that all three expressions in the for loop are optional. If the initialization expression is not used, a variable must be initialized before the loop. If the condition expression is not used, the loop will run indefinitely until the program is terminated or a break statement is used. If the increment/decrement expression is not used, the loop counter variable must be incremented or decremented within the loop statements.

Here's an example of using the for loop:

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

In this example, the loop counter variable i is initialized to 1, and the loop will execute as long as i is less than or equal to 10. In each iteration, the value of i is printed to the console using the printf function, and then i is incremented by 1. The loop will repeat until i is no longer less than or equal to 10.

It's also possible to nest one or more for loops within another for loop to perform more complex iterations. The nested loops will execute the inner loop completely for each iteration of the outer loop.