Press "Enter" to skip to content

C Program for Add, Subtract, Multiply and Divide Two Given Numbers

This is a basic C program to accept two integer numbers and perform Addition, subtraction, multiplication and division operations and display their result.
Here we accept two numbers using scanf function and we store the result on a separate variable.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
int n1, n2, result;
printf("Enter two numbers: ");
scanf("%d%d",&n1,&n2);
result = n1 + n2;
printf("\nSum of %d and %d is %d",n1,n2,result);
result = n1 - n2;
printf("\nDifference of %d and %d is %d",n1,n2, result);
result = n1 * n2;
printf("\nProduct of %d and %d is %d",n1,n2, result);
result = n1 / n2;
printf("\nQuotient of %d and %d is %d",n1,n2, result);
getch();
}

Code Explanation:
Here we accept two integers into n1 and n2 respectively. Each time of operation, result variable stores the result of the corresponding operation and print the appropriate result.
We can code same program without any extra code rather than two variables. That is we don’t need the variable ‘result’.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
int n1, n2, result;
printf("Enter two numbers: ");
scanf("%d%d",&n1,&n2);
printf("\nSum of %d and %d is %d",n1,n2, n1 + n2);
printf("\nDifference of %d and %d is %d",n1,n2,n1 - n2);
printf("\nProduct of %d and %d is %d",n1,n2,n1 * n2);
printf("\nQuotient of %d and %d is %d",n1,n2, n1 / n2);
getch();
}

Here we directly display the result on the print section. So we can avoid an extra variable (result) as we as extra line of code which decrease the time and space complexity of the program.

Sample output with sample input:

C Program to Addition, subtraction, multiplication, division

Be First to Comment

Leave a Reply