Sunday, October 30, 2011

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 ) ;
 }
}
 

1 comment:

  1. can you give example of finding prime no using odd loop

    ReplyDelete