Answer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fact_calc(char* output, int n) {
int i;
int factorial = 1;
sprintf(output, "%d! ", n);
for (i = n; i >= 1; i--) {
factorial *= i;
sprintf(output + strlen(output), "%d ", i);
}
sprintf(output + strlen(output), "%d", factorial);
}
int main() {
int user_num;
char output[50];
while (1) {
printf("Enter an integer between 0 and 9 (-1 to quit): ");
scanf("%d", &user_num);
if (user_num == -1) {
break;
} else if (user_num < 0 || user_num > 9) {
printf("Invalid input. Please try again.\\");
continue;
}
fact_calc(output, user_num);
printf("%s\\", output);
}
return 0;
}
Step-by-step explanation:
The fact_calc function takes a string output argument and an integer input argument n, and calculates n! while building a string to display the calculation. It uses the sprintf function to append the intermediate steps of the calculation to the output string.
The main function repeatedly prompts the user for input and calls the fact_calc function with the user's input. If the user enters an invalid value, an error message is displayed and the program re-prompts for input. The program exits when the user enters -1.