Monday, April 1, 2013

The traffic light program (nested ifs)

A program that displays the recommended actions depending on the color of a traffic light. This program uses nested if statements.

/* The traffic light program (nested ifs) */
#include <stdio.h> int main (void) { char colour; /* ask user for colour */ printf ("Enter the colour of the light (R, G or Y): "); scanf ("%c", &colour); /* test if colour is red */ if (colour == 'r' || colour == 'R') printf ("STOP! \n"); else if (colour == 'y' || colour == 'Y') /* yellow colour test */ printf ("CAUTION! \n"); else if (colour == 'g' || colour == 'G') /* green colour test */ printf ("GO! \n"); else /* if not Y or G or R then invalid colour */ printf ("INVALID COLOUR! \n"); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter the colour of the light (R, G or Y): G
GO!

1 comment:

  1. here why we are checking the colour in both capital amd small letters

    ReplyDelete