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
(2 * (4 - (2+1)/2) + 3 - 2)evaluates to7, which could be demonstrated more simply byint 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 to6. Maybe pick out individual sub-expressions to further narrow the misunderstanding.)