We can divide two numbers in C language using the division operator '/'. Consider the expressionz = x / y;
Here x, y and z are three variables. Variable x is divided by variable y and the result is assigned to variable z.
Integer division in C
When we divide two integers the result may or may not be an integer. Let's look at some examples
4/2 = 2 (An integer)
3/2 = 1.5 (Not an integer)
In C language, when we divide two integers, we get an integer result, e.g., 5/2 evaluates to 2.
Let's write a program to understand division in C. While dividing to avoid getting the result converted to an integer we convert denominator to float in our program, you may also write float in the numerator. This explicit conversion is known as typecasting.
C program for arithmetic operations
C program to perform basic arithmetic operations of addition, subtraction, multiplication, and division of two numbers/integers that a user inputs.
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, you can also write: divide = (float)first/second
printf("Sum = %d\n", add);
printf("Difference = %d\n", subtract);
printf("Multiplication = %d\n", multiply);
printf("Division = %.2f\n", divide); // "%.2lf" to print two decimal digits, by default (%lf) we get six
return 0;
}
Output of program:
As a general rule integer/integer = integer, float/integer = float and integer/float = float.
Download Arithmetic operations program.
If we calculate 13/5 in a C program, the result is 2, so you might be thinking how can I get the remainder. To get it, use the modulus operator (%), yes it's a percentage sign.
The value of n is 3 (The remainder we obtain when 13 is divided by 5).