Here's a program that performs basic arithmetic operations like addition, subtraction, multiplication and division using C programming language.
#include<stdio.h> //header file #include<conio.h> //header file void main() { int a, b; clrscr(); printf("Enter the first number"); scanf("%d",&a); printf("Enter the second number"); scanf("%d",&b); printf("First Num is %d\nSecond num is %d, a, b); printf("Sum of %d and %d is %d", a, b, a + b); printf("Difference of %d and %d is %d", a, b, a - b); printf("Multiplication of %d and %d is %d", a, b, a * b); if(b == 0 && a != 0){ printf("Division of %d and %d is %.2f", b, a, (float)b/a); }else if(a == 0 && b == 0){ printf("Division of %d and %d can't be performed", b, a); }else{ printf("Division of %d and %d is %.2f", a, b, (float)a/b); } getch(); }
Explanation of above program
The above code is very simple. The program simply performs four basic arithmetic operations and returns the results back to the user. Lets understand the program from the beginning.
First the header files are included. Then inside the main function, we declare two variables to hold the values of two numbers. Then the user is prompt to enter the numbers. Once the numbers are entered, arithmetic operations are now performed.
First we add the numbers and print the result back. Notice inside the printf() first %d will display value of a, second %d will display the value of b and last %d will display the value of a + b. Similarly, in next two steps difference and multiplication of two numbers is printed.
Now for the division part you have to be extra careful because if the denominator is zero the program will throw division by zero exception and will run forever causing your program to crash. So it's better to check the numbers before actually dividing them. Here we simply check in the if statement that if value of a is non zero and b is zero then we divide b by a i.e. b/a. In the else if part we check if both a and b are zero then we don't divide the numbers but show a message to user that division can't be performed with such inputs and in the else part i.e. a may have any value and b should have only non-zero values, we are dividing a by b i.e. a/b.
You may have noticed that we've used %.2f to display the division. This prints a float value with two digits after decimal i.e. 10.00, 15.29 etc.