Odd loop in C Programming

Odd loop in C Programming

Odd loop in C Programming

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

Previous
Next Post »

1 comments:

Click here for comments
Unknown
admin
7 May 2016 at 15:34 ×

Thank you for giving this type of nice article.I am very glad to inform you that it is very understand everything that you said.Really i wish to thank you.It is about Odd loop in C Programming and you cover everything that related information.It is nice post with understanding a lot.Custom essay writing service is the better service that provides detailed and effective information related to educational basis.

Congrats bro Unknown you got PERTAMAX...! hehehehe...
Reply
avatar