Arithmetic operations on two integer numbers
C program to perform all arithmetic operations on two integer numbers.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2;
int add, sub, mul, mod, div_integer;
float div_float;
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
add = num1 + num2;
sub = num1 - num2;
mul = num1 * num2;
div_integer = num1 / num2;
div_float = (float)num1 / num2;
mod = num1 % num2;
printf("Addition = %d\n", add);
printf("Subtraction = %d\n", sub);
printf("Multiplication = %d\n", mul);
printf("Integer Quotient = %d\n", div_integer);
printf("Floating Quotient = %f\n", div_float);
printf("Modulus = %d", mod);
getch();
}
Output
Enter any two numbers: 8
3
Addition = 11
Subtraction = 5
Multiplication = 24
Integer Quotient = 2
Floating Quotient = 2.666667
Modulus = 2
Explanation
The above program performs basic arithmetic operations which are addition, subtraction, multiplication, division, and modulus of two numbers. Numbers are assumed to be positive integers and are entered by a user. The numbers entered are read using scanf() statement.
In C language, when we divide two integers, we get an integer quotient as a result, for example, 5/2 evaluates to 2. As a general rule,
integer/integer = integer
float/integer = float and
integer/float = float.
So, in statement
'%' operator known as modulo operator is used to perform the modulus operation on two positive integers and returns the remainder after division of one number by another. For example, 5 % 2 = 1 and 8 % 2 = 0.
In C language, when we divide two integers, we get an integer quotient as a result, for example, 5/2 evaluates to 2. As a general rule,
integer/integer = integer
float/integer = float and
integer/float = float.
So, in statement
div_float = (float)num1 / num2;
, num1 is typecasted to float before the divide operation, to avoid integer division.
'%' operator known as modulo operator is used to perform the modulus operation on two positive integers and returns the remainder after division of one number by another. For example, 5 % 2 = 1 and 8 % 2 = 0.