Wednesday, October 26, 2011

The while Loop

It is often the case in programming that you want to do Somthing a fixed number of times. Perhaps you want to calculate grosssalaries of ten different persons, or you want to converttemperatures from centigrade to fahrenheit for 15 different citiesThe while loop is isimple example, wdeally suited for such cases. Let us look at ahich uses a while loop. The flowchart showncount = 1 ;below would help you to understand the operation of the while loop.






/* Calculation of simple interest for 3 sets of p, n and r */ 
main( )
{
int p, n, count 
float r, si ;
count = 1 ;
while ( count <= 3 )
 {
        printf ( "\nEnter values of p, n and r " ) ;
            scanf ( "%d %d %f", &p, &n, &r ) ;
            si = p * n * r / 100 ;
        printf ( "Simple interest = Rs. %f", si ) ;
  
            count = count + 1 ;
 }
}

And here are a few sample runs...

Enter values of p, n and r  1000  5  13.5
Simple  interest = Rs. 675.0000im e i 00
Enter values of p, n and r  2000  5  13.5
Simple interest = Rs. 1350.000000
Enter values of p, n and r  3500  5  3.5
Simple interest = Rs. 612.500000
The program executes all statements after the while 3 times. The logic for calculating the simple interest is written within a pair of braces immediately after the while keyword. These statements form what is called the‘body’ of the while loop. The parentheses after the while contain a condition. So long as this condition remains true all statements within the body of the while loop keep getting executed repeatedly. To begin with the variable count is initialized to 1 and every time the simple interest logic is executed the value of count is incremented by one. The variable count is many a times called either a ‘loop counter’ or an ‘index variable’.
The operation of the while  loop is illustrated in the following figure.



1 comment:

  1. "I very much enjoyed this article.Nice article thanks for given this information. i hope it useful to many pepole.php jobs in hyderabad.
    "

    ReplyDelete