write a c function called fact_calculation that takes a string output argument a
ID: 3778769 • Letter: W
Question
write a c function called fact_calculation that takes a string output argument and an integer input argument n and returns a string showing the calculation of n!. For example, if the value supplied for n were 6, the string returned would be 6! 5 6 3 5 3 4 3 3 3 2 3 1 5 720 Write a program that repeatedly prompts the user for an integer between 0 and 9, calls fact_calculation and outputs the resulting string . If the user inputs an invalid value , the program should display an error message and re-prompt for valid input. Input of the sentinel -1 should cause the input loop to exit.
Explanation / Answer
#include<stdio.h>
#include<string.h>
void fact_calculation(int n, char str[]);
int main()
{
//n is number to take as input
int n;
//declare char array to hold return string from function call fact_calculation
char str[100];
//for looping indext, declare i
int i ;
while(1)
{
printf("Entrer an integer between 0 and 9: ");
scanf("%d",&n);
if( n > 9 )
{
printf("Please enter value of n between 0 and 9 ");
continue;
}
if( n < 0 )
{
printf("Quit.. ");
break;
}
fact_calculation(n,str);
printf("Factorial of number %d is %s ",n,str);
}
}
void fact_calculation(int n, char str[])
{
int tmp = n;
int i = 0 ,fact=1,j;
char buf[20];
//calculate factorial of number
while(tmp)
{
if( tmp == 0 )
{
fact*=1;
break;
}
fact*=tmp;
--tmp;
}
//convert n to character and append ! after n and numbers till we get 1 and append factorial of number at the end of string
str[0]=n+48;
str[1] = '!';
str[2] = '=';
i = 3;
while(n)
{
str[i++] = n+48;
if( n == 1)
str[i++] = '=';
else
str[i++] = 'x';
--n;
}
//convert factorial number to string and then append this string at the end of str , which has to be returned from this function
sprintf(buf,"%d",fact);
//append factorial
for( j = 0 ; j < strlen(buf) ; j ++)
{
str[i++] = buf[j];
}
str[i] = '';
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.