LOOP

Loop In C

Introduction

One of the greatest advantages of a computer is its capability to execute a series of instructions repeatedly. This is achieved by the loop structures available in a programming language. In this session you will learn the various loop structures in C.

The Loop in C Structure

A loop is a section of code in a program which is executed repeatedly, until a specific condition is satisfied. The loop concept is fundamental to structured programming.

The loop structures available in C are:

  • The for loop
  • The while loop
  • The do…while loop

The condition which controls the execution of the loop is coded using the Relational and Logical operators in C

The ‘for’ Loop

The general syntax of the “for” loop is

for (initialize counter; conditional test; re-evaluation parameter)
{
  Statement (s) ;
}

The initialize counter is an assignment statement that sets the loop control variable, before entering the loop. This statement is executed only once. The conditional test is a relational expression, which determines when the loop will exit. The re-evaluation parameter defines how the loop control variable changes (mostly, an increment or decrement in the variable set at the start) each time the loop is repeated. These three sections of the for loop must be separated by semicolons. The statement, which forms the body of the loop, can either be a single statement or a compound statement (more than one statement).

The for loop continues to execute as long as the conditional test turns out to be true. When the condition becomes false, the program resumes with the statement following the for loop.

Example:

/*This program demonstrates the for loop in a C program */
#include <stdio.h>
main()
{
   int count;
   printf ("/This is a \n");
   for (count = 1: count <=4; count++)
       printf ("\n\t\t nice"); 
   printf ("\n\t\t world. \n");
}

The sample output

This is a
  nice
  nice
  nice
  nice
  world
   

Look at the for loop section in the program.

  1. The initialization parameter is count = 1

    It is executed only once when the loop is entered, and the variable count is set to 1.

  2. The conditional test is count <=6

    A test is made to determine whether the current value of count is less than or equal to 6. If the test is true, then the body of the loop is executed

  3. The body of the loop consists of a single statement

    printf (“\n\n\t nice”) ;

    This statement can be enclosed in braces to make the body of the loop more visible.

  4. The re-evaluation parameter is count++, increments the value of count by 1 for the next iteration.

The re-evaluation parameter is count++, increments the value of count by 1 for the next iteration.
The steps 2,3,4 are repeated until the conditional test becomes false. The loop will be executed 6 times for value of count ranging from 1 to 6. Hence, the word nice appears six times on the screen. For the next iteration, count is incremented to 7. Since this value is greater than 6, the loop is ended and the statement that follows it is executed.

Example:

Prints even numbers from 1 to 25.

#include ‹stdio.h>
main ()
{
    int num:
    printf ("The even numbers from 1 to 25 are: \n\n") ; 
    for (num=2; num <= 25; num+=2) 
        printf ("sd\n", num) ;
}

Output

The even numbers from 1 to 25 are
2
4
6
8
10
12
14
16
18
20
22
24

The for loop above initializes the integer variable num to 2 (to get an even number) and increments it by 2 every time the loop is executed.

In for loops, the conditional test is always performed at the top of the loop. This means that the code inside the loop is not executed if the condition is false in the beginning itself.

The ‘While’ Loop

The second kind of loop structure in C is the ‘while’ loop. Its general syntax is

while(condition is true)
  statement;

where, statement is either an empty statement, a single statement or a block of statements. If a set of statements are present in a while loop then they must be enclosed inside curly braces { }. The condition may be any expression. The loop iterates while this condition is true. The program control is passed to the line after the loop code, when the condition becomes false.

The ‘for’ loop can be used provided the number of iterations are known before the loop starts executing, When the number of iterations to be performed is not known before hand, the while loop can be used.

Example:

* A simple program using the while loop */
#include ‹stdio.h>
main ( )
{
   int count - 1;
   while ( count <- 10)
  {
     printf("\n This is iteration :d\n", count) : count++;
  }
      printf("n The loop is completed. \n") ;
}

Output

This is iteration 1


This is iteration 2


This is iteration 3


This is iteration 4


This is iteration 5


This is iteration 6


This is iteration 7


This is iteration 8


This is iteration 9


This is iteration 10


The loop is completed.

The program initially sets the value of count to 1 in the declaration statement itself. The next statement executed is the while statement. The condition is first checked. The current value of count is 1, which is less than 10. The condition test results is true, and therefore the statements in the body of the while loop are executed. Therefore, they are enclosed within curly braces { }. The value of count becomes 2 after 1st iteration. Then the condition is checked again. This process is repeated until the value of count becomes greater than 10. When the loop is exited, the second printf( ) statement is executed.

Like for loops, while loops check the condition at the top of the loop. This means that the loop code is not executed, if the condition is false at the start.

The conditional test in the loop may be as complex as required. The variables in the conditional test may be reassigned values within the loop, but a point to remember is that eventually the condition test must become false otherwise the loop will never end.

The ‘do…. while Loop

The do… while loop is sometimes referred to as the do loop in C. Unlike for and while loops, this 100p checks its condition at the end of the loop, that is after the loop has been executed. This means that the do…. while loop will execute at least once, even if the condition is false at first.

The general syntax of the do… while loop is:

do{
    statement;
} while (condition);

The curly brackets are not necessary when only one statement is present within the loop, but it is a good habit to use them. The do… while loop iterates until the condition becomes false. In the do …while loop the statement (block of statements) is executed first, then the condition is checked. If it is true, control is transferred to the do statement. When the condition becomes false, control is transferred to the statement after the loop.

Example:

*accept only int values */ 
#include <stdio.h›
main ()
{
 int numl, num2;
 num2 - 0;
 do{ l
    printf("\nEnter a number : ");
    scanf ("8d", &num1) :
    printf(" No. is id", num1) ; 
    num2++:
}while (num1 ! = 0) ;
printf("\nThe total numbers entered were id", --num2) ;
  /* num is decremented before printing because count for last integer (0)
is not to be considered */
}

Output

Enter a number : 10

No. is 10

Enter a number : 300

No. iS 300

Enter a number : 45

No. is 45

Enter a number : 0

No. is 0

The total numbers entered were 3

The above code will accept integers and display them until zero (0) is entered. It will then, exit from the do… while loop and print the number of integers entered.

Jump statement

C has four statements that perform an unconditional branch: return, goto, break, and continue. Unconditional branching means the transfer of control from the point where it is, to a specified statement. Of the above jump statements, return and goto can be used anywhere in the program, whereas break and continue statements are used in conjunction with any of the loop statements.

The ‘return’ Statement

The return statement is used to return from a function. It causes execution to return to the point at which the call to the function was made. The return statement can have a value with it, which it returns to the program. The general syntax of the return statement is:

return expression ;

The expression is optional. More than one return can be used in a function. However the function will return when the first return is met. The return statement will be clear after a discussion on functions.

The ‘goto’ statement

Though C is a structured programming language, it contains the following unstructured forms of program control:

  • goto
  • label

A goto statement transfers control not only to any other statement within the same function in a C program, but it allows jumps in and out of blocks. Therefore, it violates the rules of a strictly structured programming language.

The general syntax of the goto statement is,

goto label;

where label is an identifier which must appear as a prefix to another C statement in the same function. The semicolon(;) after the label identifier marks the end of the goto statement. goto statements in a program make it difficult to read. They reduce program reliability and make the program difficult to maintain. However, they are used because they can provide useful means of getting out of deeply nested loops.

The ‘break’ statement

The break statement has two uses. It can be used to terminate a case in the switch statement and/or to force immediate ending of a loop, bypassing the normal loop conditional test.

When the break statement is met inside a loop, the loop is immediately ended and the program control is passed to the statement following the loop.

The ‘continue’ statement

The continue statement causes the next iteration of the enclosing loop to being. When this statement is met in the program, the remaining statements in the body of the loop are skipped and the control is passed to the re-initialization step.
In case of the for loop, continue causes the increment portions of the loop and then the conditional test to be executed. In case of the while and do… while loops, program control passes to the conditional tests.

The ‘exit()’ function

The exit () function is a standard C library function. Its working is similar to the working of a jump statement, the major difference being that the jump statements are used to break out of a loop, whereas exit () is used to break out of the program. This function causes immediate ending of the program and control is transferred back to the operating system. The exit () function is usually used to check if a mandatory condition for a program execution is satisfied or not. The general syntax of the exit () function is

exit (int return_code) ;

where, return_code is optional. Zero is generally used as a return code to indicate normal program ending. Other values indicate some sort of error.

Summary

  • The loop structures available in C are:
    • The for loop
    • The while loop
    • The do…while loop
  • The for loop enables repeated execution statements in C. It uses three expressions, separated by semicolons, to control the looping process. The statement part of the loop can be simple statement or a compound statement.
  • The body of a do statement is executed at least once.
  • C has four statements that perform an unconditional branch : return, goto, break, and continue.
  • The break statement enables early exit from a simple or a nesting of loops. The continue statement causes the next iteration of the loop to begin.
  • A goto statement transfers control to any other statement within same function in a C program, but it allows jumps in and out of blocks.
  • The exit() function causes immediate termination of the program and control is transferred back to the operating system.