logo codesdope

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 ask 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 consider our example step by step.

In our example, firstly, we assigned a value 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 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 to '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 perform 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 this with for loop. But before that, let's look at the syntax of for loop.

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

#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 step is used to assign value to a variable and is executed first and only once. 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 'while' loop which was being checked again and again.

a++ - This is executed after the code in the body of for loop has been executed. 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 loop.


In the above example, firstly 'a=1' assigns value 1 to '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 thus 'Hello World' gets printed.

Once the codes in the body of for loop are executed, step a++ is executed which increases the value of 'a' by 1. So 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 incremented.

When the value of 'a' becomes 10, condition 'a <= 10' becomes true and 'Hello World' gets printed. Now, when a++ increases the value to '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

There is another way to write program of for loop

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

And 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, a is 1. So, 12*a is 12. In the second iteration, 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' now.
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 loop.

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

When the first for loop will be executed, i will be 1 and then Table of 12 will be printed.
Now coming to the second for loop.
j is 1 and 12*1 = 12 will be printed.
In the second loop, i is again 12 but j will be 2.
So, 12*2 = 24 will be printed.
Coming to the last iteration while 'i' is still 12, this time 12*10 = 120 will be printed.
Now, coming out of the outer loop, j will become 13 and Table of 13 will be printed and again the same will repeat with j equals 13.
It’s cool to see this work, 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 how.

Suppose we have to print 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, robotics, etc.

do...while loop


It is just like 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 try to 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 now, 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


There may exist some loops that can iterate or occur infinitely.These are called Infinite Loop 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.

Don't spend so much time trying to choose the perfect opportunity that you miss the right opportunity.
-Michael Dell

Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.