0

Please suggest alternate code for Traingular matrices.

#include <iostream>

using namespace std;

int main(void)
{
    int rows = 5, cols = 5;
    int **arr;
    // allocate and initialize the array
    arr = new int * [rows];
    for (int r = 0; r < rows; r++) {
        arr[r] = new int[r + 1];
        for(int c = 0; c <= r; c++)
            arr[r][c] = (r + 1) * 10 + c + 1;
    }
    // print the array
    for(int r = 0; r < rows; r++) {
        for(int c = 0; c <= r; c++)
            cout << arr[r][c] << " ";
        cout << endl;
    }
    // free the array
    for(int r = 0; r < rows; r++)
        delete [] arr[r];
    delete [] arr;
    return 0;
}
{

Edited by mike_2000_17: moved to C++ forum

3
Contributors
2
Replies
15
Views
2 Years
Discussion Span
Last Post by David W
0

That code looks OK (by beginner's standards, of course). What is the problem you are having with it? What kind of an alternative are you looking for? Why?

0

Note your line 7 could be changed to ...

int rows = 5; //, cols = 5; // cols is not used below

and you could use functions for each step ...

// allocate and initialize the array
// print the array
// free the array

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.