1

I think, my code below is correct. I want to access 5, then 9, 10, 13, 14 and 15, but I really do not know why it is missing the 5 completely and index of M is starting from 2.

#include <iostream>
#include <vector>
    
int main() {
  std::vector<std::vector<int>> matrix_val = {
    {1,2,3,4,50},
    {5,6,7,8,90},
    {9,10,11,12,130},
    {13,14,15,16,300}
  };
    
  for (int M = 1; M < 4; M++) {  
    for (int k = 0; k < M - 1; k++) {  
      std::cout << " Matix_val is " << matrix_val[M][k] 
                << " Value of M " << M 
                << " Value of k " << k 
                << std::endl;
    }    
  }
Gemmy
  • 9
  • 5
Manu
  • 69
  • 8
  • On the first run of the *outer* loop, `M` is `1`; so, for how many *inner* loops will `k` be **less than** `M - 1` when `k` starts off at zero? – Adrian Mole Mar 22 '23 at 04:46
  • 1
    Start using a debugger. [What is a debugger and how can it help me diagnose problems?](/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jason Mar 22 '23 at 05:31
  • Side note: if you think your code is correct and it doesn't do what you want, your thinking is almost certainly incorrect. – user4581301 Mar 22 '23 at 06:03

3 Answers3

1

Your inner loop

for (int k = 0; k < M - 1; k++) 

doesn't run if M = 1, because the condition k < M - 1 is not true for k = 0. You need

for (int M = 0; M < 4; M++) {
    for (int k = 0; k < M; k++) {

which produces this output:

 Matix_val is 5 Value of M 1 Value of k 0
 Matix_val is 9 Value of M 2 Value of k 0
 Matix_val is 10 Value of M 2 Value of k 1
 Matix_val is 13 Value of M 3 Value of k 0
 Matix_val is 14 Value of M 3 Value of k 1
 Matix_val is 15 Value of M 3 Value of k 2
Mikael Jagan
  • 9,012
  • 2
  • 17
  • 48
pm100
  • 48,078
  • 23
  • 82
  • 145
1

Your inner loop is off by one. Just change:

for(int k=0; k < M-1; k++) {
    ...
}

to:

for(int k=0; k < M; k++) {
    ...
}
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

The proper way of indexing container without causing problems is to get the extent of the loop from the container it self:

for(int M = 0; M < size(matrix_val); ++M)
    for(int K = 0; K < size(matrix_val[M]); ++K)
        std::cout << matrix_val[M][K] << "\n";

But this old-school for loops can easily become source of bugs through bad indexing, wrong condition... The better approach is modern range-based for loops:

std::size_t i=0;
for(auto& row : matrix_val){
    std::size_t j=0;
    for(auto& element : row)
       std::cout<<std::format ("[{}][{}]={}\n", i, j++, element);
    ++i;
};
Red.Wave
  • 2,790
  • 11
  • 17