here is the question: Write a program that accepts a positive integer. Use a function to calculate the factorial of
that number.
my codes:

``````#include <stdio.h>
#include <stdlib.h>
int fun(int z);
int main()
{
int n,x,fact;

printf("enter  a number: ");
scanf("%d",&n);
fact=fun(n);
printf("factorial of %d is %ld\n" ,n,fact);

system("pause");
return(0);
}
int fun(int z)
{
int n,c,  fact=1;
for(c=1;c<=n;c++)

return fact*c;
}
``````

i am still having the difficulty when i enter 2 i should have get 2 but instead i get a 1. what is wrong?

## All 5 Replies

Line 19. What is the value of `n`?

Also, your function `fun` just plain doesn't work. That loop doesn't loop. The first time you get to line 21, the function finishes.

``````#include <stdio.h>
#include <stdlib.h>
int fun(int z);
int main()
{
int n,x,fact;

printf("enter  a number: ");
scanf("%d",&n);
fact=fun(n);
printf("factorial of %d is %ld\n" ,n,fact);

system("pause");
return(0);
}
int fun(int z)
{
int n,c,  fact=1;
for(c=1;c<=z;c++)
{
fact=fact*c;
}
return (fact);
}
``````

now it works ;)

Great. What's that `n` for in line 18?

What's that n for in line 18?

yes,
its good practice that if there is no use of any variable remove these.(i think they consume memory).

so , if `n` is not useful then don't declare it.

so , if n is not useful then don't declare it.

This is why I believe `-Wall` (and other compilers' equivalents) shouldn't be optional.

commented: Indeed! +14
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.