Hello,
I've been working with C trying to get factorials which I've successfully accomplished but my code needs to output an error message when inputting negative numbers, unfortunately my code outputs an error when using 1 and 0.
This is what my code looks like (keep in mind I'm a beginner user so my code is simple).

#include <stdio.h>

int main()
{
	int x, number, fac;
   	fac = 1;
   	printf("Enter a number:\n");
   	scanf("%d",&number);
  	for(x = 1; x <= number; x++)
  		{
			if (number >= 0)
				fac = fac * x;
  		}
  		if (number >= 0 && fac != 1)
  			printf("%d! = %d\n", number, fac);
  		else
  			printf("Factorial not defined for negative numbers.\n");
 }

I just changed small thing in your code.Factorial values of 1 and 0 is 1.I have done it in the following program.You check it.

#include        <stdio.h>
#include        <stdlib.h>
int main()
{
int x, number, fac;
fac = 1;
printf("Enter a number:\n");
scanf("%d",&number);
if(number<0)
{
printf("Factorial not defined for negative numbers.\n");
exit(0);
}
for(x = 1; x <= number; x++)
{
if (number >= 0)
fac = fac * x;
else
        fac=1;
}
printf("%d! = %d\n", number, fac);
}

YES!
It works perfectly, thanks a bunch.

Be a part of the DaniWeb community

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