C Loops – syntax, working & programs

In C, Loops are used in programming to repeat a specific block until some end condition is met. There are three loops in C programming:

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

for loop

Syntax of for loop

 

for-loop-C-programmingGeneral Form of the for Statement
for (expr1; expr2; expr3)
statement
next statement

How for loop works?

First expr1 is evaluated; typically expr1 is used to initialize the loop. Then expr2 is evaluated; if it is nonzero (true) then statement is executed, expr3 is evaluated, and control passes back to the beginning of the for loop again, except that evaluation of expr1 is skipped. The process continues until expr2 is zero (false), at which point control passes to next statement.

 

download code : Program-to-Print-1-to-10-&-Find-Sum-using-for-Loop.c(3 downloads)

output:

for-loop-demo
for-loop-demo

 


while loop

The syntax of a while loop is:

where, testExpression checks the condition is true or false before each loop.
General Form of while Statement
while (expr)
statement
next statement

How while loop works?

First expr is evaluated. If it is nonzero (true), then statement is executed, and control is passed back to the beginning of the while loop. The body of the while loop, namely statement, is executed repeatedly until expr is zero (false). At that point control passes to next statement.

download code : Program-to-Print-1-to-10-Find-Sum-using-While-Loop.c(5 downloads)

Output

while-loop-demo
while-loop-demo

 


do…while loop

The do while loop is same to the while loop with one important difference. The body of do…while loop is executed once, before checking the test expression. Hence, the do…while loop is executed at least once.

do…while loop Syntax


How do…while loop works?

The code block (loop body) inside the braces is executed once.

Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This process goes on until the test expression is evaluated to 0 (false).

When the test expression is false (nonzero), the do…while loop is terminated.

download code : Program-to-Print-1-to-10-&-Find-Sum-using-do-while-Loop.c(3 downloads)

output:

do-while-loop-demo
do-while-loop-demo

Download these programs on loops to learn more: