0

Please can someone explain why I am getting 7 at the last iteration of the loops instead of 6? It this a problem of my loops structure or the compilator needs an additional information?

#include <iostream>
using namespace std;

int main() {
int p = 4;
int i, j, k;
      for(i=0; i<(p-1); i++){
         for(j=(i+1); j<p; j++){

               cout << "i = " << i << " j = " << j << endl;
               k = i * (p - (i+1)/2) + j - i;
               cout << " k = " << k << endl;

         }
      }
  return 0;
}

Output

i = 0 j = 1
k = 1
i = 0 j = 2
k = 2
i = 0 j = 3
k = 3
i = 1 j = 2
k = 4
i = 1 j = 3
k = 5
i = 2 j = 3
k = 7
1
  • You did a good job showing the values of your variables, which could allow greater simplification of your code. Basically, you are asking why the expression (2 * (4 - (2+1)/2) + 3 - 2) evaluates to 7, which could be demonstrated more simply by int main() { std::cout << (2 * (4 - (2+1)/2) + 3 - 2) << std::endl; }. No need to complicate things by having loops. (A good addition, though, would be an explanation of why you think this expression should evaluate to 6. Maybe pick out individual sub-expressions to further narrow the misunderstanding.) Commented Jan 31, 2021 at 4:54

1 Answer 1

1

Basic algebra with integer division using: i = 2 j = 3

Let's compute your line of code:

k = i * (p - (i+1)/2) + j - i

Breaking it down:

k = i * (p - (i+1)/2) + j - i

k = 2 * (4 - (2+1)/2) + 3 - 2

k = 2 * (4 - 3/2) + 3 - 2

k = 2 * (4 - 1) + 3 - 2

k = 2 * 3 + 1

k = 6 + 1

k = 7

For what's it's worth, each +1 increment on j results in a +1 increment on k. But that same can't be said for i, which is a multiplication factor in that equation. That last iteration of your code sees i increment from 1 to 2.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.