Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Loops in C - for while do while and goto (http://www.go4expert.com/articles/loops-c-goto-t29938/)

faribasiddiq 22Dec2013 09:48

Loops in C - for while do while and goto
 
Loops are the basic logic building structures in computer programming. It is a way of executing statement(s) repeatedly in specified times, which is termed as iteration.

Here different types of loops in C language will be discussed. All of them have same goal, but their way of working is different. The topics of discussion of this article would be to understand the following loops in C programming:

for Loop



It is very easiest to understand out of all loops. Generally it is used when number of iteration is known to a programmer. Traditionally, a basic for loop has four parts:
  • Initialization
  • Condition
  • Update(Increment/Decrement)
  • Statements
Here is the basic syntax of for loop.
Code:

for (variable(s) initialization; condition(s); update value of variable(s))
{
        statement 1;
        . . . .
        . . . .
        . . . .
        statement N;
}

For a beginner, it must not be that easy to understand the syntax. For elucidation, an example is given:
Code:

int main()
{
        int i;
        for(i = 0; i < 5; i++)
                printf("%d", i);
}

Illustration for different parts of the loops for above example is as follows:
  • i = 0 initialize the loop control variable i.
  • i < 5 is condition for the loop. The loop continues till the value of i is less than 5.
  • i++ increments the value of i by 1. It means i+1.
  • printf("%d", i) is the statement of the loop. Value of i is displayed in the console by this statement.

The steps involved in working of the above example are:

Step 1: i = 0. So condition (i < 5) is true. Update the value of i by 1. But the updated value will work for next iteration. Print the value of i. The value that will be printed will be 0.

Step 2: Now i = 1. So Condition is true. Update the value of i by 1. But the updated value will work for next iteration. Print the value of i. The value that will be printed will be 1.

Step 3, 4, 5: Working procedure is as the previous one and print the value 2,3,4 accordingly.

Step 6: Now i = 5. So Condition is false. So, exit the loop.

So the building blocks of for loop are:
  • Initialize the loop variable(s).
  • Check the condition for next iteration.
  • Update the value of loop variable.
  • Statement(s).
The value of loop control variable can be updated by any amount. For example, i+=2 can be used for incrementing the value by 2. Some other operators can be used for updating the value of loop control variable such as decrement (-), multiplication (*), divide (-) etc. besides increment operator (+).

The benefit of using for loop is immense. An example may help in explanation. Suppose you will be given two numbers x and y. You have to find out the summation of all numbers from x to y including these numbers. How can this be done? For loop makes it quite easy for you.
Code:

int main()
{
        int x,y,num,sum = 0;
        scanf("%d %d",&x,&y);
        for(num = x; num <= y; num++)
                sum = sum + num;
        printf("Summation of %d to %d is %d",x, y, sum);
}

You can use multiple variables for loop control. Initialization, condition and update, every block can work with multiple variables.
  • In initialization and update, separate the two variable using coma(,) separation.
  • In condition, use logical and, or (&&, ||) according to your need.
Why should multiple variables be used? Suppose two sprinters x and y are there and speed of y is double of speed of x. They are going to participate in a 30 meter sprint. x has started from 10 meters ahead of y. Who have won the race? In different stages of race, what is their position? Their positions can be obtained in the following manner:
Code:

int main()
{
        int x,y;
       
        for (x=10, y=0 ; x <= 30 && y <= 30 ; x++, y= y+2)
        {
                printf("%d\t%d\n",x,y);
        }
        return 0;
}

Nested for loop: You can use one for loop inside another. It is called nested for loop. Basic syntax for nested for loop is:

Code:

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

The process to draw a triangle using nested for loop is given:
Code:

int main()
{
        int i,j,rows;
        printf("Enter the number of rows");
        scanf("%d",&rows);
        for(i=1;i<=rows;++i)
        {
                for(j=1;j<=i;++j)
                {
                        printf("*");
                }
                printf("\n");
        }
        return 0;
}

The number of rows have been assumed as 3. Then for every row, inner loop executes i times. the simulation is given here:

Input 1 : i = 1, j = 1
Output: *
Input 2 : i = 2, j = 1, 2
Output: * *
Input 3 : i = 3, j = 1, 2, 3
Output: * * *

One of the uses of nested loops is for creating two dimensional array or matrix. Initialization of any matrix is done using nested for loop. Suppose you will make a row*col matrix. An example is given below showing how to initialize and access it.
Code:

int mat[10][10];
int i,j,row,col;
 
printf("Enter order of matrix=");
scanf("%d%d",&row,&col);
printf("Enter Elements: ");
for(i=0;i<row;i++)
{
        for(j=0;j<col;j++)
        {
                scanf("%d",&mat[i][j]);
        }
}

for(i=0;i<row;i++)
{
        for(j=0;j<col;j++)
        {
                printf("row[%d] col[%d]= %d\n",i,j,mat[i][j]);
        }
}

while Loop



While loop can be thought as repetition of if statement.It is also known as pre- test loop as condition check is done before execution of the block.
Here is the basic syntax of a while loop:
Code:

While(condition)
{
        statement(s);
}

Everything that can be done using for loop can be done using while loop also. Remember the program that printed 0 to 4 using for loop. Below a while loop implementation is given. It will give basic understanding about while loop.
Code:

int main()
{
        int i = 0;

        while(i < 5)
        {
                printf("%d",i);
                i++;
        }
}

Here, initialization is before for loop. Updating loop control variable is done inside loop.

While loop provides some advantages when number of iteration is not known. Suppose, you will take input continuously from keyboard until a negative value is given. Here, number of iteration of the loop is unknown to you. How while loop handles it is depicted here.
Code:

int main()
{
        int num = 0;

        while(num >= 0)
        {
                printf("Enter new number");
                scanf("%d",&num);       
        }
}

You can use multiple conditions in while loop. Let us play a guessing game. I will randomly pick a number from 1 to 20. You will try to guess it. I will give you hints every time whether you got it, or you should try smaller number, or greater number. I will give you 5 chances. This can be done using while loop in the following manner.
Code:

int main
{
        int secretNum, guessNum = 0;
        int usedChance = 0;
        int maxChances = 5;

        srand((unsigned int)time(NULL));
        secretNum = rand() % 20 + 1;
        printf("Guess a number from 1 to 20.You will get %d chances\n",maxChances);
        while(guessNum != secretNum && usedChance < maxChances )
        {
                scanf("%d",&guessNum);
                if(guessNum == secretNum)
                        printf("Congrats.You have got it.\n");
                else if(guessNum < secretNum)
                        printf("Try a bigger number.\n");
                else
                        printf("Try a smaller number.\n");
                usedChance++;
        }
        return 0;
}

You might change it slightly. Do not limit the chance to 5 times. Give unlimited chances until the right number is guessed. Look how many chance one player needs to get the number. Do it yourself.

Like nested for loop, while loop also has nested version. Basic syntax is:
Code:

while (condition1)
{
        while (condition2)
        {
                statement(s);
        }
}

Remember the for loop section. There was a matrix operation using nested for loop. Matrix can also be initialized using nested while loop.
Code:

i =0;
while(i < row)
{
        j = 0;
        while(j < col)
        {
                scanf("%d\t",&mat[i][j]);
                j++;
        }
        i++;
}

Similarly the value of matrix can be accessed.

do while Loop



do-while loop is a variation of while loop. The condition is checked by a while loop and statements are in do segment. It is also known as post-test tool as it first executes the block and then checks the condition.

Here is the basic syntax :
Code:

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

Look at some comparison between while and do while.
  • While loop first checks the condition, if the condition is satisfied, then the statements are executed. In other hand, do-while loop first executes statements one time and then check the conditions for the next iteration.
  • In while loop, it is possible that statements inside loop will not be executed entirely, if condition fails for the very first time. On the other hand, statements in do-while loop will be executed at least one time.

The iteration of a do while loop is as below.
Code:

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

The program prints the value from 1 to 5. In do segment, it increments the loop control variable and print the value. In while section, it checks if the value of loop control variable is less than another variable.

Remember any game or application which shows you the menu and allows you to select any option. Then according to your choice, does some operation. For example, some menu like this:

Select any one from the menu:
  1. Add numbers.
  2. Subtract numbers
  3. Multiply numbers.
  4. Divide numbers.
  5. Exit.
You then make a choice from 1-5 and program works accordingly. Look, at the beginning of the program, menu has been displayed to you once. That means it is independent of your choice of operation. Here lies the usage of do section of do-while loop.
Code:

int option = -1;
float num1, num2;
 
do
{
        printf("Enter two numbers");
        scanf("%f %f",&num1,&num2);
        printf("Select 1-5 for any operation\n");
        printf("1.Addition\n");
        printf("2.Subtraction\n");
        printf("3.Multiplication\n");
        printf("4.Division\n");
        printf("5.Exit Program\n");
        scanf("%d", &option);
        printf("\n");
   
        switch(option)
        {
                case 1:
                        printf("Summation result is =%.2f\n",num1+num2);
                        break;
                case 2:
                        printf("Subtraction result is =%.2f\n",num1-num2);
                        break;
                case 3:
                        printf("Multiplication result is =%.2f\n",num1*num2);
                        break;
                case 4:
                        printf("Division result is =%.2f\n",num1/num2);
                        break;
                case 5:
                        printf("Terminating...");
                        break;
                default: 
                        printf("Invalid operator");
                        break;
        }
}while(option != 5);

Every time you enter two numbers, program shows you the menu. You can choose 1-4 to make the calculation and 5 to exit. If you choose any other option other than 1-5, it prompts you that you have choosen the invalid operator and redirects you to the main menu again. The program continues until the exit option, that means option 5 is pressed.

goto



goto statement performs unconditional jump from one statement to another statement.But the this jump can be done in the same function, you can not use goto statement to jump from one function to another function.

Basic syntax for goto is as follows.
Code:

statement;
. . .
goto label;
statement;
label:
statement;

http://imgs.g4estatic.com/loops-c/goto.png

For more clarification, the example below shows depending on conditional statement, how different label is executed and some statements are ignored.
Code:

if(player1Runs > player2Runs)
        goto player1
else
        goto player2
. . .
. . .
player1:
        printf(“I am player1, I have won the match”);
player2:
        printf(“I am player2, I have won the match”);

Here, if player1Runs is greater than player2Runs, it jumps to player1 label, otherwise jumps to player2 label using goto statement.

You can use goto statement for looping. Instead of using for, while, do while loop, you can do the same job using goto. An example is shown below:
Code:

int i = 0;

firstLoop:
        printf("%d",i);
        i++;
        if(i<10)
                goto firstLoop;
        printf("\nout of first loop");

It is suggested not to use goto statements. The goal you achieve by using goto statement, can be achieved more easily using some other conditional statements like if-else if-else etc.
Shortcomings of goto statement:
  • Make a mess of sequence of code
  • Unintended infinite loop
  • Reduces readability
So, we have had a journey through the different kinds of loop. For long and repetitive task, loop is still the best logic structure. According to the situation, you may have to choose one which works best in that situation. So, start your practice and do the best use of loops in your programs.


All times are GMT +5.5. The time now is 10:52.