looping statements in c

The looping statements instruct the compiler to execute a statement or group of statements multiple times.

The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This means repeating a block or multiple blocks of a program is called as looping statements. In addition, loops or looping statements can run either a specified number of times or until a particular condition is satisfied. Loops are iterative in nature that’s why it is sometimes called as Iterative Control Instruction.

There are three ways to implement looping statements in c:

Apart from the above-mentioned ways, there is one more way to implement looping statements in c language and that is nested loop

for loop

The for loop is widely used by programmers because it contains initialization, termination and control flow at one place. The for loop allows a programmer to specify three things about a loop in a single line.

  • Setting a loop counter to an initial value (initialization).
  • Testing the loop counter to determine whether its value has reached the number of repetitions desired. (condition or termination)
  • Increasing or decreasing the value of loop counter each time the body of the loop has been executed (flow control).

The syntax of for loop

for (initialization ; condition ; flow) { some statements; ........................ }

Notice the two semicolons inside bracket of for loop. Since these are part of the syntax of for loop so it should always be mentioned. Two semicolons create three sections.

The first section is used for is used for initialization, second is used for condition check or termination and the third section is used to mention control flow of a program.

Example

A very simple example of for loop implementation on the code::blocks:

#include <stdio.h>
#include <conio.h>
int main ()
{
 int i;   //variable decalaration//
 for ( i=1; i<=2 ; i++)
  {
   printf("Number = %d \n", i);
   }
getch(); // use in (turbo c or older IDE), don't use in code::blocks//
return 0;  // return type of main() function is int//
}

OUTPUT:

Number = 1

Number =2

Understand the program execution

  • Inside the main() function, a variable i of integer data type is declared.
  • Inside the bracket of for loop the variable, i is initialized with 1. Now, the condition (i<=2) will be checked. Since 1<2 so condition becomes true and control will move inside the for loop and execute the statement inside for loop and in this case it will print the value of i on the output screen.
  • After the execution all the statements inside for loop, the value of the variable i increases by 1 (also called as a counter variable).
  • Now the value of the variable i will be 2. Again condition will be checked and the condition becomes true again. Therefore, control will enter for loop and execute the statements inside the loop. Now 2 will be printed on screen and value of the variable i will be 3.
  • Again, the condition will be checked and this time the condition (3<=2) will be false and hence control will exit from for loop.

Special Attention

  • You can initialize the variable either inside the main function (as a local variable) or outside (as a global variable) during the declaration of a variable. In this case syntax of for loop will be for ( blank (don’t write anything); condition; flow).
  • Don’t use looping statements when you have small work like the above-mentioned program. It is always a good practice to use looping statements only when you have at least more than 10 statements to execute because looping statements are complex and it takes time in execution. So if you will use this for the smaller program it will unnecessarily increase execution time and hence lowers the execution speed. However, using looping statements in large program saves programmers time taken to write the same code multiple times, reduces space and execution time.
  • Please note that \n is an escape sequence that is just used to write one output on one line. You may or may not use this, it’s up to you. However, if you will not use this your output in the above program will look something like this 12 (in one line). It becomes really hard to read output when there are several numbers of outputs to print. In order to make your output more readable, you must \n.

Read More About for Loop

while loop

The while loop repeats a statement or group of statements while a given condition is true. In addition, it tests the condition before executing the body of the loop. Few important points about while loop:

  • The statements within the while loop would keep getting executed till the condition is true. When the condition becomes false, the control passes to the first statement that follows the body of the while loop.
  • The most important thing is, in the place of condition you can use any valid expression. So long as the expression evaluates to a non-zero value the statements within the loop would execute.
  • In addition, the condition may use relational or logical operators.

The syntax of while loop

initialize the loop counter; // locally or globally// while (condition) {  statement1;  ........................  control flow (increment or decrement); }

The syntax of while loop is similar to if statement. When the condition is true control moves inside while-block and executes statements after while-block rather it goes back to the condition of while block.

The condition will be checked again and if the condition is true then control will move inside while loop. This process will be repeated until the condition becomes false.

Example:

#include <stdio.h>
#include <conio.h>
int main()
{
int i=1;  // variable decalaration and initialization //
while (i<=2)
  {
   printf ("Number = %d \n", i);
   i++;
  }
getch(); // use in (turbo c or older IDE), don't use in code::blocks//
return 0;  // return type of main() function is int//
}

OUTPUT:

Number = 1

Number =2

Understand the program execution

  • Inside the main() function, a variable i of integer data type is declared and initialized with 1.
  • Now, the condition (i<=2) inside while loop will be checked. Since 1<2 so condition becomes true and control will move inside the while loop and execute the statements inside while loop and in this case, it will print the value of i on the output screen.
  • After the execution of all the statements inside while loop, the value of the variable i increases by 1 (also called as a counter variable).
  • Now the value of the variable i will be 2. Again condition will be checked and the condition (2<=2) becomes true. Therefore, control will again enter inside while loop and execute the statements inside the loop. Now 2 will be printed on screen and value of the variable i will be 3.
  • Again, the condition will be checked and this time the condition (3<=2) will be false and hence control will exit from while loop.

Special Attention

  • You can initialize the variable either inside the main function (as a local variable) or outside (as a global variable) during the declaration of a variable.
  • Don’t use looping statements when you have small work like the above-mentioned program. It is always a good practice to use looping statements only when you have at least more than 10 statements to execute because looping statements are complex and it takes time in execution. So if you will use this for the smaller program it will unnecessarily increase execution time and hence lowers the execution speed. However, using looping statements in large program saves programmers time taken to write the same code multiple times, reduces space and execution time.
  • Please note that \n is an escape sequence that is just used to write one output on one line. You may or may not use this, it’s up to you. However, if you will not use this your output in the above program will look something like this 12 (in one line). It becomes really hard to read output when there are several numbers of outputs to print. In order to make your output more readable, you must \n.

Read More About while Loop

 do-while

The do-while loop repeats a statement or group of statements without checking condition at the first time. After one execution of do block, condition inside the bracket of while the block is checked. Few important points about do-while loop:

  • The do-while loop is one of the looping statements in c language, which executes the statements inside the do-block and then checks the condition.
  • In addition, the do-while loop executes the statements inside do-block n+1 times, where n is the number of times condition is true.
  • The statements within the do-while loop would keep getting executed till the condition is true. When the condition becomes false, the control passes to the first statement that follows the body of the do-while loop.
  • The most important thing is, in the place of condition you can use any valid expression. So long as the expression evaluates to a non-zero value the statements within the loop would execute.
  • In addition, the condition may use relational or logical operators.

The syntax of do-while loop

main()
{
initialize the loop counter; // locally or globally//
  do
   {
    statement1;
    ........................
   }
  while (condition);
}

The do-while loop consists of two keywords do and while. The code that has to put in the loop is prefixed with keyword do and post-fixed with keyword while along with termination condition. Don’t forget to write a semicolon after while keyword.

In addition, the do-while works similar to while but the only difference is it will execute statements inside do block once irrespective of the condition is true or false. In contrast with the while loop, in do-while loop control enters in the loop body first then the condition will be checked.

Example

#include <stdio.h>
#include <conio.h>
int main()
{
int i=1;  // variable decalaration and initialization //
  do
   {
    printf ("Number = %d \n", i);
    i++; // increment or decrrement can be used according to need.
   }
  while (i<=2);
getch(); // use in (turbo c or older IDE), don't use in code::blocks//
return 0;  // return type of main() function is int//
}

OUTPUT:

Number = 1

Number =2

Understand the program execution

  • Inside the main() function, a variable i of integer data type is declared and initialized with 1.
  • First of all, statements inside do-block will execute without any condition check. So, 1 will be printed on your screen. After that value of i will increase by one and becomes 2.
  • Then, the condition (i<=2) inside while loop will be checked. Since 2 is equal to 2 so condition becomes true and control will again move inside the do-block. Now, 2 will be printed on the screen. After that value of i will again increase by 1 and becomes 3.
  • Again condition (i<=2) will be checked and this time condition will be false as (3<=2) becomes false. So, the loop will terminate and control will exit from this loop.

Special Attention

  • You can initialize the variable either inside the main function (as a local variable) or outside (as a global variable) during the declaration of a variable.
  • Don’t use looping statements when you have small work like the above-mentioned program. It is always a good practice to use looping statements only when you have at least more than 10 statements to execute because looping statements are complex and it takes time in execution. So if you will use this for the smaller program it will unnecessarily increase execution time and hence lowers the execution speed. However, using looping statements in large program saves programmers time taken to write the same code multiple times, reduces space and execution time.
  • Please note that \n is an escape sequence that is just used to write one output on one line. You may or may not use this, it’s up to you. However, if you will not use this your output in the above program will look something like this 12 (in one line). It becomes really hard to read output when there are several numbers of outputs to print. In order to make your output more readable, you must \n.

Read More About do-while Loop

Nested Loop

Using loop inside the body of the loop is called as a nested loop because sometimes it is important to repeat the repetitions.

There are many combinations by using which you can form a nested loop. I am going through nested for loop ( for loop inside another for loop).

Syntax

for (initialization ; condition ; flow)
{
  for (initialization ; condition ; flow)
   {
    some statements;
    .................................
    }
some statements;
}

Notice the two semicolons inside bracket of each for loop. Since these are part of the syntax of for loop so it should always be mentioned. Two semicolons create three sections.

The first section is used for is used for initialization, second is used for condition check or termination and the third section is used to mention control flow of a program.

Example

Write a program to print 2 lines with each containing 1 and 2.

#include <stdio.h>
#include <conio.h>
int main ()
{
int i, j;   //variable decalaration//
 for ( i=1; i<=2 ; i++)
  {
    for (j=1; j<=2; j++)
     {
      printf("%d ", j);
      }
printf ("\n");
}
getch(); // use in (turbo c or older IDE), don't use in code::blocks//
return 0;  // return type of main() function is int//
}

OUTPUT

12

12

Understand the program execution

  • Whenever you have to implement a program like above-mentioned program then you will take two counter variables. In this case, these variables are i and j and both are declared inside the main function as a local variable.
  • The first counter variable i is a row which indicates two lines to be printed that’s why i wrote printf (“\n”) inside first for loop, not inside second.
  • The second counter variable j is for value to printed in that line.
  • Nested for loop is very useful during solving star pattern or any pattern program and matrix or 2-D related program.

Read More About Nested For Loop

Infinite Loop

Most of the time beginners do a mistake while writing the program and puts the wrong condition while implementing looping statements. As a result of this, control flows inside that loop at an infinite time and that is called an infinite loop.

Although you can form an infinite loop in many ways by just making condition inside the loop always equal to true. The for loop is traditionally used for this purpose.

Example

#include <stdio.h>
#include <conio.h>
int main ()
{
  for( ; ; )
     {
      printf("Infinite Loop Success\n");
      }
return 0;
}

In C language when the conditional expression is absent, the compiler assumes the condition is true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.

How should You Stop This Naughty Infinite Loop

You can terminate an infinite loop by pressing Ctrl + C keys together.

Links Of Relevant Contents

for loop   while loop   do-while loop    nested loop    infinite loop


<< Prev                                                                                                              Next >>


 

Detected Ad-Blocking Software!

Hello Folks!

We run this website to provide quality content to our visitors. For the betterment & maintenance of the website, we need money. We earn money through Adsense on free quality content. We know most of you are our prime members. But this is just a global detection. If you are our premium member then you won't see any ad on the pages. 

Please Co-operate with us by enabling our website to serve Ads!

Best Wishes!

Mycteacher Team

Close