-1

I have a little problem, I don't quite understand how to make a toothed (a notched?) matrix in C++. The matrix should be like this (with 4 columns and 6 rows):

enter image description here

But I keep getting a matrix in the form of a triangle, i.e. no repeating rows are displayed. How can I fix it? I'm attaching a piece of code, but I don't think it will help much.

(N are rows, M are columns)

for (int i = 0; i < N; i++) { 
   matrix[i] = new double[M]; 
   for (int p = 0; p <= i; p++) { 
      matrix[i][p] = rand() % 101 - 50; 
   cout << setw(5) << matrix[i][p]; 
}
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • You'll be glad to hear you don't need anyone's help to figure this out, just a tool you already have: your debugger! This is exactly what a debugger is for. It [runs your program, one line at a time, and shows you what's happening](https://stackoverflow.com/questions/25385173/), this is something that's every C++ developer must know how to do. With your debugger's help you'll able to quickly find all problems in this and all future programs you write, without having to ask anyone for help. Have you tried using your debugger, already? If not, why not? What did your debugger show you? – Sam Varshavchik Dec 16 '21 at 13:30

1 Answers1

0

I'm assuming that the first row has 1 column, second has 2 columns, etc., up to a maximum of M columns. In which case, the below will work.

size_t N = 6;
size_t M = 4;
double **matrix = new double*[N];

for (size_t i = 0; i < N; i++) { 
   size_t cols = std::min( i + 1, M ); // determine the correct number of cols for the row
   matrix[i] = new double[cols]; 
   for (size_t p = 0; p < cols; p++) { 
      matrix[i][p] = rand() % 101 - 50; 
      cout << setw(5) << matrix[i][p]; 
   }
}

Btw, I'd suggest using something more modern than rand().

Would also generally recommend not using new, and instead preferring std::unique_ptr or std::shared_ptr, or in this case using std::vector. Don't forget to delete as well.

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
  • 1
    And try to avoid new/delete, e.g. use std::array,4> or std::vector>. Even in this bit of example code I am missing the necessary "delete" calls (and thus it leaks memory) – Pepijn Kramer Dec 16 '21 at 13:46
  • Chris, thank you so much, it really worked! Sorry, I don't know much about programming and I don't have anyone to ask about the problem. :( – krakozyabrr Dec 16 '21 at 13:50