0% found this document useful (0 votes)
2 views2 pages

Menu Driven Program Example

This document contains a C program for a simple calculator that performs basic arithmetic operations: addition, subtraction, multiplication, and division. The program continuously prompts the user to select an operation and input two numbers, displaying the result until the user chooses to exit. It includes error handling for division by zero and invalid menu choices.

Uploaded by

Prasenjit Guha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Menu Driven Program Example

This document contains a C program for a simple calculator that performs basic arithmetic operations: addition, subtraction, multiplication, and division. The program continuously prompts the user to select an operation and input two numbers, displaying the result until the user chooses to exit. It includes error handling for division by zero and invalid menu choices.

Uploaded by

Prasenjit Guha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <stdio.

h>
#include<stdlib.h>
// Function declarations for operations
float add(float a, float b);
float subtract(float a, float b);
float multiply(float a, float b);
float divide(float a, float b);

int main() {
int choice;
float num1, num2;
while(1)
{
// Display the menu
printf("\nSimple Calculator\n\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Divide\n");
printf("0 for exit \n");
printf("\nEnter your choice: ");
scanf("%d", &choice);

// Get input numbers for calculation

// Perform the operation based on the user's choice


switch(choice) {
case 1:
printf("\nEnter two numbers: ");
scanf("%f %f", &num1, &num2);
printf("\nResult: %.2f\n", add(num1, num2));
break;
case 2:
printf("\nEnter two numbers: ");
scanf("%f %f", &num1, &num2);
printf("\nResult: %.2f\n", subtract(num1, num2));
break;
case 3:
printf("\nEnter two numbers: ");
scanf("%f %f", &num1, &num2);
printf("\nResult: %.2f\n", multiply(num1, num2));
break;
case 4:
printf("\nEnter two numbers: ");
scanf("%f %f", &num1, &num2);
if (num2 != 0) {
printf("\nResult: %.2f\n", divide(num1, num2));
} else {
printf("\nError! Division by zero.\n");
}
break;
case 0:
exit(1);
default:
printf("\nInvalid choice!\n");
}
}
return 0;
}

// Function definitions for operations

// Addition
float add(float a, float b) {
return a + b;
}

// Subtraction
float subtract(float a, float b) {
return a - b;
}

// Multiplication
float multiply(float a, float b) {
return a * b;
}

// Division
float divide(float a, float b) {
return a / b;
}

You might also like