Write a program to calculate the values for and
Input-Output:
Enter the input in nPr/npr and nCr/ncr format :
3p3
Value of 3p3=6
-------------------
Enter the input in nPr/npr and nCr/ncr format :
5c2
Value of 5c2=10
--------------------
Enter the input in nPr/npr and nCr/ncr format :
10P2
Value of 55c2=1485
--------------
Enter the input in nPr/npr and nCr/ncr format :
-5c2
Sorry both n and r must be positive>0
Include all possible error handling
C Code:
#include<stdio.h>
#include<math.h>
int factp(int,int);
int factc(int,int);
int fact(int);
void main ()
{
char inp[10],type;
int n=0,r=0,nf[10],rf[10],i,j,size,midindex,flag;
printf("Enter in npr/ncr format:\t");
scanf("%s",&inp);
for(i=0;i<10;i++){
if(inp[i]=='\0'){
size=i;
break;
}
}
//Fining '-' sign //Error handeling
for(i=0;i<size;i++){
if(inp[i]=='-'){
printf("\nInvalid Input n/r cannot be negative");
exit(0);
}
}
//Finding the middle p/c
flag=0;
for(i=0;i<size;i++){
if(inp[i]=='p'||inp[i]=='P'||inp[i]=='c'||inp[i]=='C'){
midindex=i;
type=inp[i];
flag=1;
}
}
//Error handeling
if(midindex==0)
{
printf("Invalid Input: n is missing");
}
if(flag==0){
printf("\nInvalid Input: p/c missing");
exit(0);
}
//Generating n value
for(i=0;i<midindex;i++)
{
nf[i]=inp[i]-'0';
n=n+nf[i]*pow(10,midindex-i-1);
}
//Generating r value
for(i=midindex+1;i<size;i++)
{
rf[i]=inp[i]-'0';
r=r+rf[i]*pow(10,size-i-1);
}
//Error handeling
if(r==0){
printf("Invalid Input: r is missing or r=0");
exit(0);
}
if(n==0){
printf("Invalid Input: n=0");
exit(0);
}
if(n<r){
printf("Invalid Input: n cannot be less than r");
exit(0);
}
//calculating final result
if(type=='p'||inp[i]=='P'){
printf("\nResult=%d", factp(n,r));
}
else if(type=='c'||inp[i]=='C'){
printf("\nResult=%d", factc(n,r));
}
else
printf("Unknown Error");
}
int factp(int n,int r){
return (fact(n)/fact(n-r));
}
int factc(int n,int r){
return (fact(n)/(fact(n-r)*fact(r)));
}
int fact(int f){
int fact=1;
while(f>0){
fact=fact*f;
f--;
}
return (fact);
}
Input Output:
Comments
Post a Comment