-1

So I was wondering what the equivalent expression for this for loop would be I honestly have never seen for loop written this way due to lack of experience I guess.

Here is the code:

    string convertToBase7(int num) {
     int res = 0;
    for(int i=0; num!=0; res += pow(10,i++)*(num % 7), num /= 7) {}
    return to_string(res);
}

so does the statments after the semi-colon get executed at each iteration in the order it is written? Also at say at i = 2 then, res += pow(10,3)? Is that correct?

Jason Kim
  • 1
  • 1
  • 5

1 Answers1

1

So if you have:

for (int i = 0, j = 0; i < 5 && j < 3; ++i, ++j)

is similar to:

int i = 0, j = 0;
while (i < 5 && j < 3) {
    ++i;
    ++j;
}

so does the statments after the semi-colon get executed at each iteration in the order it is written?

As you can see from above code yes.

Also at say at i = 2 then, res += pow(10,3)? Is that correct?

Not necessarily because it is not guarantied that i would be incremented before it was passed to a function. Check this out: Order of operations for pre-increment and post-increment in a function argument?

You have also this problem

num != 0;

what would happen if division:

num /= 7;

skips zero, by accident, thus I recommend you do following:

num > 0;

So with all of the above, I would write this line:

for(int i=0; num!=0; res += pow(10,i++)*(num % 7), num /= 7) {}

as follows:

 for(int i=0; num!=0; ++i, res += pow(10,i)*(num % 7), num /= 7) {}

if I need to make sure i is incremented before it is passed to a function, or.:

for(int i=0; num!=0; res += pow(10,i)*(num % 7), ++i, num /= 7) {}

If I need to make sure i is incremented after it is passed to a funciton.