So I was asked to write a function int ncr(int n, int r)
, which basically computes n choose r and returns the value, but, my code also needs to account for error cases if the user enters negative numbers or invalid input like n lesser than r (or) if the user enters floating point numbers
#include <stdio.h>
int ncr(int n, int r)
{
if (n - r < r)
{
r = n - r;
}
if (r == 0)
{
return 1;
}
else return ncr(n-1,r) + ncr(n-1,r-1);
}
int main()
{
int n, r;
float n1, r1;
printf("Input :\n");
printf("n = ");
scanf("%f", &n1);
printf("r = ");
scanf("%f", &r1);
printf("Output : ");
n = n1;
r = r1;
if (n1 - n > 0 || r1 - r > 0)
{
printf("Invalid Input, n and r both should be integer numbers");
return 1;
}
if (n <= 0 || r < 0)
{
printf("Invalid input, n (or) r should be unsigned numbers");
}
else if (n < r)
{
printf("Invalid input, n should be greater than or equal to r");
}
else
{
printf("C(n, r) = %d", ncr(n,r));
}
return 0;
}
This piece of code works completely fine but, the thing I am concerned with is that there must surely be a better way to account for throwing an error message if the user enters floating point numbers. I handled this case by actually reading a float
using scanf("%f", &n1)
and scanf("%f", &r1)
and later checking whether these floats are just integers or not and accordingly thrown the error if these numbers also have digits after the decimal point.
Instead of using these float
duplicates like n1
and r1
, can we just not solve the issue by using only int n, r
directly?
I've tried doing this too where I read the input directly into n
and r
without using any float duplicates like n1
and r1
if (scanf("%d", &n) != 1)
{
printf("Output : Invalid Input, n and r both should be integer numbers");
return 1;
}
printf("r = ");
if (scanf("%d", &r) != 1)
{
printf("Output : Invalid Input, n and r both should be integer numbers");
return 1;
}
But the output is not satisfying
Input :
n = 6.7
r = Output : Invalid Input, n and r both should be integer numbers
It appears that contro-flow is not going into the first if(scanf("%d", &n) != 1)
statement but is going into the second one (I can tell this because r =
is being printed on-screen)
This all seems insignificant but it would be great if someone tells a better way to throw an error message if the user enters a float
instead of an int
without actually reading float
numbers like I did (i.e., using duplicates)