C Loops – syntax, working & programs

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)
next statement (increment or decrements of counter)

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 (43 downloads)



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)
next statement ( increment or decrements counter)

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 (36 downloads)



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.


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 (38 downloads)


Related programs on loops to learn more:

C Program – Loops Example – Fibonacci Series up to N terms
C Program –Loops Example -To Find Factorial of Number N