Close
Close

Loops in C


We are assuming that you are practicing a lot. If not, then go to the practice section before proceeding. First solve a good number of problems of all the topics covered so far and then come back. In case of any doubt, ask your question in the discussion section.

while Loop


What if someone asks you to print 'Hello World' 10 times?

One way is to write the printf statement 10 times. But that is definitely not a good choice if you have to write it 50 times!

So, here comes the while loop.

#include <stdio.h>
int main()
{
    int a = 1;
    while ( a <= 10 )
    {
        printf ( "Hello World\n" );
        a ++;
    }
    return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Now, let's understand each line of the code.

First, have a look at the syntax of a while loop.

while(condition)
{
    statement(s)
}

while loop checks whether the condition written in '( )' is true or not.
If the condition is found true, then statements written in the body of the while loop i.e., inside the braces { } are executed. Then, again the condition is checked, and if found true then statements in the body of the while loop are executed again. This process continues until the condition becomes false.

For better understanding, let's understand our example step by step.

In our example, firstly, we assigned a value of 1 to a variable 'a'.

while(a <= 10) checks the condition 'a <= 10'. Since the value of a is 1 which is less than 10, the statements of while (within the braces { }) are executed.

'Hello World' is printed and a++ increases the value of 'a' by 1. So, now the value of 'a' becomes 2.

Now, again the condition is checked. This time also a <= 10 is true because the value of 'a' is 2. So, again 'Hello World' is printed and the value of 'a' increased to 3.

When the value of 'a' becomes 10, again the condition a <= 10 is true and 'Hello World' is printed for the tenth time. Now, a++ increases the value of 'a' to 11.

This time, the condition a <= 10 becomes false and the while loop terminates.

Wasn't that interesting?

while loop in c

The following animation will also help you to understand the while loop.

gif of while loop in c

Let's see one more example of while loop

#include <stdio.h>
int main()
{
    char choice = 'y';
    while(choice == 'y')
    {
        int a;
        printf("Enter a number to check odd or even\n");
        scanf("%d",&a);
        if(a%2==0)
        {
            printf("Your number is even\n");
        }
        else
        {
            printf("Your number is odd\n");
        }

        printf("Want to check more y for yes n for no\n");
        scanf(" %c",&choice);

    }
    return 0;
}
Output
Enter a number to check odd or even
2
Your number is even
Want to check more y for yes n for no
y
Enter a number to check odd or even
5
Your number is odd
Want to check more y for yes n for no
n

The loop will run until the value of 'choice' becomes different than 'y'. So, for the first time, it will run since 'choice' is 'y'. Then it will execute the codes inside the loop. At last, it will ask the user whether he wants to check more. And this can change the value of the variable 'choice' and may terminate the loop.

Note that the variable 'a' is defined inside the while loop and will be invalid outside that.

Another Loop - FOR


Let's go to our first example in while loop where we have to print 'Hello World' 10 times.

We can also do the same with for loop. But before that, let's look at the syntax of for loop.

for(initialization; condition; propagation)
{
    statement(s)
}

As stated, for is also a loop which repeats the codes inside its body. The code is repeated until the condition is true. Anything written in the place of initialization is executed only once and before starting the loop. The statement written at the place of propagation is executed after every iteration of the loop. Let's look at an example to understand it better.

#include <stdio.h>
int main()
{
    int a ;
    for ( a = 1 ; a <= 10 ; a ++ )
    {
         printf ( "Hello World\n" ) ;
    }
    return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Now let's see how for loop works.

for(a=1; a<=10; a++)

a=1 → This is the initialization of the loop and is executed once at the starting of the loop. Generally, it used to assign value to a variable. Here, 'a' is assigned a value 1.

a<=10 → This is the condition which is evaluated. If the condition is true, the statements written in the body of the loop are executed. If it is false, the statement just after the for loop is executed. This is similar to the condition we used in the while loop which was being checked again and again.

a++ → This is executed after the execution of the code in the body of for loop. In this example, the value of 'a' increases by 1 every time the code in the body of for loop executes. There can be any expression here which you want to run after every iteration of the loop.

In the above example, firstly a=1 assigns the value of 1 to the variable a.

Then condition a<=10 is checked. Since the value of 'a' is 1, therefore the code in the body of for loop is executed and 'Hello World' gets printed.

Once the codes in the body of for loop are executed, a++ is executed which increases the value of 'a' by 1. Now, the value of 'a' is 2.

Again the condition a<=10 is checked which is true because the value of 'a' is 2. Again codes in the body of for loop are executed and 'Hello World' gets printed and then the value of 'a' is again increased by 1 (a++).

When the value of 'a' becomes 10, the condition a <= 10 evaluates to true and 'Hello World' gets printed. Now, when a++ increases the value of 'a' to 11, the condition a<=10 becomes false and the loop terminates.

Don’t you think it’s just a different form of while loop? Yes, it is actually.

for and while in c

We can also skip any of the initialization, condition or propagation statements. Let's look at the following examples of writing the same code in different ways.

{
  int a = 1 ;
  for ( ; a <= 10 ; a ++ )
   {
     printf ( " Hello World " ) ;
   }
}

We can also write it as:

{
  int a ;
  for ( a = 1 ; a <= 10 ; )
   {
     printf ( " Hello World " ) ;
     a ++ ;
   }
}

Try these once.

Now let's see some examples of for loop.

#include <stdio.h>
int main()
{
    int a ;
    printf("Table of 12\n");
    for ( a = 1 ; a <= 10 ; a ++ )
    {
         printf ( "12*%d = %d",a,12*a ) ;
    }
    return 0;
}
Output
Table of 12
12*1 = 12
12*2 = 24
12*3 = 36
12*4 = 48
12*5 = 60
12*6 = 72
12*7 = 84
12*8 = 96
12*9 = 108
12*10 = 120

It is easy to understand. In the first iteration, the value of 'a is 1. So, 12*a is 12. In the second iteration, the value of 'a' is 2. So, 12*a is 24. And at last, 'a' is 10. So, 12*a is 120.

#include <stdio.h>
int main()
{
    int a,b,power,i ;
    power = 1;

    printf("To find a raised to the power b.\n give value of a");
    scanf("%d",&a);

    printf("Give value of b\n");
    scanf("%d",&b);

    for ( i = 1 ; i <= b ; i ++ )
    {
        power = power*a;
    }

    printf("Power of a'%d' raised to b'%d' is %d\n",a,b,power);
    return 0;
}
Output
To find a raised to the power b.
give value of a
5
Give value of b
4
Power of a'5' raised to b'4' is 625

To calculate ab, we have taken a variable 'power' and its initial value is 1.
In the first iteration, power = power*a will be power = 1*a. So, power will become 'a'.
In the second iteration, 'power' will be a*a i.e., a2
In the third iteration, 'power' will be a2*a i.e., a3.
So, in bth iteration, 'power' will be ab.

Nested loop


Like if/else, we can also use one loop inside another. This is called nesting of loops.

See this example to make it clear.

#include <stdio.h>
int main()
{
    int i;
    int j;

    for(i = 12;i<=14;i++)
    {/*outer loop*/

        printf("Table of %d\n",i);

        for(j = 1;j<=10;j++)
        {/*inner loop*/

            printf("%d*%d\t=\t%d\n",i,j,i*j);
        }
    }
    return 0;
}
Output
Table of 12
12*1    =    12
12*2    =    24
12*3    =    36
12*4    =    48
12*5    =    60
12*6    =    72
12*7    =    84
12*8    =    96
12*9    =    108
12*10    =    120
Table of 13
13*1    =    13
13*2    =    26
13*3    =    39
13*4    =    52
13*5    =    65
13*6    =    78
13*7    =    91
13*8    =    104
13*9    =    117
13*10    =    130
Table of 14
14*1    =    14
14*2    =    28
14*3    =    42
14*4    =    56
14*5    =    70
14*6    =    84
14*7    =    98
14*8    =    112
14*9    =    126
14*10    =    140

At the initial execution of the first, 'i' is 1 and thus, 'Table of 12' gets printed.

Now, the next statement is for(j = 1;j<=10;j++). So, executing this statement:

'j' is 1 and 12*1 = 12 will be printed.

Now, the second iteration of the inner loop will take place. 'i' is still 12 but 'j' will be increased to 2. So, 12*2 = 24 will be printed.

Coming to the last iteration of the inner loop, 'i' is still 12, and 'j' will be 10, so 12*10 = 120 will be printed.

Now, coming out of the outer loop, there is no statement after the inner loop, so 'i' will be increased to 13 (i++) for the next iteration of the outer loop and 'Table of 13' will be printed and things will be repeated with the value of 'j' equal to 13.

nested loop in C

It’s cool to see this working, isn’t it?

We can also initialize multiple variables and use multiple conditions and propagation steps in for loop by just using a comma ' , '

Let's see this working.

Suppose we have to change the values of a variable 'a' from 1 to 5 and the values of another variable 'b' from 5 to 1.

#include <stdio.h>
int main()
{
    int a ;
    int b ;
    for ( a = 1 , b = 5 ; a <= 5 , b >= 1 ; a ++ , b -- )
    {
         printf ( "a = %d\t b = %d\n" , a , b ) ;
    }
    return 0;
}
Output
a = 1    b = 5
a = 2    b = 4
a = 3    b = 3
a = 4    b = 2
a = 5    b = 1
'\t' is used to provide tabspace like '\n' gives a newline.

So, you must be having fun by now. You will have a lot more fun when you apply your coding skills in practical situations like games, websites, robots, etc.

do...while loop


It is just like the while and for loop but the only difference is that the code in its body is executed once before checking the condition.

do
{
  statement(s)
}
while(condition);

Now, let's see the same example of printing 'Hello World' 10 times but this time with do...while loop.

#include <stdio.h>
int main()
{
    int a = 1;
    do
    {
        printf( "Hello World\n" );
        a ++;
    }
    while(a <= 10);
    return 0;
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

Let's understand this.

At first, the codes inside the body of loop (i.e. within the braces { } following do ) are executed without checking condition. This prints 'Hello World' and a++ increments the value of 'a' by 1. So, the value of 'a' becomes 2.

Once the code inside the braces ({ }) is executed, condition 'a <= 10' is checked. Since the value of 'a' is 1, so the condition is satisfied.

Again the code inside the body of loop is executed and the value of 'a' becomes 2.

When the value of 'a' is 10 and 'Hello World' is printed for the tenth time, a++ increases the value of 'a' to 11. After this, the condition becomes false and the loop terminates.

We just saw three different types of loops which are used to repeat a certain process some number of times and they were fun as well, I hope. But you need to solve questions to make your base in coding concrete.

What if loop goes on and on - Infinite Loop


There may exist some loops that can iterate or occur infinitely. These are called Infinite Loops. These loops occur infinitely because their condition is always true.

We can make an infinite loop by leaving its conditional expression empty. When the conditional expression is empty, it is assumed to be true.

Let's see an example on how to make a for loop infinite.

#include <stdio.h>
int main()
{
    for(;;)
    {
        printf("This is not gonna end!\n");
    }
    return 0;
}
Output
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
This is not gonna end!
...
To terminate an infinite loop, press Ctrl + C.
To learn from simple videos, you can always look at our C++ video course on CodesDope Pro. It has over 750 practice questions and over 200 solved examples.
Don't spend so much time trying to choose the perfect opportunity that you miss the right opportunity.
- Michael Dell

Ask Yours
Post Yours
Doubt? Ask question