Skip to content

Commit 8fbd60d

Browse files
authored
Enhance comments and variable initialization in factorial.c
Added comments for clarity and improved code readability.
1 parent e5dad3f commit 8fbd60d

1 file changed

Lines changed: 16 additions & 10 deletions

File tree

math/factorial.c

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,36 @@
1-
#include <stdio.h>
1+
/*
2+
Program to compute factorial of large numbers using array storage.
3+
Handles values beyond standard integer limits.
4+
*/
5+
#include <stdio.h> //for basic functions like printf,scanf etc
26
int main()
37
{
4-
int a[200], n, counter, temp, i;
5-
a[0] = 1;
6-
counter = 0;
8+
int a[200], n, counter, temp, i; //initialize variables and arrays
9+
a[0] = 1; //first element of the array to be 1
10+
counter = 0; //to track number of digits in result
711
printf("Enter a whole number to Find its Factorial: ");
8-
scanf("%d", &n);
9-
if (n < 0)
12+
scanf("%d", &n); //take input number and store to variable n
13+
if (n < 0) //factorial not defined for negatives
1014
printf("Cannot Calculate factorials for negative numbers.");
1115
else
1216
{
1317
for (; n >= 2; n--)
1418
{
15-
temp = 0;
19+
temp = 0; //for carry during multiplication
1620
for (i = 0; i <= counter; i++)
1721
{
18-
temp = (a[i] * n) + temp;
19-
a[i] = temp % 10;
20-
temp = temp / 10;
22+
temp = (a[i] * n) + temp; //multiply digit and add previous carry
23+
a[i] = temp % 10; //store last digit of result
24+
temp = temp / 10; //update carry
2125
}
26+
//store remaining carry digits in array
2227
while (temp > 0)
2328
{
2429
a[++counter] = temp % 10;
2530
temp = temp / 10;
2631
}
2732
}
33+
//print factorial in msd order
2834
for (i = counter; i >= 0; i--) printf("%d", a[i]);
2935
}
3036
return 0;

0 commit comments

Comments
 (0)