Menu Driven Program
Menu Driven Program in C++ (3 Ways With Output)
BeginnerTopic: Application Programs
C++ Menu Driven Program Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
void displayMenu() {
cout << "\n=== MENU ===" << endl;
cout << "1. Add" << endl;
cout << "2. Subtract" << endl;
cout << "3. Multiply" << endl;
cout << "4. Divide" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
}
int main() {
int choice;
double num1, num2, result;
do {
displayMenu();
cin >> choice;
if (choice >= 1 && choice <= 4) {
cout << "Enter two numbers: ";
cin >> num1 >> num2;
}
switch(choice) {
case 1:
result = num1 + num2;
cout << "Result: " << result << endl;
break;
case 2:
result = num1 - num2;
cout << "Result: " << result << endl;
break;
case 3:
result = num1 * num2;
cout << "Result: " << result << endl;
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
cout << "Result: " << result << endl;
} else {
cout << "Error: Division by zero!" << endl;
}
break;
case 5:
cout << "Exiting..." << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
} while(choice != 5);
return 0;
}Output
=== MENU === 1. Add 2. Subtract 3. Multiply 4. Divide 5. Exit Enter your choice: 1 Enter two numbers: 10 20 Result: 30 === MENU === 1. Add 2. Subtract 3. Multiply 4. Divide 5. Exit Enter your choice: 5 Exiting...
Understanding Menu Driven Program
This program demonstrates 3 different ways to create menu-driven programs: using switch-case with do-while loop, using functions for each menu option, and using classes with methods. Menu-driven programs provide user-friendly interfaces.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.