Loops in C

Introduction

In general terms, Loops in C is nothing but a never-ending structure. A loop is a sequence of instructions written in a program that repeats continuously until it reaches a condition that terminates it. In this article we will explore more about Loops in C.

While Loop in C

To repeat a code many times is difficult. Suppose a software aims to wish ‘Good morning’ to the users, and every day hundred user access that software. What should the programmer do?

One way is to write the printf(“Good morning”) 100 times. But this doesn’t seem to be a good choice. Moreover, if the number of users reaches 1000 in the future, then it is impossible to write the same thing 1000 times.

Here, the while loop comes into use.

Syntax

while(condition)

{

               statement(s)…

}

In the above syntax, while is the keyword followed by a condition. It will check the condition written inside  ‘( )’ first, and if the result is true, the control will move inside the body of the loop written in { } braces, and the statements are executed. Then, the condition is rechecked, and if found to be true, statements in the body of the loop are executed again. This process terminates only when the condition becomes false.

Example

Let’s look at a code to print a message 10 times.

#include<stdio.h>
int main()
{
            int m=1;
            while(m<=10)
            {
                        printf("Good morning\n");
                        m=m+1;
            }
            return 0;
}

Output

Loops in C

Explanation

In the code above, ‘m’ is declared an integer and assigned a value ‘1’.

while(m<=10) checks whether ‘m’ satisfies the condition. Since ‘1<=10’ is true, the statements of the while loop are executed.

‘Good morning’ is printed, and the value of ‘m’ becomes ‘2’. When the condition is rechecked, it comes out to be true (since, 2<=10). Thus, once again, ‘Good morning’ is printed.

This process continues when ‘m=10’, ‘Good morning’ is printed for the 10th time, and ‘m’ becomes 11. But now the condition, i.e. ‘m<=10’, becomes false. Therefore, the while loop terminates.

Example 2

Playing with real coding is very interesting. Isn’t it?

#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);


    }
    printf("exit");
    return 0;
}

 

Output:

While Loop in C

The loop will run until the value of ‘choice’ becomes different from ‘y’. So, for the first time, it will run since ‘choice’ is ‘y’, and the code inside it gets executed. Then, it asks for the user’s choice again, and execution of code takes place.

When the user presses ‘n’, the loop gets terminated and prints ‘exit’.

Note: The variable ‘y’ is a global variable valid everywhere in code, but ‘a’ is only valid inside ‘while loop’ is not outside that.

 

For Loop in C

For loop is another loop that can be used to repeat the code inside its body.

Syntax

for (initialization; condition; propagation)

{

Statement(s)

}

Let’s go to our first example of a while loop where the variable ‘m’ is first initialised. The condition was written in ‘( )’ braces, and in the body, propagation of ‘m’ was done (m=m+1). The same code can be made with for loop by following the syntax.

The initialisation part is executed once and before the starting of the loop.

Once there is an initialisation, control will move to the condition to check whether it is true or false. The code then gets executed if the condition is true.

Finally, after the iteration of the loop, the statement written at the place of propagation is executed.

Example

It will become clearer with an example.

#include<stdio.h>
int main()
{
            int m;
            for(m=1; m<=10;m++)
            {
                        printf("Good morning\n");
            }
            return 0;
}

Output

For Loop in C

Explanation

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

m=1’ initialises the loop and is executed once at the starting of the loop. ‘m’ is assigned with a value ‘1’.

m<=10’ this condition is evaluated. If the condition is true, the statements written inside the body of the loop are executed. If it is false, control moves out of the loop and executes the code outside it.

m++’ after the execution of code, the propagation part is executed and updates the value of ‘m’.

In the program above, the assignment of value ‘1’ to ‘m’ condition is checked, which is true. Thus, statements inside the body are executed. Then ‘m++’ updates the value of ‘m’, and now m is equal to 2. This procedure repeats again and again.

‘m=10’ prints the message 10th time, and propagation of ‘m’ increases its value to 11, the condition becomes false, and the loop terminates.

It is a different form of the while loop.

Note: We can skip any initialisation, condition propagation statements, and design our code differently but never skip the ‘;’ semicolon used in the syntax.

The codes written below are valid:

{  
   int a=1;
   for (; a<=5; a++)
   { 
      printf (“C programmer”);
    }
 }

 

We can rewrite it as:

{  
   int a;
   for (a=1; a<=5; )
   { 
      printf (“C programmer”);
      a++;
    }
 }

 

Or,

{  
   int a=1;
   for (; a<=5; )
   { 
      printf (“C programmer”);
      a++;
    }
 }

 

Use case of Loop

Look at some more applications of this ‘for loop’.

  1. A table of any value can be made simple by using this loop.
#include<stdio.h>
int main()
{
            int x;
            printf("enter any value to calculate its table\n");
            scanf("%d",&x);
            printf("Table of %d:",x);
            int y;
            for(y=1;y<=10;y++)
            {
                        printf("\n %d * %d = %d",x,y,x*y);
            }
           
            return 0;
}

 

Output:

Use case of Loop

Hopefully, the above code is clear.

In the first iteration, the value of ‘y’ is 1. So, 8*y is 8.

In the second iteration, the value of ‘y’ is 2. So, 8*y is 16.

And at last, ‘y’ is 10. So, 8*y is 80.

  1. To calculate: b raised to the power a.
#include<stdio.h>
int main()
{
            int a, b;
            printf("To calculate a raised to the power b\n");
            printf("enter value for a:");
            scanf("%d",&a);
           
            printf("enter value for b:");
            scanf("%d",&b);
            int i, power=1;
            for(i=1;i<=b;i++)
            {
                        power=power*a;
            }
            printf("%d raised to the power %d is\n%d",a,b,power);
}

Output:

Loop Example in C

In the first iteration, power=power*a will be power=1*a. So, power will become ‘a’.

Similarly, in the second iteration, ‘power’ will be a*a.

So, in the bth times, ‘power’ will be multiplied b times.

In the code above, ‘a’ is multiplied ‘b’ times, i.e. 9*9. Thus, ‘a’ raised to the power ‘b’ is 81.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.