lundi 21 janvier 2019

Creating a Dynamic 2D Array that has x y coordinates like a graph

I need help in displaying a 2D array that starts (x,y) = (0,0) on the bottom left corner.

This is what i have so far, i have trouble making the bottom left corner as (0,0). What i have is

x1y1, x1y2, x1y3, x1y4, x1y5,

x2y1, x2y2, x2y3, x2y4, x2y5,

x3y1, x3y2, x3y3, x3y4, x3y5,

x4y1, x4y2, x4y3, x4y4, x4y5,

x5y1, x5y2, x5y3, x5y4, x5y5,

Whereas i want to have

x1y5, x2y5, x3y5, x4y5, x5y5,

x1y4, x2y4, x3y4, x4y4, x5y4,

x1y3, x2y3, x3y3, x4y3, x5y3,

x1y2, x2y2, x3y2, x4y2, x5y2,

x1y1, x2y1, x3y1, x4y1, x5y1,

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

string ** array2D = nullptr;

void init2DArray(int, int);
void populate2DArray (int, int);
void display2DArray (int, int);
void safelyDeallocateMemory (int, int);

int main() {
   int row, col;
   row = col = 0;
   cout << "Pls enter no. of cols : ";
   cin >> col;
   cout << endl;

   cout << "Pls enter no. of rows : ";
   cin >> row;
   cout << endl;

    init2DArray (col, row);
    populate2DArray (col, row);
    display2DArray (col, row);
    safelyDeallocateMemory (col, row);

    cout << endl;

  return 0;
 }

void init2DArray (int col, int row) {
        array2D = new string * [row];

        for (int i = 0; i < row; i++)
              array2D [i] = new string [col];
}

void populate2DArray (int row, int col) {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {

                ostringstream oss;
                oss << "x" << i + 1 << "y" << j + 1;

                array2D [i][j] = oss.str();
             }
         }
  }

void display2DArray (int col, int row) {
        cout << endl;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                cout << array2D [i][j] << ", ";
            }
            cout << endl;
        }
 }

Aucun commentaire:

Enregistrer un commentaire