factorial logic question

So I wrote a code to calculate the factorial of an int value, but when I checked online the code I made was a bit different then most of the codes I found. I just want to know if the code I wrote is okay, or if there's something wrong with it, or something I should do better with it. I tested it with a few numbers and it seems to be working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// My code
#include <iostream>
#include <string>
int factorial(int num);

int main()
{ std::cout << factorial(6);
  return 0;
}
int factorial(int num){
for(int i=(num-1);i>0;i--)num*=i;
return num;
}



The online codes look more like this...
1
2
3
4
5
6
int factorial(int num){
    int fact = 1;
    for(int i = 2; i <= num; i++)
        fact *=i;
    return fact;
}   
Last edited on
the code works for me.
Homberto wrote:
the code works for me.
Uggh...did you even read the OP?


@OP Your way is fine. I think the thing is most people like to loop forward and not backward. There is one slight problem with your and the other code though, you did not check if it is 0 or greater. Also if it is 0 then it is 1. Oh and you forgot to check if the number won't give an overflow.
Topic archived. No new replies allowed.