The programs we have written so far behave more or less the same regardless of the input we give them. We will now look at mechanisms which allow our programs to behave differently depending on conditions which exist within the program at the time they are executed.
Often in executing an algorithm we wish to execute a step only if a certain condition holds to be true (e.g., If the light is red, begin applying the brakes). Similarly, we may wish to choose between two courses of action, one if a condition is true, and the other if the condition is false (e.g., If the age is under 21, escort the minor from the establishment, otherwise up-sell toxic substances.).
Our language, C, provides a mechanism to allow us conditionally execute a statement or block of statements:
For example:
#include <stdio.h>
main()
{
float a , b ;
printf( "Enter a number.\n" ) ;
scanf( "%f" , &a ) ;
printf( "Enter another number.\n" ) ;
scanf( "%f" , &b ) ;
if ( a < b )
printf( "%f is less than %f.\n" , a , b ) ;
else if ( a > b )
printf( "%f is greater than %f.\n" , a , b ) ;
else
{
printf( "Congratulations!\n" ) ;
printf( "%f is equal to %f.\n" , a , b ) ;
}
}
| Operator | Description | True | False |
|---|---|---|---|
| < | less than | 1 < 2 | 2 < -3 |
| <= | less than or equal to | ( n % 3 ) <= 2 | ( 2 + 5 ) <= 2 |
| > | greater than | 5 > 2 | ( n % 3 ) > 2 |
| >= | greater than or equal to | 5 >= 5 | 5 >= 5 - 1 |
| == | equal to | 7 == 7 | 4 == ( n % 3 ) + 1 |
| != | not equal to | 7 != 6 | 3 + 2 != 1 + 4 |
| ! | not | ! ( 2 > 3 ) | ! 1 |
| && | and | ( n % 3 <= 2 ) && ( n % 2 <= 1 ) | 1 && 0 |
| || | or | n <= 0 || 0 <= n | ( n % 2 > 5 ) || 0 |
| General Form | Example |
|---|---|
if ( condition ) statement ; |
if ( i < 0 ) printf( "Please enter a non-negative number.\n" ) ; |
if ( condition ) statement ; else statement ; |
if ( n % 2 == 1 ) printf( "odd\n" ) ; else printf( "even\n" ) ; |
if ( condition )
{
statement ;
...
}
else
{
statement ;
...
}
|
if ( age < 21 )
{
printf( "Sorry, kid.\n") ;
printf( "I'm gonna have to ask you to leave.\n" ) ;
}
else
{
printf( "Will that be all?\n" ) ;
printf( "We're running a special on \"Everclear\".\n" ) ;
}
|
Copyright © 1999, Ray Ontko (rayo@ontko.com).