C Programming

Solved Example

Practice Questions

Exercise Question

Menu driven program to perform addition, subtraction, multiplication, division, power and square root.

Objective

Write a program to input any choice to perform basic math operations. The list of operations along with the input given below...

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Division (%)
  • Power (^)
  • Square Root (s)

Program

#include "stdio.h"
#include "math.h"

int main() {
	char ch;
	int a,b;
	printf("Enter your choice,say(+,-,*,/,%%,^,s): ");
	scanf("%c",&ch);
	
	fflush(stdin);
	
	switch(ch) {
		case '+':
			printf("Enter any two numbers: ");
			scanf("%d%d",&a,&b);
			printf("%d + %d = %d\n",a, b, a + b);
			break;
		case '-':
			printf("Enter any two numbers: ");
			scanf("%d%d",&a,&b);
			printf("%d - %d = %d\n",a, b, a - b);
			break;
		case '*':
			printf("Enter any two numbers: ");
			scanf("%d%d",&a,&b);
			printf("a * b = %d\n",a, b, a * b);
			break;
		case '/':
			printf("Enter any two numbers: ");
			scanf("%d%d",&a,&b);
			printf("%d / %d = %.2f\n",a, b, (float)a / b);
			break;
		case '%':
			printf("Enter any two numbers: ");
			scanf("%d%d",&a,&b);
			printf("%d %% %d = %d\n",a, b, a % b);
			break;
		case '^':
			printf("Enter any two numbers: ");
			scanf("%d%d",&a,&b);
			printf("%d ^ %d = %.2f\n",a, b, pow(a,b));
			break;
		case 's':
		case 'S':
			printf("Enter any number: ");
			scanf("%d",&a);
			printf("Square root of %d = %.2f",a, sqrt(a));
			break;
		default:
			printf("Invalid input");
	}
	return 0;
}

Output

Enter your choice,say(+,-,*,/,%,^,s): +
Enter any two numbers: 3 7
3 + 7 = 10

Enter your choice,say(+,-,*,/,%,^,s): *
Enter any two numbers: 2 24
2 * 24 = 48

Enter your choice,say(+,-,*,/,%,^,s): /
Enter any two numbers: 25 2
25 / 2 = 12.50

Enter your choice,say(+,-,*,/,%,^,s): ^
Enter any two numbers: 3 4
3 ^ 4 = 81.00

Enter your choice,say(+,-,*,/,%,^,s): s
Enter any number: 2
Square root of 2 = 1.41

Explanation

To print the % sign use %% in the printf statement.

For the square root, lowercase 's' or uppercase 'S' both are allowed that can be done with multiple cases.