Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is the cleaner way to do this simple while?

Tags:

c++

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.

like image 704
user363834 Avatar asked Nov 26 '22 20:11

user363834


2 Answers

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;
}
like image 116
LukeN Avatar answered Nov 29 '22 11:11

LukeN


int factorial(int n) {
   int product = 1;
   for (int i = 1; i <= n; i++) {
      product *= i;
   }
   return product;
}

is way more readable (and generalized).

like image 33
msw Avatar answered Nov 29 '22 10:11

msw