user1961282 user1961282 - 7 months ago 26
C Question

C language. Factorial code (shortest possible)

I wanted to code the shortest snippet possible for a factorial operation, using also the minimum number of variables (could not make it with less than 2) and the minimum of lines too. But, it is not working despite that the logic is, I think, good and correct, :/

Here it is: say factorial of 5.

#include<stdio.h>

main()
int x, i = 5;
{
while(i!=1)
{
i--;
x *= i;
}

printf("%d",x);
}


So, let's depict what that code would do:

inside the loop
i
turns 4,
then we have
x = 5 * 4
which makes it 20.

Next round
i
is 3, we have

x = 20 * 3


Next round
i
is 2

x = 60 * 2


next
i
is 1
x = 120 * 1
, so that is the factorial.

I know there are bright brains out there who can come up with obfuscated code to do all that in half a line, but I would be satisfied just to find out why is giving me errors.

UPDATE AFTER PEOPLE'S INPUT:

it always yields 0 now, even if I change i!=2

main()
{
int x, i = 5;
while(i!=1)
{
i--;
x *= i;
}

printf("%d",x);


}


THE FINAL SOLUTION AND EXPLANATION:

I code in PHP and Java and today I wanted to do a quicky in C, so when I wrote this:

int x, i = 5;

I took for granted that it would initialize both to 5, as it does in PHP and JAVA, but it does not!

So, if I do

#include<stdio.h>

main()
int x = 5;
int i = 5;
{
while(i!=1)
{
i--;
x *= i;
}

printf("%d",x);
return (0);
}


my code works.

Thank you to all those who pointed the fundamental syntax errors.

Syntax errors happen when one is not familiar with the language rules, but the most important is the logic of the code and that was correct.

Answer Source

You forgot the { and also you need to initialize x before using as it causing undefined behavior.

#include<stdio.h>

int main()
{
    int x = 1, i = 5;
    while(i!=1)
    {
       x *= i;
       i--;
    }
    printf("%d",x);
    return 0;
}