vendredi 26 octobre 2018

How to print one side of the diagonal of an array?

Lets suppose we have a 5 X 5 random array
1 2 3 7 8
4 7 3 6 5
2 9 8 4 2
2 9 5 4 7
3 7 1 9 8
Now I want to print the left side of the diagonal shown above, along with the elements in the diagonal, like
1 2 3 7 8
4 7 3 6
2 9 8
2 9
3
The code I've written is

#include <iostream>
#include <time.h>


using namespace std;

int main(){
    int rows, columns;

    cout << "Enter rows: ";
    cin >> rows;
    cout << "Enter colums: ";
    cin >> columns;

    int **array = new int *[rows]; // generating a random array
    for(int i = 0; i < rows; i++)
        array[i] = new int[columns];

    srand((unsigned int)time(NULL)); // random values to array

    for(int i = 0; i < rows; i++){        // loop for generating a random array
        for(int j = 0; j < columns; j++){
            array[i][j] = rand() % 10;    // range of randoms
            cout << array[i][j] << " "; 
        }
        cout << "\n";
    }

    cout << "For finding Max: " << endl;

    for(int i = 0; i < rows; i++){//loop for the elements on the left of
        for(int j = columns; j > i; j--){//diagonal including the diagonal
             cout << array[i][j] << " "; 
        }
        cout << "\n";
    }
    return 0;
}

After running the code the shape I get is correct , but the elements do not correspond to the main array. I have no idea what the problem is.

Aucun commentaire:

Enregistrer un commentaire