This is the third part of the notes for the C programming course provided
online in the BCPPDOS forum of CompuServe, during January 1995.  The first
part is called NOTEC1.TXT, please read the message in NOTEC1.TXT as to the
use of these notes.

(c)  Terry Hawkes 1995



                         C++ Programming Beginners

                                 Chapter 3

                             TEST Expressions



The if...else Statement


The format of the if statement takes the form:


      if(expr)
            statement1;
      else
            statement2;


Where expr is any expression that can be expressed or converted to an integer
value. If expr is nonzero (true), then statement1 is evaluated; otherwise,
statement2 is evaluated (false).

      if (your_number % 2 == 0)
        printf("Your number is even\n");
      else
        printf("Your number is odd\n");


Two other important points about the if..else statement are:


First, the else statement is optional.


      if (expr)
            statement1;


is a valid statement.


      if (your_number % 2 == 0)
        printf("Your number is even\n");
      if (your_number % 2 != 0)
        printf("Your number is odd\n");
Second, more than one statement can be evaluated for a particular expression:



      if (your_number == 0.0)
            printf("The ratio is undefined\n");
                        /* A single statement */
      else  {
                 ratio = 100 / your_number;
                 printf("The ratio is %f \n",ratio);
            }        /* A compound statement */




Example ifelse1.c

      /*    ifelse1.c       */
      /* A program to demonstrate the if. else statement */

      #include <stdio.h>
      #define YES 'y'   /* YES is defined as the character y, the */
                        /* compiler will replace every instance */
                        /* of YES with the character y */
      main()

      {     /* main */
        int response_integer;
        char response_character;

        printf("Do you like programming in C? (Y/N): ");
        response_integer = getchar( );    /* get character from keyboard */
        response_character = response_integer;  /* convert to character */

        if (response_character == YES)    /* is character 'y' */
          printf("\n\nThere is more in store!");

        else                              /* character is not 'y' */
          {
            printf("\nKeep trying and you'll change your mind!\n");
            printf("Programming needs patience!");
          }

        return 0;
      }     /* main */


Example run

      Do you like programming in C++? (Y/N): Y

      There is more in store
#define

The #define statement tells the preprocessor to replace every instance of YES
with the character y, this is called macro substitution.  C compilers are
multiple pass compilers, that is they take more than one pass through your
code to produce a program from it.  The first pass is by the preprocessor, one
of its jobs is to process any references to the #define statements.


You can see further examples of if-else statements in the examples Intro11.c
and Intro12.C



else-if construction


      if(expression)
            statement;

      else if(expression)
            statement;

      else if (expression)
            statement;

               else
                 statement;


This sequence is one way of writing a multi-way decision.  The expressions are
evaluated in order; if any expression is true the associated statement or
group of statements is executed and the chain terminated.  Only one statement
or group of statements is evaluated.  The last else handles the "none of the
above" or default case.  This is useful for error checking.



See C++ example program Intro13.c
Functions within an if expression

Any assignment statement enclosed in parentheses is an expression that has the
same value as that which was being assigned.  For example the expression  (sum
= 5 + 3) has the value 8, so the expression ((sum = 5 + 8) <= 10) would yield
the value true, since 8 <= 10.


A more exotic example is:


      if ((ch=getch()) =='q')
            puts("Had enough then\n");
      else
            puts("Good move, well have some more\n");


When the program hits the expression ((ch=getch()) == 'q'), it stops until a
character is pressed, it is assigned to ch, then compares the same character
with  q.  If the character pressed equals q, then the message "Had enough
then" is displayed. Otherwise the "Good move..." message is displayed. 
Functions can be called and their results used in the expression part of an
if-else statement. 



SWITCH statement


      The switch statement makes multipath branches easier to code and follow
      than the use of multiple if-else statements.  It takes the form:


            switch(value)
            {
              case value1:statement or group of statements; break;
              case value2:statement; break;
              case value3:statement; break;
              ...
              default:statement or group of statements
            }


The value must be a fixed incremental type, like integers or characters.  Each
of the values following a 'case' is compared with 'value'.  If a match is
found then the statement following is evaluated.  The break statement at the
end of each case is very important.  It causes execution to jump past the end
of the switch statement.  It is usual to include a break statement as the last
statement for each case.


Try the example program Intro14.c then remove all the break statements and see
what happens when you run the program again.
The Ternary Operator (?:)


This is a good one if you want to confuse people who do not understand the
syntax of a C program, it comes under 'economical syntax' mentioned in part
one. The ternary operator enables you to choose between two expressions, if
a condition is true or false.  This can be accomplished with the use of the
if..else statement, such as in the function imin below, which returns the
smaller of two numbers:


      int  imin(int a, int b)
      {
            if (a < b)
              return(a);
            else
              return(b);
      }



The if..else statement is used often enough to warrant a special operator. 
The format is:


            expr1 ? expr2 : expr3


This is interpreted as follows: " If expr1 is true, then evaluate expr2 and
let the entire expression assume its value; otherwise, evaluate expr3 and
assume its value."  You can rewrite the function imin as follows:



      int  imin(int a, int b)
      {
            return((a < b) ? a : b);
      }

which still returns the smaller of the two numbers.


This can be rewritten as an inline macro:


      #define imin(a,b) ((a < b) ? a : b)


Now whenever your program sees the call to function imin(e1, e2), the
preprocessor replaces it with ((e1 < e2) ? e1 : e2). This is a more general
solution, since a and b are no longer limited to being type int; they can be
any type that allows the < relationship.

Now that's economical syntax!  I leave it up to you to decide which form to
use, though I do encourage my students to make their programming code
readable.

Example Program ternary.c


/* A program to demonstrate the ternary operator */
      #include <stdio.h>
      void main(void)
      {     /* main */
        int num1, num2, dummy,numerator, divisor;

        printf("Please type in two integers less than 10.\n-> ");
        scanf("%d %d", &num1, &num2);

        divisor=(num1 > num2) ? num2 : num1; 
                        /* smallest in divisor */

        numerator=(num1 < num2) ? num2 : num1;
                        /* largest in numerator */
        printf("\nThe largest number will now be divided by the smallest
number:");
        printf("\n\n\t%d / %d = %d\n",numerator,divisor,numerator/divisor);
      }     /*main */                              /* this is the division */



Example Run

Please type in two integers less than 10
-> 2 8


The largest number has been divided by the smallest number:

            8 / 2 = 4






Practical 3.1

Write a C program to read in two integers and print out the larger of the two.


Practical 3.2

Write a C program which will identify a character input from the keyboard as
either a letter, a number, a punctuation mark or an unidentified character. 
Use the Ascii table values with several if statements.
