Monday, April 1, 2013

Input validation loop (do-while)

A program that shows the best use of a do-while loop, an input validation loop. This particular program validates that the color entered is a valid traffic light color.

/* Input validation loop (do-while) */
#include <stdio.h> int main (void) { char colour; /* ask user for colour */ do { printf ("Enter the colour of the light (R,G,Y,A): "); scanf (" %c", &colour); /* very important to leave space before %c here */ }while (colour!='R' && colour!='r' && colour!='G' && colour!='g' && colour!='Y' && colour!='y' && colour!='A' && colour!='a'); /* test the alternatives */ switch (colour) { /* red light */ case 'R': case 'r': printf ("STOP! \n"); break; /* yellow or amber light */ case 'Y': case 'y': case 'A': case 'a': printf ("CAUTION! \n"); break; /* green light */ case 'G': case 'g': printf ("GO! \n"); break; /* no default case necessary here */ } return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter the colour of the light (R,G,Y,A): b
Enter the colour of the light (R,G,Y,A): x
Enter the colour of the light (R,G,Y,A): G
GO!

No comments:

Post a Comment