Using an infinite loop to implement a menu system. - C Statement

C examples for Statement:for

Description

Using an infinite loop to implement a menu system.

Demo Code

#include <stdio.h>

/* Displays a menu and inputs user's selection. */
int menu(void)
{
    int reply;/*from  www  .  j a va2 s. co  m*/

    puts("\nEnter 1 for task A.");
    puts("Enter 2 for task B.");
    puts("Enter 3 for task C.");
    puts("Enter 4 for task D.");
    puts("Enter 5 to exit program.");

    scanf("%d", &reply);

    return reply;
}
int main( void ){
   int choice;

   while (1)   {

    /* Get the user's selection. */

    choice = menu();

    /* Branch based on the input. */

    if (choice == 1)
    {
        puts("\nExecuting task A.");
    }
    else if (choice == 2)
         {
             puts("\nExecuting task B.");
         }
    else if (choice == 3)
         {
             puts("\nExecuting task C.");
         }
    else if (choice == 4)
         {
             puts("\nExecuting task D.");
         }
    else if (choice == 5)       /* Exit program. */
         {
             puts("\nExiting program now...\n");
             break;
         }
         else
         {
             puts("\nInvalid choice, try again.");
         }
   }
   return 0;
}

Result


Related Tutorials