Loops in C - for, while and do...while Loops

    1 Votes

In previous chapter of this C programming tutorial we've learned about decision making control statements. But what if we want to run a piece of code multiple times? Writing same code block multiple times is bothersome as well as a waste of time and energy of the programmer. But fear not, C has another control structure in its sleeve called looping.

Looping statement saves us from writing same code blocks again and again and executes the specific code block multiple times until some conditions are met. We may have known how many times we need to execute the code block or this decision could be made on the go. Looping has a solution for both cases.

There are mainly three types of loop statements available in C programming language. They are

  • 'for' loop
  • 'while' loop
  • 'do ... while' loop

Let's look at each of these loop statements in detail.

'for' Loop in C

Most commonly used loop statement in C programming language is 'for' loop. Syntax of 'for'loop is as given below.

for(initialize expression; test condition; index modification expression)
{
    Statement block
}	

The 'for'loop generally includes three expressions separated by semicolon (;),

  1. Init expression, which is executed first. You can initialize the loop control variable at this point. This expression is optional.
  2. Test condition is evaluated next. The body of loop is executed only if this condition evaluates to true. If this condition evaluates to false, the control moves to the next line after 'for' loop
  3. Index modification expression is executed after body of the loop. You can update the loop control variable at this location. After the execution of index modification expression, loop test condition is evaluated again and this procedure follows until the test condition is evaluated to false

'for' Loop Example in C

Suppose we want to print first 10 integers starting from 0. How we can write this using for loop? What will be the three expressions? Let’s look at the following program.

#include<stdio.h>
void main()
{
    int index;
    for(index = 0; index < 10; index++)
    {
        printf("%d\n", index);
    }
}

Output:

0
1
2
3
4
5
6
7
8
9

First, the initialize expression assigns the value 0 to 'index' variable. It declares that the loop will run with initial value 0. The second expression or test condition checks whether the value of the 'index' is less than 10 or not. The last expression modifies the 'index' variable, i.e. increments its value by 1. So, at start index is 0, the test condition is satisfied and the code block enclosed in braces is executed.

As a result, we get 0 in our screen and then a line feed. After the code block execution is finished, the third expression of 'for' loop gets executed and it increments the value of the 'index'. Again the control flow goes back to 'for' statement. But this time the value of the index does not revert back to 0 as initialization expression is executed only once i.e. at starting time of the loop. Next, the test condition is checked and now, the current value of the 'index', which is 1 satisfies the test expression. So, the 'printf' is executed and index 'index' incremented again. This is repeated until the index value is 10, when the test condition fails and execution will continue from the line following for loop code block, i.e. from the line after the closing brace.

The expressions of loop declaration are are separated by semicolons. All the expressions are not necessary, but the two semicolons are. You can omit one or two expressions or all three expressions and just leave two semicolons in the parenthesis and the code will compile normally and even run too.

The following lines are legal for 'for'loop in C language.

/*
Here the variable 'index' must be initialized before the loop, 
since the initialization is omitted from 'for' statement.
If the variable is not initialized prior to execution of 'for' loop, 
it would be containing garbage value and result in unexpected output.
*/
for(; index < 10; index++) 

/*
Here, both the initialization and loop control variable modification are omitted. 
The value of variable 'index' has to be modified as part of loop body, else the 
code will result in unexpected output since the test condition will always evaluate 
to a fixed value.
*/
for(; index <10; )

/*
Here, all the three expressions are omitted, and the loop will continue forever (infinite loop), 
unless you use the 'break' keyword explicitly in loop body.
*/
for(;;)

As part of 'for'loop you can initialize and modify more than one variable and can contain more than one increment or decrement statement, but they should be separated by comma (,). Consider the example below.

for(i = 0, j = 100; i < 10; i++)

In the above program, both of the variables, 'i' and 'j' would get initialized as part of the initialization statement.

'while' Loop in C

After 'for' loop, let's look at 'while' loop in C language. Unlike 'for' loop, 'while' loop contains only a single expression and it is used as the test condition. The initialization and modification expressions of 'for' loop is omitted in 'while' loop. The general syntax of 'while'loop is given below.

while(expression)
{
    statement block
}

If the 'expression' evaluates to true, i.e. it evaluates to a non-zero value, code in the 'statement block' gets executed. And after execution of 'statement block', the expression is evaluated again to check it's truth value and this process continues until the expression evaluates to false.

So if you place a non-zero value as the 'expression', 'while' loop executes infinitely unless you have an explicit 'break'statement as part of 'statement block'.

while(1) {
    statement block
}

In the above code snippet, the 'statement block' gets executed infinitely.

'while' Loop Example in C

We can write our program to print first 10 numbers using 'while'loop as given below

#include<stdio.h>
void main()
{
    int index = 0;
    while(index < 10)
    {
      printf("%d\n", index++);
    }
}

Output:
0
1
2
3
4
5
6
7
8
9

Here, the index is initialized during declaration and it is incremented inside 'while' code block. The 'while' statement contains only test condition (index < 10). Note that, here the increment is post-increment. So, the 'printf' will print the value starting from 0 up to 9 as index++ will return the present value of index and then increment it by 1.

In case of 'while' loop and 'for' loop if you omit the braces, then only the immediate statement will be considered as the loop body.

'do...while' Loop

'do...while' loop is similar to 'while' except that the loop test expression is evaluated after execution of the loop body. The syntax of 'do...while'is given below.

do
{
    Statement block	
} while(expression);	

Also, note that there is a semicolon (;) that is followed by while statement. Since the condition expression of 'do...while' is evaluated after the execution of loop body, it is guaranteed that the loop body will be executed at least once even if the text condition is false.

Also Read - Top C Interview Questions and Answers for Freshers & Advanced C Interview Questions and Answers

'do...while' Loop Example in C

Below program prints the first 10 numbers starting from 0.

#include<stdio.h>
void main()
{
    int index = 0;
    do
    {
       printf("%d\n", index++);
    } while(index < 10);
}

Output:
0
1
2
3
4
5
6
7
8
9

If you replace the while condition with while(0), you will still get output 0 printed on your screen, since the test condition is evaluated after execution of loop body.

Also Read - Top Embedded C Interview Questions and Answers & C++ Interview Questions and Answers

Entry Controlled Loops & Exit Controlled Loops

The 'for' loop and the 'while' loop are known as the entry controlled loops as the test condition is checked before executing the loop body. Because of that, if the test condition is evaluated to false, loop body will not get executed.

'do...while' loop is known as exit controlled loop since the loop test expression is evaluated after execution the loop body. Because of that the loop body will be executed at least once even if the test condition fails the first time.

Planning to do an MBA?
A quick all-in-one MBA entry manual for MBA Aspirants. Book covers
  • Possible MBA Tests & Exam Preparation
  • Tips to choose right MBA Program
  • Essay, Resume & Letter of Recommendation
  • MBA Interview Preparation
  • MBA Financial Planning
Price - 6.99$
 

Popular Videos

How to speak to people

How to speak so that people want to listen.

Got a tip or Question?
Let us know

Related Articles

C Overview and Basic Syntax
Data Types in C Language
C Qualifiers - Constant and Volatile type Qualifier
C Type Casting with examples - float to int / int to char / int to long
C Constants and Literals
C Operators - Arithmetic, Assignment, Relational and Logical
C Operators - Bitwise Operators and Conditional Operators
C Operator Precedence and Associativity Table with Examples
C Input and Output Statements
C Format Specifiers for printf and scanf
C Decision Making Control Structures - 'if', 'if - else', nested 'if', 'switch'
C 'break', 'continue' and 'goto' Statements to Control Program Flow
C Preprocessor Directives and Macros
C Functions Tutorial with Examples
C Arrays - Dynamic, 2d and Multidimensional with Examples
C Strings - Internal Working and Functions with example
C Pointers basics explained with examples
Structures in C Programming with Example
Unions in c programming with example
C Storage Class Specifiers - auto, register, static and extern