I'm learning C++ and I want to make clean and readable code. I was wondering which way is better? (this is supposed to make the factorial of 9)
First Method:
int main(){
    int i = 1,r = i;
    while (i < 10) {
       r *= ++i;
    }
}
Second Method:
int main(){
    int i = 1,r = i;
    while (i < 10) {
       i++;
       r *= i
    }
}
The first may be harder to understand but it's one less line. Is it worth it? What about performance? Obviously it wouldn't matter in such a trivial example but it would be a good practice to make fast code from the beginning.
That while can't get much simpler, but you can always switch to a for!
int r = 1;
for (int i = 1; i <= 10; i++) {
   r *= i;
}
int factorial(int n) {
   int product = 1;
   for (int i = 1; i <= n; i++) {
      product *= i;
   }
   return product;
}
is way more readable (and generalized).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With