The Loop Control Structure - C Programming

Sometimes we want some part of our code to be executed more than once. We can either repeat the code in our program or use loops instead. It is obvious that if for example we need to execute some part of code for a hundred times it is not practical to repeat the code. Alternatively we can use ourrepeating code inside a loop.

There are three methods for, while and do-while which we can repeat a part of a program.

1. while loop

while loop is constructed of a condition or expression and a single command or a block of commands that must run
in a loop.

//for single statement  
while(expression) 
    statement;

//for multiple statement   
while(expression) 
{ 
    block of statement 
} 

The statements within the while loopwould keep on getting executed till the condition being tested remains true. When the condition becomes false, the control passes to the first statement that follows the body of the while loop.

The general form of while is as shown below:

initialise loop counter;  
while (test loopcounter using a condition) 
{ 
    do this; 
    and this; 
    increment loopcounter;
} 

Example

#include <stdio.h>
int main () {
   /* local variable definition */
   int a = 10;
   /* while loop execution */
   while( a < 20 ) {
      printf("value of a: %d\n", a);
      a++;
   }
   return 0;
}

When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

2. for loop

for loop is something similar to while loop but it is more complex. for loop is constructed from acontrol statement that determines how many times the loop will run and a command section. Command section is either a single command or a block of commands.

//for single statement  
for(control statement) 
    statement;  

//for multiple statement
for(control statement) 
{ 
    block of statement 
} 

Control statement itself has three parts:

for ( initialization; test condition; run every time command )
  • Initialization part is performed only once at for loop start. We can initialize a loop variable here.
  • Test condition is the most important part of the loop. Loop will continue to run if this condition is valid (true). If the condition becomes invalid (false) then the loop will terminate.
  • Run every time command section will be performed in every loop cycle. We use this part to reach the final condition for terminating the loop. For example we can increase or decrease loop variable’s value in a way that after specified number of cycles the loop condition becomes invalid and for loop can terminate.

Example

#include <stdio.h>
int main () {
   int a;
   /* for loop execution */
   for( a = 10; a < 20; a = a + 1 ){
      printf("value of a: %d\n", a);
   }
   return 0;
}

When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

3. do-while loop

The while and for loops test the termination condition at the top. By contrast, the third loop in C, the do-while, tests at the bottom after making each pass through the loop body; the body is always executed at least once.
The syntax of the do is

do
{
    statements;
}while (expression);

The statement is executed, then expression is evaluated. If it is true, statement is evaluated again, and so on. When the expression becomes false, the loop terminates. Experience shows that do-while is much less used than while and for. A do-whileloop is used to ensure that the statements within the loop are executed at least once.

Example

#include <stdio.h>
int main () {
   /* local variable definition */
   int a = 10;
   /* do loop execution */
   do {
      printf("value of a: %d\n", a);
      a = a + 1;
   }while( a < 20 );
   return 0;
}

When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

4. Break and Continue statement

We used break statement in switch...case structures in previouslly. We can also use
"break" statement inside loops to terminate a loop and exit it (with a specific condition).

In above example loop execution continues until either num>=20 or entered score is negative.

while (num<20) 
{ 
    printf("Enter score : "); 
    scanf("%d",&scores[num]); 
    if(scores[num]<0) 
        break; 
} 

Continue statement can be used in loops. Like breakcommand continue changes flow of a program. It does not terminate the loop however. It just skips the rest of current iteration of the loop and returns to starting point of the loop.

Example 1 (break)

#include <stdio.h>
int main () {
   /* local variable definition */
   int a = 10;
   /* while loop execution */
   while( a < 20 ) {
      printf("value of a: %d\n", a);
      a++;
      if( a > 15) {
         /* terminate the loop using break statement */
         break;
      }		
   }
   return 0;
}

When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

Example 2 (continue)

#include<stdio.h> 
main() 
{ 
    while((ch=getchar())!='\n') 
    { 
        if(ch=='.') 
            continue; 
        putchar(ch); 
    }  
} 

In above example, program accepts all input but omits the '.' character from it. The text will be echoed as you enter it but the main output will be printed after you press the enter key (which is equal to inserting a "\n" character) is pressed. As we told earlier this is because getchar() function is a buffered input function.

5. Goto and labels

C provides the infinitely-abusable goto statement, and labels to branch to. Formally, the goto statement is never necessary, and in practice it is almost always easy to write code without it. We have not used goto in this book.

Nevertheless, there are a few situations where gotos may find a place. The most common is to abandon processing in some deeply nested structure, such as breaking out of two or more loops at once. The break statement cannot be used directly since it only exits from the innermost loop. Thus:

for ( ... )
{           
    for ( ... ) 
    {               
        ...               
        if (disaster)
        {                   
            goto error;
        }           
    }
}       
...   
error:       
/* clean up the mess */

This organization is handy if the error-handling code is non-trivial, and if errors can occur in several places.

A label has the same form as a variable name, and is followed by a colon. It can be attached to any statement in the same function as the goto. The scope of a label is the entire function.

Example

#include <stdio.h>
int main () {
   /* local variable definition */
   int a = 10;
   /* do loop execution */
   LOOP:do {
      if( a == 15) {
         /* skip the iteration */
         a = a + 1;
         goto LOOP;
      }
      printf("value of a: %d\n", a);
      a++;
   }while( a < 20 );
   return 0;
}

When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Note - By uses of goto, programs become unreliable, unreadable, and hard to debug. And yet many programmers find goto seductive.

6. Quiz

Test what you learn from this tutorial. Click here to give a quiz based on this tutorial.

7. Examples

Example Statement for Loops in C Language
1. Print All ASCII Values
2. Convert the given binary number into decimal
3. Print Diamond Shape
4. Check leap year in a given year range
5. Convert number to binary using bitwise operators
6. Find the value of sin(x) using the series up to the given accuracy without using math.h library functions.

Next - Arrays


You've successfully subscribed to Developer Insider
Great! Next, complete checkout for full access to Developer Insider
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.