≡ Menu

C Loops Explained with Examples (For Loop, Do While and While)

Loops are very basic and very useful programming facility that facilitates programmer to execute any block of code lines repeatedly and can be controlled as per conditions added by programmer. It saves writing code several times for same task.

There are three types of loops in C.

  1. For loop
  2. Do while loop
  3. While loop

1. For Loop Examples

Basic syntax to use ‘for’ loop is:

for (variable initialization; condition to control loop; iteration of variable) {
    statement 1;
    statement 2;
    ..
    ..
}

In the pseudo code above :

  • Variable initialization is the initialization of counter of loop.
  • Condition is any logical condition that controls the number of times the loop statements are executed.
  • Iteration is the increment/decrement of counter.

It is noted that when ‘for’ loop execution starts, first variable initialization is done, then condition is checked before execution of statements; if and only if condition is TRUE, statements are executed; after all statements are executed, iteration of counter of loop is done either increment or decrement.

Here is a basic C program covering usage of ‘for’ loop in several cases:

#include <stdio.h>

int main () {

    int i = 0, k = 0;
    float j = 0;
    int loop_count = 5;

    printf("Case1:\n");
    for (i=0; i < loop_count; i++) {
        printf("%d\n",i);
    }

    printf("Case2:\n");
    for (j=5.5; j > 0; j--) {
        printf("%f\n",j);
    }

    printf("Case3:\n");
    for (i=2; (i < 5 && i >=2); i++) {
        printf("%d\n",i);
    }

    printf("Case4:\n");
    for (i=0; (i != 5); i++) {
        printf("%d\n",i);
    }

    printf("Case5:\n");
    /* Blank loop  */
    for (i=0; i < loop_count; i++) ;

    printf("Case6:\n");
    for (i=0, k=0; (i < 5 && k < 3); i++, k++) {
        printf("%d\n",i);
    }

    printf("Case7:\n");
    i=5;
    for (; 0; i++) {
        printf("%d\n",i);
    }

    return 0;
}

In the code above :

  • Case1 (Normal) : Variable ‘i’ is initialized to 0; condition is to execute loop till ‘i’ is lesser than value of ‘loop_count’ variable; iteration is increment of counter variable ‘i’
  • Case2 (Using float variable) : Variable ‘j’ is float and initialized to 5.5; condition is to execute loop till ‘j’ is greater than ‘0’; iteration is decrement of counter variable ‘j’.
  • Case3 (Taking logical AND condition) : Variable ‘i’ is initialized to 2; condition is to execute loop when ‘i’ is greater or equal to ‘2’and lesser than ‘5’; iteration is increment of counter variable ‘i’.
  • Case4 (Using logical NOT EQUAL condition) : Variable ‘i’ is initialized to 0; condition is to execute loop till ‘i’ is NOT equal to ‘5’; iteration is increment of counter variable ‘i’.
  • Case5 (Blank Loop) : This example shows that loop can execute even if there is no statement in the block for execution on each iteration.
  • Case6 (Multiple variables and conditions) : Variables ‘i’ and ‘k’ are initialized to 0; condition is to execute loop when ‘i’ is lesser than ‘5’and ‘k’ is lesser than ‘3’; iteration is increment of counter variables ‘i’ and ‘k’.
  • Case7 (No initialization in for loop and Always FALSE condition) : Variables ‘i’ is initialized before for loop to ‘5’; condition is FALSE always as ‘0’ is provided that causes NOT to execute loop statement; iteration is increment of counter variable ‘i’.

Here is the output of the above program :

# ./a.out
Case1:
0
1
2
3
4
Case2:
5.500000
4.500000
3.500000
2.500000
1.500000
0.500000
Case3:
2
3
4
Case4:
0
1
2
3
4
Case5:
Case6:
0
1
2
Case7:

Loop can run infinitely if condition is set to TRUE always or no condition is specified. For example:

for (;;)

If loop contain only one statement then braces are optional; generally it is preferred to use braces from readability point of view. For example :

for (j=0;j<5;j++)
    printf("j”);

Loops can be nested too. There can be loop inside another loop. Given below is example for nested loop to display right angle triangle of ‘@’ symbol.

for (i=0; i < 5; i++)
{
    for (j=0;j<=i;j++)
    {
        printf("@”);
    }
}

Just like For Loops, it is also important for you to understand C Pointers fundamentals.

2. Do While Loop Examples

It is another loop like ‘for’ loop in C. But do-while loop allows execution of statements inside block of loop for one time for sure even if condition in loop fails.

Basic syntax to use ‘do-while’ loop is:

variable initialization;
do {
statement 1;
statement 2;
..
..
iteration of variable;
} while (condition to control loop)

I the pseudo code above :

  • Variable initialization is the initialization of counter of loop before start of ‘do-while’ loop.
  • Condition is any logical condition that controls the number of times execution of loop statements
  • Iteration is the increment/decrement of counter

Here is a basic C program covering usage of ‘do-while’ loop in several cases:

#include <stdio.h>
int main () {
int i = 0;
int loop_count = 5;

printf("Case1:\n");
do {
printf("%d\n",i);
i++;
} while (i<loop_count);

printf("Case2:\n");
i=20;
do {
printf("%d\n",i);
i++;
} while (0);

printf("Case3:\n");
i=0;
do {
printf("%d\n",i);
} while (i++<5);

printf("Case4:\n");
i=3;
do {
printf("%d\n",i);
i++;
} while (i < 5 && i >=2);
return 0;
}

In the code above :

  • Case1 (Normal) :Variable ‘i’ is initialized to 0 before ‘do-while’ loop; iteration is increment of counter variable ‘i’; condition is to execute loop till ‘i’ is lesser than value of ‘loop_count’ variable i.e. 5.
  • Case2 (Always FALSE condition) : Variables ‘i’ is initialized before ‘do-while’ loop to ‘20’; iteration is increment of counter variable ‘i’; condition is FALSE always as ‘0’ is provided that causes NOT to execute loop statements, but it is noted here in output that loop statement is executed once because do-while loop always executes its loop statements at least once even if condition fails at first iteration.
  • Case3 (Iteration in condition check expression) : Variable ‘i’ is initialized to 0 before ‘do-while’ loop; here note that iteration and condition is provided in same expression. Here, observe the condition is to execute loop till ‘i’ is lesser than ‘5’, but in output 5 is also printed that is because, here iteration is being done at condition check expression, hence on each iteration ‘do-while’ loop executes statements ahead of condition check.
  • Case4 (Using logical AND condition) : Variable ‘i’ is initialized before ‘do-while’ loop to ‘3’; iteration is increment of counter variable ‘i’; condition is execute loop when ‘i’ is lesser than ‘5’ AND ‘i’ is greater or equal to ‘2’.

Here is output for above program.

# ./a.out
 Case1:
 0
 1
 2
 3
 4
 Case2:
 20
 Case3:
 0
 1
 2
 3
 4
 5
 Case4:
 3
 4
#

Also, if you are interested, read about our earlier article on bitwise operators in C.

3. While Loop Examples

It is another loop like ‘do-while’ loop in C. The ‘while’ loop allows execution of statements inside block of loop only if condition in loop succeeds.

Basic syntax to use ‘while’ loop is:

variable initialization;
 while (condition to control loop) {
 statement 1;
 statement 2;
 ..
 ..
 iteration of variable;
 }

In the pseudo code above :

  • Variable initialization is the initialization of counter of loop before start of ‘while’ loop
  • Condition is any logical condition that controls the number of times execution of loop statements
  • Iteration is the increment/decrement of counter

Basic C program covering usage of ‘while’ loop in several cases:

#include <stdio.h>

int main () {

    int i = 0;
    int loop_count = 5;

    printf("Case1:\n");
    while (i<loop_count) {
        printf("%d\n",i);
        i++;
    }

    printf("Case2:\n");
    i=20;
    while (0) {
        printf("%d\n",i);
        i++;
    }

    printf("Case3:\n");
    i=0;
    while (i++<5) {
        printf("%d\n",i);
    }
    printf("Case4:\n");
    i=3;
    while (i < 5 && i >=2) {
        printf("%d\n",i);
        i++;
    }

    return 0;
}

In the code above:

  • Case1 (Normal) : Variable ‘i’ is initialized to 0 before ‘while’ loop; iteration is increment of counter variable ‘i’; condition is execute loop till ‘i’ is lesser than value of ‘loop_count’ variable i.e. 5.
  • Case2 (Always FALSE condition) : Variables ‘i’ is initialized before ‘while’ loop to ‘20’; iteration is increment of counter variable ‘i’; condition is FALSE always as ‘0’ is provided that causes NOT to execute loop statements and loop statement is NOT executed. Here, it is noted that as compared to ‘do-while’ loop, statements in ‘while’ loop are NOT even executed once which executed at least once in ‘do-while’ loop because ‘while’ loop only executes loop statements only if condition succeeds.
  • Case3 (Iteration in condition check expression) :Variable ‘i’ is initialized to 0 before ‘while’ loop; here note that iteration and condition is provided in same expression. Here, observe the condition is execute loop till ‘i’ is lesser than ‘5’ and loop iterates 5 times. Unlike ‘do-while’ loop, here condition is checked first then ‘while’ loop executes statements.
  • Case4 (Using logical AND condition) :Variable ‘i’ is initialized before ‘while’ loop to ‘3’; iteration is increment of counter variable ‘i’; condition is execute loop when ‘i’ is lesser than ‘5’ AND ‘i’ is greater or equal to ‘2’.

Below is output for above program.

# ./a.out
Case1:
0
1
2
3
4
Case2:
Case3:
1
2
3
4
5
Case4:
3
4
#
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Robert Phillips December 5, 2012, 2:18 pm

    Hi Himanshu —

    I’m just starting to learn C. Found your website last week. This is my first email ‘tip’ from you.

    I was puzzled at the output for Case 3 in both the DO-WHILE and WHILE loops, even after running the code. I was thinking that i was incremented, then checked that it was <5. Finally got it. I know this tutorial is about loops but may I suggest that it would be pedagogically useful in this context to provide a Case 3 and a Case 3A, with the only difference being a postfix increment in the WHILE condition check in one (as you now have it) and a prefix increment in the other. I did that and learned – or saw confirmed – one more bit of the C puzzle.

    Thanks for the loops tutorial. I look forward to more.

  • Yuvaraj.A December 5, 2012, 10:07 pm

    Hi HIMANSHU,

    It us helping me to recall the big ‘C’.

    I would like to note some points here.

    Actually the syntax for loops in c are as below.

    For for Loop:

    for (expr1; expr2; expr3)

    For while Loop:

    while (expr1)

    For do-while

    do {
    }while (expr1);

    Here expr1, expr2, expr3 are valid expressions in c.

    In your case you mentioned like only variable initialization can be there in place of expr1 in for Loop.

    For example the below program is also valid one.

    int main()
    {
    int i=0;
    for(1; i<4; i++){
    printf("i = %d\n", i);
    }
    }

  • Rahul December 5, 2012, 11:40 pm

    Thanks , this a very handy reference. Bookmarked 🙂

  • Marc-Andre December 11, 2012, 1:47 am

    @Yuvaraj.A

    In the example you gave:

    int main()
    {
    int i=0;
    for(1; i<4; i++){
    printf("i = %d\n", i);
    }
    }

    the 1 in the for instruction does nothing actually, it could be leaved blank. Actually, by initialization, we mean that the expression before the first semi-colon will be only evaluated or executed once in the loop at the beginning.

    The second one must be a predicate i.e. it must return a value that can be considered as true or false and it will be evaluated everytime before entering the loop.

    The third expression is an instruction that is executed at the end of the last instruction in the loop is executed but before the evaluation of expr2 for the next loop iteration.

    Actually, expr1 and expr3 can be more than one instructions, separated by a comma. e.g.

    for(int i=0, j=0 ; j<5 ; printf("i = %d\n", i), j++,i+=2*j);

    is a valid (ugly) for loop

  • DuskoKoscica February 8, 2013, 4:43 am

    First of all, I like to explain the break, continue, and don’t forget the goto, exit and some other things….
    I will look more carefully at this because I don’t have so much time, but U should have explain more things to people,
    Also there should be examples, that are more complex, as well as examples for people to do them bay them self.
    Did Yo explain this thing
    for( ; ; ;), or while(true){ }
    Please, analyze the Daff’s thing, machine or what so ever…

  • Abhishek January 13, 2016, 12:06 am

    I can’t understand this c++ system,loops.

  • Ankush Sharma February 3, 2016, 10:36 pm

    thanks a lot for sharing these knowledge. This tutorial is easy to understand.

  • acinaj yam February 9, 2016, 3:32 am

    how can we get this output by using while loop in c# program?
    1
    121
    12321
    1234321
    123454321

  • Anonymous April 13, 2016, 10:23 pm

    how can i get
    *
    **
    ***
    ****
    *****
    using do while loop in c

  • Unknown April 16, 2016, 11:54 am

    Ok, and this is how!

    First apprach is to use two for and it will be pretty obvious >
    one star,
    two stars,
    three stars,
    four stars,
    and five stars.

    If you like to have one for, it might be done with some strings and fillings….

    Not 99% sy//***rrrr***er w*-*-h+/*at is your desire>

  • Elsa Bautista May 14, 2016, 7:56 pm

    how can I do this program,
    (make a program that input 6 numbers and then output the following.
    a. total of all 6 numbers.
    b. total of all positive numbera.
    c. how many are between 50 and 100,inclusive.)
    can anyone answer this because I badly need the solution in my problem.

  • Tariku May 19, 2016, 11:24 pm

    it good !!

  • Raman June 5, 2016, 12:21 am

    Can anyone please give me one program example on nested loop?

  • deva January 5, 2017, 3:10 am

    How can we get numerical examples of (for,do,while)loops.

  • maniteja February 20, 2017, 12:24 am

    can we implement for loop with out intialization ,increment and decrement and give one example?can we implement for loop with out intialization,condition ,increment and decrement and give one example?