Edmond Sn
Edmond Sn

Reputation: 3

Nested loop for triangular matrix in C++

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

Upvotes: 0

Views: 123

Answers (1)

selbie
selbie

Reputation: 104589

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.

Upvotes: 1

Related Questions