Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: May 8, 2024
Difficulty: Easy

Menu Driven Program in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

A menu driven program in C is a type of program that presents a list of options to the user & allows them to choose what they want the program to do. The user can select an option by entering a number or letter corresponding to their choice. Based on the user's input, the program performs the selected task or operation. Menu driven programs make it easy for users to interact with a program, even if they don't have a lot of technical knowledge. 

Menu Driven Program in C

In this article, we will learn what menu driven programs are, how to create them using different methods in C, with different examples to help you understand the concept better.

Algorithm for Menu Driven Program in C

Creating a menu-driven program in C involves a sequence of logical steps that ensure smooth & effective user interaction. Here’s a straightforward way to structure your program:

  1. Display Menu Options: Start by presenting the user with a list of actions or choices. This is typically done using printf statements that enumerate possible commands or functions available in the program.
     
  2. User Input for Selection: Prompt the user to make a choice. This is generally achieved with a scanf statement that reads the user's input, usually a number corresponding to an option.
     
  3. Processing the Selection: Utilize a control structure like an if-else ladder or a switch case to execute different blocks of code based on the user’s selection. Each block will correspond to a specific functionality of the program.
     
  4. Looping the Menu: To allow continuous operation until the user decides to exit, wrap the menu display and selection process in a while loop. This loop will continue to execute until a particular exit condition is met, which is usually triggered by a specific user input (e.g., entering '0' to exit).
     
  5. Exit the Program: Include an option to exit the loop & terminate the program gracefully. This ensures that the user can stop the program's execution at their convenience.


Here's a simple pseudocode to illustrate these steps:

while(user does not want to exit):
    display menu()
    choice = get user input()
    if choice == 1:
        perform action1()
    else if choice == 2:
        perform action2()
    else if choice == exit option:
        break
    else:
        display an error message()
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples of Menu-Driven Programs in C

These examples will highlight how to construct a menu, handle user input, and perform actions based on that input.

Example 1: Basic Menu-Driven Program

This simple example demonstrates a menu that allows the user to choose between two operations: adding two numbers and exiting the program.

  • C

C

#include <stdio.h>

int main() {

   int choice;

   int num1, num2, sum;

   while(1) {

       printf("Menu:\n");

       printf("1. Add Numbers\n");

       printf("2. Exit\n");

       printf("Enter your choice (1-2): ");

       scanf("%d", &choice);

       switch(choice) {

           case 1:

               printf("Enter two numbers: ");

               scanf("%d %d", &num1, &num2);

               sum = num1 + num2;

               printf("Sum = %d\n", sum);

               break;

           case 2:

               printf("Exiting program.\n");

               return 0;

           default:

               printf("Invalid choice, please try again.\n");

       }

   }

   return 0;

}

Output

Menu:
1. Add Numbers
2. Exit
Enter your choice (1-2): 1
Enter two numbers: 4 5
Sum = 9
Menu:
1. Add Numbers
2. Exit
Enter your choice (1-2): 2
Exiting program.


In this program, the while loop continues to run, displaying the menu until the user selects the option to exit. The switch case structure processes the user's choice, either performing the addition or terminating the program.

Example 2: Menu-Driven Program Using Functions

This example expands on the basic structure by using functions to handle different tasks, making the code more modular and easier to manage.

  • C

C

#include <stdio.h>

void addNumbers() {

   int a, b;

   printf("Enter two integers: ");

   scanf("%d %d", &a, &b);

   printf("Result: %d\n", a + b);

}

void exitProgram() {

   printf("Thank you for using the program.\n");

}

int main() {

   int choice;

   while(1) {

       printf("Menu:\n");

       printf("1. Add Numbers\n");

       printf("2. Exit\n");

       printf("Enter your choice (1-2): ");

       scanf("%d", &choice);

       switch(choice) {

           case 1:

               addNumbers();

               break;

           case 2:

               exitProgram();

               return 0;

           default:

               printf("Invalid choice, please try again.\n");

       }

   }

}

Output

Menu:
1. Add Numbers
2. Exit
Enter your choice (1-2): 2
Thank you for using the program.


Here, each menu option calls a specific function: addNumbers() for addition, and exitProgram() for exiting. This approach enhances the clarity and reusability of the code.

Program to Create a Menu Driven Software in C

To build a more comprehensive menu-driven software in C, we can develop a program that incorporates multiple functionalities. This type of program provides a more robust example of how menu-driven interfaces facilitate user interaction with various functionalities. Here’s how you can structure such a program:

Step-by-Step Creation of a Multi-Functional Menu-Driven Software

  1. Define Functions for Each Task: Start by writing separate functions for each task that your software is supposed to perform. This can include operations like calculations, data processing, or even file management, depending on what your program aims to achieve.
     
  2. Design the Menu: Construct a clear and concise menu that lists all the options available to the user. Ensure each menu item is numbered and described briefly so users can easily choose the task they need.
     
  3. Implement User Input Handling: Use scanf to capture user input, which corresponds to the menu item number. This input directs which function to execute.
     
  4. Execute Functions Based on Input: Use a switch statement or an if-else chain to execute the function corresponding to the user’s choice.
     
  5. Loop the Menu: Encase your menu in a while loop to allow multiple operations during a single program run. Provide an option to exit the menu loop, usually by entering a specific command like '0' for exit.

Example Code

Here is an example code that shows a menu-driven program capable of performing three different tasks:

  • C

C

#include <stdio.h>

void displayMessage() {

   printf("Hello, welcome to our program!\n");

}

void addNumbers() {

   int num1, num2;

   printf("Enter two numbers to add: ");

   scanf("%d %d", &num1, &num2);

   printf("The sum is: %d\n", num1 + num2);

}

void multiplyNumbers() {

   int num1, num2;

   printf("Enter two numbers to multiply: ");

   scanf("%d %d", &num1, &num2);

   printf("The product is: %d\n", num1 * num2);

}

int main() {

   int choice;

   while(1) {

       printf("\nMenu:\n");

       printf("1. Display Welcome Message\n");

       printf("2. Add Two Numbers\n");

       printf("3. Multiply Two Numbers\n");

       printf("4. Exit\n");

       printf("Enter your choice (1-4): ");

       scanf("%d", &choice);


       switch(choice) {

           case 1:

               displayMessage();

               break;

           case 2:

               addNumbers();

               break;

           case 3:

               multiplyNumbers();

               break;

           case 4:

               printf("Exiting program.\n");

               return 0;

           default:

               printf("Invalid choice, please try again.\n");

       }

   }

}

Output

Menu:
1. Display Welcome Message
2. Add Two Numbers
3. Multiply Two Numbers
4. Exit
Enter your choice (1-4): 1
Hello, welcome to our program!
Menu:
1. Display Welcome Message
2. Add Two Numbers
3. Multiply Two Numbers
4. Exit
Enter your choice (1-4): 3
Enter two numbers to multiply: 4 5
The product is: 20
Menu:
1. Display Welcome Message
2. Add Two Numbers
3. Multiply Two Numbers
4. Exit
Enter your choice (1-4): 4
Exiting program.


In this code, the program offers a menu with three operations plus an exit option. Functions are invoked based on user choices, and the program can be repeatedly used until the user decides to exit.

Program to Create a Menu Driven Software in C Using Switch Case

Switch cases in C are a powerful tool for handling multiple choice scenarios, making them ideal for menu-driven programs. This approach allows for a clean and efficient handling of user commands based on their input. Here’s a step-by-step guide on how to implement a menu-driven program using a switch case statement.

Steps to Implement Switch Case in Menu-Driven Programs

  1. Define the Menu: Begin by designing a menu that clearly outlines the options available to the user. Each option should have a unique identifier, typically an integer, which the user will input to select their choice.
     
  2. Capture User Input: Prompt the user to enter their choice and use scanf to read this input into a variable. This variable will be used in the switch case to determine which action to perform.
     
  3. Implement Switch Case Logic: Use the switch statement to execute a different block of code depending on the user’s input. Each case within the switch corresponds to a menu option.
     
  4. Include a Default Case: Always include a default case in your switch statement to handle unexpected input gracefully. This case can inform the user that they have made an invalid selection and prompt them to try again.
     
  5. Loop the Menu: To allow the user to perform multiple operations without restarting the program, enclose the menu display and switch statement inside a while loop. This loop should continue until the user selects the option to exit.

Example Code with Switch Case

Here’s a practical example of a menu-driven program using a switch case to handle user input:

  • C

C

#include <stdio.h>

void greetUser() {

   printf("Welcome to our simple menu-driven program!\n");

}

void calculateSum() {

   int x, y;

   printf("Enter two integers: ");

   scanf("%d %d", &x, &y);

   printf("The sum of %d and %d is %d.\n", x, y, x + y);

}

void calculateProduct() {

   int x, y;

   printf("Enter two integers: ");

   scanf("%d %d", &x, &y);

   printf("The product of %d and %d is %d.\n", x, y, x * y);

}

int main() {

   int choice;

   while(1) {

       printf("\nMenu:\n");

       printf("1. Greet User\n");

       printf("2. Calculate Sum\n");

       printf("3. Calculate Product\n");

       printf("4. Exit\n");

       printf("Please enter your choice (1-4): ");

       scanf("%d", &choice);


       switch(choice) {

           case 1:

               greetUser();

               break;

           case 2:

               calculateSum();

               break;

           case 3:

               calculateProduct();

               break;

           case 4:

               printf("Thank you for using our program. Goodbye!\n");

               return 0;

           default:

               printf("Invalid choice, please try again.\n");

       }

   }

}
Output
Menu:
1. Greet User
2. Calculate Sum
3. Calculate Product
4. Exit
Please enter your choice (1-4): 1
Welcome to our simple menu-driven program!
Menu:
1. Greet User
2. Calculate Sum
3. Calculate Product
4. Exit
Please enter your choice (1-4): 2
Enter two integers: 5 7
The sum of 5 and 7 is 12.
Menu:
1. Greet User
2. Calculate Sum
3. Calculate Product
4. Exit
Please enter your choice (1-4): 4
Thank you for using our program. Goodbye!

Program to Create a Menu Driven Software in C Using Functions

Using functions in a menu-driven program not only organizes your code better but also makes it easier to manage, especially as programs grow more complex. Functions allow you to compartmentalize tasks, making each part of your program responsible for a specific operation. Here’s a are few steps on how to structure a menu-driven program in C using functions effectively.

Benefits of Using Functions in Menu-Driven Programs

  • Modularity: Each task is encapsulated in its own function, making the program easier to understand and modify.
     
  • Reusability: Functions can be called multiple times throughout the program or even in different programs.
     
  • Error Handling: By isolating code into functions, it becomes simpler to manage errors and debug specific parts of the program without affecting others.

Implementing Functions in a Menu-Driven Program

  • Define Functions for Operations: Begin by defining functions for all the operations you plan to include in your menu. This could be calculations, data processing, etc.
     
  • Create the Menu Function: Implement a function to display the menu options to the user. This helps keep your main function clean and focused on the overall logic.
     
  • Main Program Logic: Use the main function to handle the flow of the program. It should capture user inputs, call the appropriate functions based on those inputs, and manage the program’s running state.
     
  • Loop and Control Structure: Incorporate a loop in the main function to continually display the menu and respond to user inputs until the exit condition is met.

Example Code with Functions

Here’s a detailed example demonstrating a menu-driven program that uses functions to perform different tasks:

  • C

C

#include <stdio.h>

// Function declarations

void displayMenu();

void handleUserInput(int choice);

void greetUser();

void calculateSum();

void calculateProduct();

int main() {

   int choice;

   do {

       displayMenu();

       scanf("%d", &choice);

       handleUserInput(choice);

   } while (choice != 4);

   return 0;

}

// Function to display the menu

void displayMenu() {

   printf("\nMenu:\n");

   printf("1. Greet User\n");

   printf("2. Calculate Sum\n");

   printf("3. Calculate Product\n");

   printf("4. Exit\n");

   printf("Select an option (1-4): ");

}

// Function to process user input

void handleUserInput(int choice) {

   switch (choice) {

       case 1:

           greetUser();

           break;

       case 2:

           calculateSum();

           break;

       case 3:

           calculateProduct();

           break;

       case 4:

           printf("Exiting the program. Thank you for using it!\n");

           break;

       default:

           printf("Invalid choice, please try again.\n");

   }

}

// Function to greet the user

void greetUser() {

   printf("Hello! Welcome to our program.\n");

}

// Function to calculate the sum of two numbers

void calculateSum() {

   int num1, num2;

   printf("Enter two numbers: ");

   scanf("%d %d", &num1, &num2);

   printf("The sum is: %d\n", num1 + num2);

}

// Function to calculate the product of two numbers

void calculateProduct() {

   int num1, num2;

   printf("Enter two numbers: ");

   scanf("%d %d", &num1, &num2);

   printf("The product is: %d\n", num1 * num2);

}

Output

Menu:
1. Greet User
2. Calculate Sum
3. Calculate Product
4. Exit
Select an option (1-4): 1
Hello! Welcome to our program.
Menu:
1. Greet User
2. Calculate Sum
3. Calculate Product
4. Exit
Select an option (1-4): 4
Exiting the program. Thank you for using it!


This example clearly shows how to divide your program into functions to manage different functionalities effectively. Using functions enhances code readability and maintenance, making it easier to update or expand your program in the future.

Frequently Asked Questions

What is the main advantage of using a menu-driven program in C?

Menu-driven programs enhance user interaction by providing a clear set of options, reducing errors from incorrect input and making the program more user-friendly.

Can I use functions from other files in my menu-driven program?

Yes, you can include functions from other files using the C #include directive. This helps in organizing code into modules, making it more manageable and reusable.

How do I ensure that the user input is valid in a menu-driven program?

To ensure valid input, you can implement a loop that checks whether the entered value is within the expected range and prompts the user to re-enter the choice if it's not.

Conclusion

In this article, we have learned about the structure and implementation of menu-driven programs in C. Starting from the basics, we covered how to create simple menus, handle user input with switch cases, and modularize code using functions for better management and clarity. With the help of these techniques, you can develop efficient and user-friendly console applications that are easy to navigate and maintain. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Topics covered
1.
Introduction
2.
Algorithm for Menu Driven Program in C
3.
Examples of Menu-Driven Programs in C
3.1.
Example 1: Basic Menu-Driven Program
3.2.
C
3.3.
Example 2: Menu-Driven Program Using Functions
3.4.
C
4.
Program to Create a Menu Driven Software in C
4.1.
Step-by-Step Creation of a Multi-Functional Menu-Driven Software
4.2.
Example Code
4.3.
C
5.
Program to Create a Menu Driven Software in C Using Switch Case
5.1.
Steps to Implement Switch Case in Menu-Driven Programs
5.2.
Example Code with Switch Case
5.3.
C
6.
Program to Create a Menu Driven Software in C Using Functions
6.1.
Benefits of Using Functions in Menu-Driven Programs
6.2.
Implementing Functions in a Menu-Driven Program
6.3.
Example Code with Functions
6.4.
C
7.
Frequently Asked Questions
7.1.
What is the main advantage of using a menu-driven program in C?
7.2.
Can I use functions from other files in my menu-driven program?
7.3.
How do I ensure that the user input is valid in a menu-driven program?
8.
Conclusion