So in this post, we are going to see how we can do the mathematical operations such as Addition, Subtraction, Multiplication & Division in C Programming language.
It’s fairly simple to do mathematical operations in C language, here I will show you a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include<stdio.h> int main() { int add, sub, mul; float div; //addition add = 5 + 2; //subtraction sub = 5 - 2; //multiplication mul = 5 * 2; //division div = 5 / (float)2; printf("Add: %d, Sub: %d, Mul: %d, Div: %.2f", add,sub,mul,div); return 0; } |
Now, this is something the values are hardcoded, now let’s write this application totally dynamic so we can get the input values from the user and do the math operations.
Also, we will give multiple options to do select the operation such as “Select 1 for Addition”, “Select 2 for Subtraction” and more.
Let’s write the complete C Program to do the mathematical operation dynamically:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#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; } |
The output of the above program will be something like this:
1 2 3 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 . . . |
Just go through the program line by line to understand it.
Enjoy programming!