S
strictly_mk
Hi all, forgive me if there is a simple solution for this. I am going
through the following piece of code which simply calculates factorials
out of a book, but when i run it I get the answer 0 for whatever number
I input. Can anyone help?
Thanks in advance
strictly_mk
#include "stdio.h"
unsigned long long int return_factorial(unsigned int num); //function
prototype
int main (void) {
char input[3]; //keyboard input
int number; // number to work with
//prompt user
printf("Enter a positive integer for which the factorial will be
calculated: ");
fgets (input, sizeof(input), stdin); // read the input
sscanf (input, "%d", &number);
//check the input as conditional
if (number > 0) {
printf ("The factorial of %d is %lu.\n", number,
return_factorial(number));
} else {
printf ("You must enter a positive integer!\n");
}
getchar(); //pause and wait for user
return 0;
}
//This function takes a number and returns its factorial
unsigned long long int return_factorial(unsigned int num) {
unsigned long long int sum = 1;
unsigned int i; //multiplier to be used in calculating factorial
//Loop through every multiplier up to and including sum
for (sum = 1, i = 1; i <= num; ++i) {
sum *= i;
}
return sum;
} // End of return_factorial function
through the following piece of code which simply calculates factorials
out of a book, but when i run it I get the answer 0 for whatever number
I input. Can anyone help?
Thanks in advance
strictly_mk
#include "stdio.h"
unsigned long long int return_factorial(unsigned int num); //function
prototype
int main (void) {
char input[3]; //keyboard input
int number; // number to work with
//prompt user
printf("Enter a positive integer for which the factorial will be
calculated: ");
fgets (input, sizeof(input), stdin); // read the input
sscanf (input, "%d", &number);
//check the input as conditional
if (number > 0) {
printf ("The factorial of %d is %lu.\n", number,
return_factorial(number));
} else {
printf ("You must enter a positive integer!\n");
}
getchar(); //pause and wait for user
return 0;
}
//This function takes a number and returns its factorial
unsigned long long int return_factorial(unsigned int num) {
unsigned long long int sum = 1;
unsigned int i; //multiplier to be used in calculating factorial
//Loop through every multiplier up to and including sum
for (sum = 1, i = 1; i <= num; ++i) {
sum *= i;
}
return sum;
} // End of return_factorial function