Saturday 7 July 2012

C program to perform addition, subtraction, multiplication and division

C program to perform basic arithmetic operations i.e. addition , subtraction, multiplication and division of two numbers. Numbers are assumed to be integers and will be entered by the user.

C programming code

#include <stdio.h>
 
int main()
{
   int first, second, add, subtract, multiply;
   float divide;
 
   printf("Enter two integers\n");
   scanf("%d%d", &first, &second);
 
   add      = first + second;
   subtract = first - second;
   multiply = first * second;
   divide   = first / (float)second;   //typecasting
 
   printf("Sum = %d\n",add);
   printf("Difference = %d\n",subtract);
   printf("Multiplication = %d\n",multiply);
   printf("Division = %.2f\n",divide);
 
   return 0;
}
In c language when we divide two integers we get integer result for example 5/2 evaluates to 2. As a general rule integer/integer = integer and float/integer = float or integer/float = float. So we convert denominator to float in our program, you may also write float in numerator. This explicit conversion is known as typecasting.
Arithmetic operations.
Output of program:
arithmetic operations program

1 comments:

Unknown said...

Multiplication, division and modulus operator have highest priority than addition and subtraction operator.

Post a Comment