Division of two numbers - C Program

C program to read two numbers and print division of numbers.

Solution:

#include<stdio.h>
int main()
{
      int num1,num2,div;
      printf("\tEnter Two Numbers\n");
      printf("---------------------------\n");
      printf("Enter First Number  : ");
      scanf("%d", &num1);
      printf("\nEnter Second Number : ");
      scanf("%d",&num2);
      div=num1/num2;
      printf("\nDivision of %d & %d is = %d",num1,num2,div);
      return 0;
}


Output:

division of two no

In the above output, result of 40/7 shows '5' but the actual result of 40/7 is 5.714285714. This is because, we declare div variable int type as it shows only integer value and discard the number after decimal the point. To achieve this, problem must define variable (which holds the result of division) float type and use concept of typecasting specially where the result comes in decimal points.

What is type-casting?

Type casting means converting an expression of given data type into data another type. To avoid data loss convert lower to higher data type. e.g. If 'float' is converted into 'int' then data present after decimal point is lost.

Syntax:

(datatype) variable or (datatype) expression

Example: c= (float)a/b; or c= a/(float)b;

#include<stdio.h>
int main()
{
      int num1,num2;
      float div;  
      printf("\tEnter Two Numbers\n");
      printf("---------------------------\n");
      printf("Enter First Number  : ");
      scanf("%d", &num1);
      printf("\nEnter Second Number : ");
      scanf("%d",&num2);
      /*div defined as a float & cast any one variable num1 or num2.*/
      div=num1/(float)num2; //num2 cast as float
      printf("\nDivision of %d & %d is = %f",num1,num2,div);
      return 0;
}


Output:

division using typecasting