I am writing a simple program to calculate the factorials in ANSI C. The program works fine up to 12 because past 13 the numbers become too large for INT. What I want to do is to print the first 12, then somehow BREAK and send an error for the 13th number. However, the problem is that when I reach the 13th number and send the error, the first 12 do not print. Is is possible to return the error and still get the first 12?
My code:
#include <math.h>
#include<stdio.h>
int getIntFactorial(int x){
printf("Processing factorial of (%d) \n", x);
if (x <=1){
printf("\n Reached base case, returning %d \n", x);
printf("Now returning total value \n");
return 1;
}else if (x < 13){
printf("\n Doing recursion by calling factorial (%d - 1) \n", x);
int counter = x * getIntFactorial(x - 1);
printf("Receiving results of factorial (%d) = %d * %d = %d \n", x, x, (x-1), counter);
return counter;
}else {
///number is greater than 13
printf("Sorry, we cannot do the factorial for %d, only goes up to 12 \n", x);
return;
}
}
main()
{
getIntFactorial(13);
}
Output for 13:
Processing factorial of (13)
Sorry, we cannot do the factorial for 13, only goes up to 12
Process returned 62 (0x3E) execution time : 0.009 s
Press any key to continue.
Output for 12:
Processing factorial of (12)
Doing recursion by calling factorial (12 - 1)
Processing factorial of (11)
Doing recursion by calling factorial (11 - 1)
Processing factorial of (10)
Doing recursion by calling factorial (10 - 1)
Processing factorial of (9)
Doing recursion by calling factorial (9 - 1)
Processing factorial of (8)
Doing recursion by calling factorial (8 - 1)
Processing factorial of (7)
Doing recursion by calling factorial (7 - 1)
Processing factorial of (6)
Doing recursion by calling factorial (6 - 1)
Processing factorial of (5)
Doing recursion by calling factorial (5 - 1)
Processing factorial of (4)
Doing recursion by calling factorial (4 - 1)
Processing factorial of (3)
Doing recursion by calling factorial (3 - 1)
Processing factorial of (2)
Doing recursion by calling factorial (2 - 1)
Processing factorial of (1)
Reached base case, returning 1
Now returning total value
Receiving results of factorial (2) = 2 * 1 = 2
Receiving results of factorial (3) = 3 * 2 = 6
Receiving results of factorial (4) = 4 * 3 = 24
Receiving results of factorial (5) = 5 * 4 = 120
Receiving results of factorial (6) = 6 * 5 = 720
Receiving results of factorial (7) = 7 * 6 = 5040
Receiving results of factorial (8) = 8 * 7 = 40320
Receiving results of factorial (9) = 9 * 8 = 362880
Receiving results of factorial (10) = 10 * 9 = 3628800
Receiving results of factorial (11) = 11 * 10 = 39916800
Receiving results of factorial (12) = 12 * 11 = 479001600
Process returned 479001600 (0x1C8CFC00) execution time : 0.015 s
Press any key to continue.
According to my understanding of the requirement, Changing return;
in the last else
block to return getIntFactorial(x-1)
would yield the result you want?