#include <stdio.h>
int fact (int num)
{
int f;
if(num == 0 || num == 1)
f = 1;
else
f = num * fact(num-1);
printf("Factorial %i \n", f);
return f;
}
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%i", &n);
fact(n);
printf("Factorial of %i is %i\n", n, fact(n));
return 0;
}
#include <stdio.h>
int fact (int num)
{
int f;
if(num == 0 || num == 1)
f = 1;
else
f = num * fact(num-1);
return f;
}
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%i", &n);
fact(n);
printf("Factorial of %i is %i\n", n, fact(n));
return 0;
}
Enter a positive integer: 5
Factorial of 5 is 120
Why don't you try to delete the redundant output you don't need?
Yea makes sense really but initially i figured that i need to display all of it.
Write a program fact.c that asks the user to enter an integer number N.
The program then prints out the first N factorial numbers.
Remember that fac(1)=1, fac(n)=n*fac(n-1).
You should use a function fac that is written recursively.
#include <stdio.h>
int fact (int num)
{
int f;
if(num == 0 || num == 1)
f = 1;
else
f = num * fact(num-1);
return f;
}
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%i", &n);
for(int i = 1; i <= n; i++)
printf("Factorial of %i is %i\n", i, fact(i));
return 0;
}
The program then prints out the first N factorial numbers.
Enter a positive integer: 10
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Factorial of 6 is 720
Factorial of 7 is 5040
Factorial of 8 is 40320
Factorial of 9 is 362880
Factorial of 10 is 3628800
ea makes sense really but initially i figured that i need to display all of it.
If the goal is to calculate a single factorial, then print outside of the function. If the goal is to display all of the factorials as they are recursively calculated, print inside the function. You may find you need to change the signature of the function if the latter is the case.
Yap was just attempting something like that however if i do for it comes up with
fact.c:20:2: error: ‘for’ loop initial declarations are only allowed in C99 mode
so not sure if i'm allowed additional flags while compiling. Not exactly a problem that it double prints but not exactly neat. However appreciate the help provided
#include <stdio.h>
int fact (int num)
{
int f;
if(num == 0 || num == 1)
f = 1;
else
f = num * fact(num-1);
return f;
}
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%i", &n);
int i; // <==
for(i = 1; i <= n; i++)
printf("Factorial of %i is %i\n", i, fact(i));
return 0;
}
(?) You are using a very old compiler maybe? What is the compiler you are using?