• admin@embedclogic.com

Loop method In C

Loop In C

Loop method is used when we have to repeatedly execute some block of statements as long as the condition is true.

Loop flow chart

Let us take an example to understand the requirement of loop method –

So we can see that we have to write 5 times printf statement to print 5 times, hello and it can be more complex if we want to execute 1000 times or more while the use of for loop or any loop method makes it simple in just 2 lines whether it is 1000 or 1 million times.

To get rid of this problem C language introduces a powerful concept of loop method.By using Loop method we can write this code in two lines like this –

Types of Loop Method

There are following methods in loop category –

  1. for loop
  2. while loop
  3. do-while loop

for loop

syntax

expression1 which is the initialization of loop only execute at the first iteration of the loop.

expression2 is the conditional statement of the loop and it will check at the start of every iteration of the loop.if the condition is false then the loop will terminate otherwise execution of loop will continue.

expression3 is the increment/decrement of the loop count.it is the last statement of every iteration of the loop.

expression 1, expression 2, expression3 positions are not fixed.For loop has other ways to represent –

Example

check the all above syntax with this example and see the behavior.

while loop method

syntax

For Loop Syntax equivalent to while

Example

do-while loop method

Once the statement is to be executed whether the condition is true or false in the do-while loop method.

Therefore, the use of the do-while method is done in such a place, where we have to execute the statement once before the condition check.

Syntax