for loop in c

A for loop in c offers more control than while and do-while. With a for loop, you can specify exactly how many times you want to loop; with while loops, you must continue looping as long as a condition is true

The format of for loop in c

for (startExpression; testExpression; countExpression)
{ block of one or more C statements; }

Example of for loop in c

for (ctr = 1; ctr <= 5; ctr++)
{
printf("Counter is at %d.\n", ctr);
}

for begins, the startExpression, which is ctr = 1;, executes. The startExpression is executed only once in any for loop. The testExpression is then tested. In this example, the testExpression is ctr<=5 ;If it is true—and it will be true the first time in this code—the body of the for loop executes. When the body of the loop finishes, the countExpression is executed (ctr is incremented).

Leave a Comment