Sunday, October 30, 2011

The break Statement: C programing The Loop Control Structure

We often come across situations where we want to jump out of a loop instantly, without waiting to get back to the conditional test. The keyword break  allows us to do this. When break  is encountered inside any loop, control automatically passes to the first statement after the loop. A break is usually associated with an
if. As an example, let’s consider the following example.

Example:  Write a program to determine whether a number is prime or not. A prime number is one, which is divisible only by 1 or itself.

All we have to do to test whether a number is prime or not, is to divide it successively by all numbers from 2 to one less than itself. If remainder of any of these divisions is zero, the number is not a prime. If no division yields a zero then the number is a prime number. Following program implements this logic

main( )
{
      int   num, i ;

      printf ( "Enter a number " ) ;
      scanf ( "%d", &num ) ;

      i = 2 ;
      while ( i <= num - 1 )
 {
            if ( num % i == 0 )
  {
                  printf ( "Not a prime number" ) ;
   break ;
  }
  i++ ;
 }
if ( i == num )
            printf ( "Prime number" ) ;
}

In this program the moment num % i turns out to be zero, (i.e. num is exactly divisible by i) the message “Not a prime number” is printed and the control breaks out of the while loop. Why does the program require the if  statement after the while  loop at all? Well, there are two ways the control could have reached outside
the while loop:

(a)  It jumped out because the number proved to be not a prime.
(b)  The loop came to an end because the value of i became equal to num.

When the loop terminates in the second case, it means that there was no number between 2 to num - 1 that could exactly divide num. That is, num is indeed a prime. If this is true, the program should print out the message “Prime number”. The keyword break, breaks the control only from the while  in which it is placed. Consider the following program, which illustrates this fact.

main( )
{
      int  i = 1 , j = 1 ;

      while ( i++ <= 100 )
 {
            while ( j++ <= 200 )
  {
                  if ( j == 150 )
    break ;
   else
                        printf ( "%d %d\n", i, j ) ;
  }
 }
}

In this program when j equals 150, break takes the control outside the inner while only, since it is placed inside the inner while.

The Odd Loop : C programming The Loop Control Structure

 The loops that we have used so far executed the statements within them a finite number of times. However, in real life programming one comes across a situation when it is not known beforehand how many times the statements in the loop are to be executed. This situation can be programmed as shown below: 

/* Execution of a loop an unknown number of times */
main( )
{
      char  another ;
      int  num ;
 do
 {
            printf ( "Enter a number " ) ;
            scanf ( "%d", &num ) ;
            printf ( "square of %d is %d", num, num * num ) ;
            printf ( "\nWant to enter another number y/n " ) ;
            scanf ( " %c", &another ) ;
      } while ( another == 'y' ) ;
}

And here is the sample output...

Enter a number 5
square of 5 is 25
Want to enter another number y/n y
Enter a number 7
square of 7 is 49
Want to enter another number y/n n

In this program the do-while loop would keep getting executed till the user continues to answer y. The moment he answers n, the loop terminates, since the condition ( another == 'y' ) fails. Note that this loop ensures that statements within it are executed at least once even if n is supplied first time itself.Though it is simpler to program such a requirement using a do-while loop, the same functionality if required, can also be accomplished using for and while loops as shown below:

/* odd loop using a for loop */
main( )
{
      char  another = 'y' ;
      int  num ;
      for ( ; another == 'y' ; )
 {
            printf ( "Enter a number " ) ;
            scanf ( "%d", &num ) ;
            printf ( "square of %d is %d", num, num * num ) ;
            printf ( "\nWant to enter another number y/n " ) ;
            scanf ( " %c", &another ) ;
 }
}

/* odd loop using a while loop */
main( )
{
      char  another = 'y' ;
      int  num ;

      while ( another == 'y' )
 {
            printf ( "Enter a number " ) ;
            scanf ( "%d", &num ) ;
            printf ( "square of %d is %d", num, num * num ) ;
            printf ( "\nWant to enter another number y/n " ) ;
            scanf ( " %c", &another ) ;
 }
}
 

Multiple Initialisations in the for Loop : C programing The Loop Control Structure

The initialisation expression of the for loop can contain more than one statement separated by a comma. For example,

for ( i = 1, j = 2 ; j <= 10 ; j++ )

Multiple statements can also be used in the incrementation expression of for loop; i.e., you can increment (or decrement) two or more variables at the same time. However, only one expression is allowed in the test expression. This expression may contain several conditions linked together using logical operators.
Use of multiple statements in the initialisation expression also demonstrates why semicolons are used to separate the three expressions in the for loop. If commas had been used, they could not also have been used to separate multiple statements in the initialisation expression, without confusing the compiler.

Nesting of Loops

The way if statements can be nested, similarly whiles and fors can also be nested. To understand how nested loops work, look at the program given below:

/* Demonstration of nested loops */
main( )
{
      int   r, c, sum ;
      for ( r = 1 ; r <= 3 ; r++ )  /* outer loop */
 {
            for ( c = 1 ; c <= 2 ; c++ )  /* inner loop */
  {
                  sum = r + c ;
                  printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ;
  }
 }
}

When you run this program you will get the following output:

r = 1 c = 1 sum = 2
r = 1 c = 2 sum = 3
r = 2 c = 1 sum = 3
r = 2 c = 2 sum = 4
r = 3 c = 1 sum = 4
r = 3 c = 2 sum = 5

Here, for each value of r the inner loop is cycled through twice, with the variable c taking values from 1 to 2. The inner loop
terminates when the value of c exceeds 2, and the outer loop terminates when the value of r exceeds 3. 
As you can see, the body of the outer for loop is indented, and the body of the inner for  loop is further indented. These multiple
indentations make the program easier to understand.  Instead of using two statements, one to calculate sum and another to print it out, we can compact this into one single statement by saying:

printf ( "r = %d c = %d sum = %d\n", r, c, r + c ) ;

The way for  loops have been nested here, similarly, two while loops can also be nested. Not only this, a for loop can occur within a while loop, or a while within a for. 

The for Loop

Perhaps one reason why few programmers use while is that they are too busy using the for, which is probably the most popular looping instruction. The for allows us to specify three things about a loop in a single line: 

(a)  Setting a loop counter to an initial value.
(b)  Testing the loop counter to determine whether its value has reached the number of repetitions desired.
(c)  Increasing the value of loop counter each time the program segment within the loop has been executed.
The general form of for statement is as under:

for ( initialise  counter ; test  counter ; increment  counter )
{
  do this ;
      and this ; 
  and this ;
}

Let us write down the simple interest program using for. Compare this program with the one, which we wrote using while. The flowchart is also given below for a better understanding.



/* Calculation of simple interest for 3 sets of p, n and r */ 
main ( )
{
  int   p, n, count ;
  float   r, si ;
 
  for ( count = 1 ; count <= 3 ; count = count + 1 )
 {
    printf ( "Enter values of p, n, and r " ) ;
    scanf ( "%d %d %f", &p, &n, &r ) ;

    si = p * n * r / 100 ;
    printf ( "Simple Interest = Rs.%f\n", si ) ;
 }


If this program is compared with the one written using while, it can be seen that the three steps—initialization, testing and incrementation—required for the loop construct have now been incorporated in the for statement.
Let us now examine how the for statement gets executed:

  When the for statement is executed for the first time, the value of count is set to an initial value 1.

  Now the condition count <= 3 is tested. Since count is 1 the condition is satisfied and the body of the loop is executed for the first time.

−  Upon reaching the closing brace of for, control is sent back to the for statement, where the value of count gets incremented by 1.

−  Again the test is performed to check whether the new value of count exceeds 3.

−  If the value of count  is still within the range 1 to 3, the statements within the braces of for are executed again.

−  The body of the for loop continues to get executed till count doesn’t exceed the final value 3. 

−  When count reaches the value 4 the control exits from the loop and is transferred to the statement (if any) immediately after the body of for.

The following figure would help in further clarifying the concept of execution of the for loop.



It is important to note that the initialization, testing and incrementation part of a for loop can be replaced by any valid expression. Thus the following for loops are perfectly ok.

for ( i = 10 ; i ; i -- )
  printf ( "%d", i ) ;
for ( i < 4 ; j = 5 ; j = 0 )
  printf ( "%d", i ) ;
for ( i = 1; i <=10 ; printf ( "%d",i++ )
 ;
for ( scanf ( "%d", &i ) ; i <= 10 ; i++ )
  printf ( "%d", i ) ;

Let us now write down the program to print numbers from 1 to 10 in different ways. This time we would use a for loop instead of a while loop.

(a)  main( )
{
     int   i ;
     for ( i = 1 ; i <= 10 ; i = i + 1 )
           printf ( "%d\n", i ) ;
}

 Note that the initialisation, testing and incrementation of loop counter is done in the for statementitself.Instead of i = i + 1, the statements i++ or i += 1 can also be used.  Since there is only one statement in the body of the for loop, the pair of braces have been dropped. As with the while, the default scope of for is the immediately next statement after for.

(b)  main( )
{
     int   i ;
     for ( i = 1 ; i <= 10 ; )
 {
           printf ( "%d\n", i ) ;
           i = i + 1 ;
 }
}

 Here, the incrementation is done within the body of the for loop and not in the for statement. Note that inspite of this the semicolon after the condition is necessary. 

(c)  main( )
{
     int   i = 1 ;
     for ( ; i <= 10 ; i = i + 1 )
           printf ( "%d\n", i ) ;
}
Here the initialisation is done in the declaration statement itself, but still the semicolon before the condition is necessary.

(d)  main( )
{
     int   i = 1 ;
     for ( ; i <= 10 ; )
 {
           printf ( "%d\n", i ) ;
           i = i + 1 ;
 }
}
Here, neither the initialisation, nor the incrementation is done in the for statement, but still the two semicolons are necessary.

(e)  main( )
{
     int   i ;
     for ( i = 0 ; i++ < 10 ; )
           printf ( "%d\n", i ) ;
}

 Here, the comparison as well as the incrementation is done through the same statement, i++ < 10. Since the ++ operator comes after i firstly comparison is done, followed by incrementation. Note that it is necessary to initialize i to 0. 

(f)  main( )
{
     int   i ;
     for ( i = 0 ; ++i <= 10 ; )
           printf ( "%d\n", i ) ;
}

Here, both, the comparison and the incrementation is done through the same statement, ++i <= 10. Since ++ precedes i firstly incrementation is done, followed by comparison.
Note that it is necessary to initialize i to 0.

More Operators

There are variety of operators which are frequently used with while. To illustrate their usage let us consider a problem wherein numbers from 1 to 10 are to be printed on the screen. The program for performing this task can be written using while  in the following different ways:

(a)  main( )
{
     int   i = 1 ;
     while ( i <= 10 )
 {
           printf ( "%d\n", i ) ;
           i = i + 1 ;
 }
}
(b)  main( )
{
  int   i = 1 ;
     while ( i <= 10 )
 {
           printf ( "%d\n", i ) ;
  i++ ;
 }
}

 Note that the increment operator ++ increments the value of i by 1, every time the statement i++ gets executed. Similarly, to reduce the value of a variable by 1 a decrement operator -- is also available. 
However, never use n+++ to increment the value of n by 2, since C doesn’t recognize the operator +++.

(c)  main( )
{
     int   i = 1 ;
     while ( i <= 10 )
 {
           printf ( "%d\n", i ) ;
           i += 1 ;
 }
}

 Note that +=  is a compound assignment operator. It increments the value of i by 1. Similarly, j = j + 10 can also be written as j += 10. Other compound assignment operators are -=, *=, / = and %=.

(d)  main( )
{
     int  i = 0 ;
     while ( i++ < 10 )
printf ( "%d\n", i ) ;
}

 In the statement while ( i++ < 10 ), firstly the comparison of value of i with 10 is performed, and then the incrementation of i takes place. Since the incrementation of i happens after its usage, here the ++ operator is called a post-incrementation operator. When the control reaches printf ( ),  i has already been incremented, hence i must be initialized to 0. 

(e)  main( )
{
     int  i = 0 ;
     while ( ++i <= 10 )
        printf ( "%d\n", i ) ;
}

 In th statement    e  while ( ++i <= 10 ), firstly incrementation of i takes place, then the comparison of value of i with 10 is performed. Since the incrementation of i happens before its usage, here the ++ operator is called a pre- incrementation operator

Tips and Traps

The general form of while is as shown below:

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

Note the following points about while...

−  The statements within the while loop would 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.

In place of the condition there can be any other valid expression. So long as the expression evaluates to a non-zero value the statements within the loop would get executed.

−  The condition being tested may use relational or logical operators as shown in the following examples:

 while ( i <= 10 )
while ( i >= 10 && j <= 15 ) 
while ( j > 10 && ( b < 15 || c < 20 ) )

−  The statements within the loop may be a single line or a block of statements. In the first case the parentheses are optional. For example,

 while ( i <= 10 )
     i = i + 1 ;
is same as

 while ( i <= 10 )
{
     i = i + 1 ;
}

−  As a rule the while must test a condition that will eventually become false, otherwise the loop would be executed forever, indefinitely.

 main( )

     int   i = 1 ;
     while ( i <= 10 )
        printf ( "%d\n", i ) ; 
}
This is an indefinite loop, since i remains equal to 1 forever. The correct form would be as under:

 main( )
{
     int   i = 1 ;
     while ( i <= 10 )
 {
           printf ( "%d\n", i ) ;
           i = i + 1 ;
 }
}

−  Instead of incrementing a loop counter, we can even decrement it and still manage to get the body of the loop executed
repeatedly. This is shown below:

 main( )
{
     int   i = 5 ;
     while ( i >= 1 )
 {
           printf ( "\nMake the computer literate!" ) ;
           i = i - 1 ;
 }
}

−  It is not necessary that a loop counter must only be an int. It can even be a float.

 main( )
{
     float   a = 10.0 ;
     while ( a <= 10.5 )
 {
           printf ( "\nRaindrops on roses..." ) ;
           printf ( "...and whiskers on kittens" ) ;
           a = a + 0.1 ;
 }
}

−  Even floating point loop counters can be decremented. Once again the increment and decrement could be by any value, not necessarily

What do you think would be the output of the following
program?

 main( )
{
     int   i = 1 ;
     while ( i <= 32767 )
 {
           printf ( "%d\n", i ) ;
           i = i + 1 ;
 }
}

 No, it doesn’t print numbers from 1 to 32767. It’s an indefinite loop. To begin with, it prints out numbers from 1 to 32767. After that value of i is incremented by 1, therefore it tries to become 32768, which falls outside the valid integer range, so it goes to other side and becomes -32768 which would certainly satisfy the condition in the while. This process goes on indefinitely.
−  What will be the output of the following program?

 main( )
{
     int   i = 1 ;
     while ( i <= 10 ) ;
 {
           printf ( "%d\n", i ) ;
           i = i + 1 ;
 }
}
This is another indefinite loop, and it doesn’t give any output at all. The reason is, we have carelessly given a ; after the while. This would make the loop work like this...

 while ( i <= 10 )
 ;
{
     printf ( "%d\n", i ) ;
     i = i + 1 ;
}

 Since the value of i is not getting incremented the control would keep rotating within the loop, eternally. Note that enclosing printf( ) and i = i +1 within a pair of braces is not an error. In fact we can put a pair of braces around any individual statement or set of statements without affecting the execution of the program.