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.



Loops

The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being Satisfied This respective operation is fone through a loop controal instraction

There are three methods by way of which we can repeat a part of a program Thay are;
(a) Using a for statement 
(b) Using a while statement 
(c) Using a do-while statement
Each of these methods is discussed in the following pages

Summary

(a) There are three ways for taking decisions in a program. First way is to use the if-else statement, second way is to use theconditional operators and third way is to use the switch statement.

(b) The default scope of the if statement is only the next statement. So, to execute more than one statement they must be written in a pair of braces.

(c) An if block need not always be associated with an else block. However, an else block is always associated with an if statement.

(d) If the outcome of an if-else ladder is only one of two answers then the ladder should be replaced either with an else-if clause or by logical operators.

(e) && and || are binary operators, whereas, ! is a unary operator.

 (f) In C every test expression is evaluated in terms of zero and non-zero values. A zero value is considered to be false and a non-zero value is considered to be true.

(g) Assignment statements used with conditional operators must be enclosed within a pair of parenthesis.

The Conditional Operators

The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. Their general form is,
expression 1 ? expression 2 : expression 3
What this expression says is: “if expression 1 is true (that is, if its value is non-zero), then the value returned will be expression 2, otherwise the value returned will be expression 3”. Let us understand this with the help of a few examples:

(a) int x, y ;
scanf ( "%d", &x ) ;
y = ( x > 5 ? 3 : 4 ) ;
This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.
The equivalent if statement will be,
if ( x > 5 )
y = 3 ;
else
y = 4 ;

(b) char a ;
int y ;
scanf ( "%c", &a ) ;
y = ( a >= 65 && a <= 90 ? 1 : 0 ) ;
Here 1 would be assigned to y if a >=65 && a <=90 evaluates to true, otherwise 0 would be assigned.
The following points may be noted about the conditional operators:

(a)It’s not necessary that the conditional operators should be used only in arithmetic statements. This is illustrated in the following examples:

Ex.: int i ;
scanf ( "%d", &i ) ;
( i == 1 ? printf ( "Amit" ) : printf ( "All and sundry" ) ) ;
Ex.: char a = 'z' ;
printf ( "%c" , ( a >= 'a' ? a : '!' ) ) ;

(b) The conditional operators can be nested as shown below.
int big, a, b, c ;
big = ( a > b ? ( a > c ? 3: 4 ) : ( b > c ? 6: 8 ) ) ;
Check out the following conditional expression:
a > b ? g = a : g = b ;

(c) This will give you an error ‘Lvalue Required’. The error can be overcome by enclosing the statement in the : part within a pair of parenthesis. This is shown below:
a > b ? g = a : ( g = b ) ;

In absence of parentheses the compiler believes that b is being assigned to the result of the expression to the left of second =. Hence it reports an error.
The limitation of the conditional operators is that after the ? or after the : only one C statement can occur. In practice rarely is this the requirement. Therefore, in serious C programming conditional operators aren’t as frequently used as the if-else.

A Word of Caution

What will be the output of the following program:

main( )
{
int i ;
printf ( "Enter value of i " ) ;
scanf ( "%d", &i ) ;
if ( i = 5 )
printf ( "You entered 5" ) ;
else
printf ( "You entered something other than 5" ) ;
}

And here is the output of two runs of this program...
Enter value of i 200
You entered 5
Enter value of i 9999
You entered 5
Surprising? You have entered 200 and 9999, and still you find in either case the output is ‘You entered 5’. This is because we have written the condition wrongly. We have used the assignment operator = instead of the relational operator ==. As a result, the condition gets reduced to if ( 5 ), irrespective of what you supply as the value of i. And remember that in C ‘truth’ is always non-zero, whereas ‘falsity’ is always zero. Therefore, if ( 5 ) always evaluates to true and hence the result.
Another common mistake while using the if statement is to write a semicolon (;) after the condition, as shown below:

main( )
{
int i ;
printf ( "Enter value of i " ) ;
scanf ( "%d", &i ) ;
if ( i == 5 ) ;
printf ( "You entered 5" ) ;
}

The ; makes the compiler to interpret the statement as if you have written it in following manner:
if ( i == 5 )
;
printf ( "You entered 5" ) ;
Here, if the condition evaluates to true the ; (null statement, which does nothing on execution) gets executed, following which the printf( ) gets executed. If the condition fails then straightaway the printf( ) gets executed. Thus, irrespective of whether the condition evaluates to true or false the printf( ) is bound to get executed. Remember that the compiler would not point out this as an error, since as far as the syntax is concerned nothing has gone wrong, but the logic has certainly gone awry. Moral is, beware of such pitfalls.

The following figure summarizes the working of all the three logical operators.


Hierarchy of Operators Revisited

Since we have now added the logical operators to the list of operators we know, it is time to review these operators and their priorities. Figure 2.7 summarizes the operators we have seen so far. The higher the position of an operator is in the table, higher is its priority. (A full-fledged precedence table of operators is given in Appendix A.)


The ! Operator

So far we have used only the logical operators && and ||. The third logical operator is the NOT operator, written as !. This operator reverses the result of the expression it operates on. For example, if the expression evaluates to a non-zero value, then applying ! operator to it results into a 0. Vice versa, if the expression evaluates to zero then on applying ! operator to it makes it 1, a non-zero value. The final result (after applying !) 0 or 1 is considered to be false or true respectively. Here is an example of the NOT operator applied to a relational expression.
! ( y < 10 )

This means “not y less than 10”. In other words, if y is less than 10, the expression will be false, since ( y < 10 ) is true. We can express the same condition as ( y >= 10 ).
The NOT operator is often used to reverse the logical value of a single variable, as in the expression
if ( ! flag )
This is another way of saying
if ( flag == 0 )
Does the NOT operator sound confusing? Avoid it if you want, as the same thing can be achieved without using the NOT operator.