Function return a value

Problem: Write a C program to divide one integer number by another and show the result of division but full fill following condition:

  • Use a user defined function
  • User defined function will not receive any data
  • User defined function will not receive any data
  • User defined function will return the division of two integre number

Solution:
step1: Let function name be divide.
step2: function will not receive any data.It implies that argument is void.
step3: function will return the division as result. Here division may be integer or fraction. i.e: 10/2 = 5 which is integer but 10/3 =3.333333 which is fractional. So it is safe to use float as return type. Others fractional part will be truncated.
step4: write function body. it will look like this:

int a,b;
printf("Enter two integer value : ");
scanf("%d%d",&a,&b);
return (float)a/b;

Here a,b both are integer type. So a/b is also converted into integer and fractional part will be lost. i.e: 10/3 will be 3 instead of 3.333333. To avoid this we used data type casting here. In the mean time we have discussed data type casting.
return (float)a/b; lines says the compiler to return the value of a/b to where the function was called.

So your user defined function will look like this:

float divide(void)
{
   int a,b;
   printf("Enter two integer value : ");
   scanf("%d%d",&a,&b);
   return (float)a/b;
}

Now main() function can call this function as follows to execute devide() function as follows:

int main()
{
  divide();
  return 0;
}

But divide function will return the value of a/b. So it should be caught by another variable. So it should be called as follows:

int main()
{
  float div;
  div=divide();
  printf("Result  is : %f",div);
  return 0;
}

Entire solution is:

#include<stdio.h>
float divide(void)
{
   int a,b;
   printf("Enter two integer value : ");
   scanf("%d%d",&a,&b);
   return (float)a/b;
}
 int main()
 {
   float div;
   div=divide();
   printf("Result  is : %f",div);
   return 0;
 }

OUTPUT

Enter two integer value : 10 3
Result is : 3.333333


Next Previous