if and else

CS35: Programming and Problem Solving
Ray Ontko
Department of Computer Science
Earlham College

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

Conditions

In C, a condition is a numeric expression. If the expression evaluates to the value 0 (zero), then the condition is said to be false; if the expression evaluates to a non-zero value, then the condition is said to be true. Thus, the values 1, 9, -38, 23, 0.001, all are considered to be true, while 0 and 0.0 are considered false.

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

Statements and Blocks

The conditionally executed portion of an if or if else statement may be a statement or a block. A statement is any executable statement in C (e.g., a function call, an assignment statement, but not a declaration), while a block is a sequence of zero or more such executable statements enclosed between { and }.

General FormExample
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).