C Program to Perform Addition, Subtraction, Multiplication and Division

Question: C Program to Perform AdditionSubtractionMultiplication and Division

Solution: Here is code of to Perform AdditionSubtractionMultiplication and Division in C

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int a, b, add, sub, mul, opt, ans;
	float div;
	printf(" 1. Addition\n 2. Subtraction\n 3. Multiplication\n 4. Division\n");
	printf("Select any one option (1 to 4): ");
	scanf("%d", &opt);
 
	//check if the option is entered between 1 and 4
	if(opt <= 0 || opt > 4)
	{
		printf("Please enter values between 1 and 4!");
		exit(0);
	}
	
	//get the values of a and b
	printf("Enter value of a:");
	scanf("%d", &a);
	
	printf("Enter value of b:");
	scanf("%d", &b);
		
	//check the option selected, depends on the selection
	//do the math operation 
	if(opt == 1)
	{
		printf("\nYou have selected 'Addition'\n");
		ans = a + b;
	}
	else if(opt == 2)
	{ 
		printf("\nYou have selected 'Subtraction'\n");
		ans = a - b;		
	}
	else if(opt == 3)
	{  
		printf("\nYou have selected 'Multiplication'\n");
		ans = a * b;
	}
	else if(opt == 4)
	{
		printf("\nYou have selected 'Division'\n");
		div = a / (float)b;
	}
	
	//print the output
	if(opt != 4){
		printf("Answer: %d", ans);
	}else{
		printf("Answer: %.2f", div);
	}
	return 0;	
}

Output:


4
5
6
7
8
9
10
11
12
13
 1. Addition
 2. Subtraction
 3. Multiplication
 4. Division
Select any one option (1 to 4): 3
Enter value of a:6
Enter value of b:4
 
You have selected 'Multiplication'
Answer: 24
--------------------------------
Process exited after 4.695 seconds with return value 0
Press any key to continue . . .

You May Also Like

About the Author: Ajab Noor

Leave a Reply

Your email address will not be published. Required fields are marked *