C For Loop

Last Updated Nov 20, 2015, 07:00:14 PM





C for loop is used to execute a particular statement several times until the condition becomes FALSE

The for loop statement in c allow us to avoid writing redundant code.

Imagine, if you want to print a statement like you name printf("Your Name"); 10 times, what do you? Would you go ahead and write printf code 10 times? No. Although, you can do write it ten times, it is not a best practice. To solve similar type of problems, you can use for loop to write one single line of code to repeat a statement any no of times.

c for loop

Syntax



For loop statement in c requires three parts. Initialization, the condition and the afterthought

Initialization:

The initialization part is used to declare the required variables. In some cases, if we use multiple variables, we should use all variables of same type.

The initialization part executes in the first place

Condition

The condition part checks for a specific condition. This condition quits the loop when it encounter FALSE

When the loop encounter FALSE then it stops the execution and will jump to the next statement

AFTERTHOUGHT

The afterthought part is used to decrement or increment the loop control. This part is performed exactly once every tume the loop ends and repeats

Try It Now

In the above example, we have used for loop statement available in c programming to print the same statement five times. Meaning, we instrucuted the compiler to print SnoopCode five times with a loop condition.

Difference between for loop, while loop, do while loop?

A while loop will always evaluate the condition first.

A do/while loop will always execute the code in the do{} block first and then evaluate the condition

A for loop allows you to initiate a counter variable, a check condition, and a way to increment your counter all in one line.



for() or while() - which is BEST? - StackOverFlow

Other Loop Topics you might want to learn

while loop in C

do..while loop in C

nested loops in C