0

by now I have this code

int main() {
int cols;
cout << "cols";
cin >> cols;
int rows;
cout << "rows";
cin >> rows;


char** charArray = new char*[rows];
for (int i = 0; i < rows; ++i) {
    charArray[i] = new char[cols];
}

// Fill the array
for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < cols; ++j) {
        charArray[i][j] = char('1' + i + j );
    }
}

// Output the array
for (int i = 0; i < rows; ++i) {
    for (int j = i; j < cols ; ++j) {
        cout << charArray[i][j];
    }
    cout << endl;
}



// Deallocate memory by deleting
for (int i = 0; i < rows; ++i) {
    delete[] charArray[i];
}

and the output is like 1 2 3 2 3 4

How can I make it to be 1 2 3 4 5 6

I tried a lot, im a newbie in programming so can you please explain me what's the matter with this problem! Thanks a lot!!

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • 2
    Please have a look at this [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) list, take [the tour](https://stackoverflow.com/tour) and read [the help page](https://stackoverflow.com/help). Welcome to SO. – Ron Feb 23 '18 at 14:36

3 Answers3

3

Just change this:

charArray[i][j] = char('1' + i + j );

by:

 charArray[i][j] = char('1' + i*cols + j);

BTW: You have a typo in the output array loop:

for (int j = i; j < cols ; ++j) {

Should be:

for (int j = 0; j < cols ; ++j) {
Rama
  • 3,222
  • 2
  • 11
  • 26
1

Array filling loop should be

int count = 0;     
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
    charArray[i][j] = char('1' +count );
count++;
}
}

try with above code

Yash Thakor
  • 129
  • 3
  • 10
0

You are building a matrix, here right. So it's 2-dimensional. What the output means is that your matrix looks like:

1 2 3
2 3 4

Which is only natural, since, while filling it, you wrote for each element at coordinate i,j to be value 1+i+j. That means if i and j both equal 1 (second line, second column, since index start at 0), you put value the 1+1+1=3.

If you want to get the matrix:

1 2 3
4 5 6

You'll have to fill it with

charArray[i][j] = char('1' + i*ncols + j );

This way when you fill the first line, i = 0, so it's the same. But then on the second line, i=1, so you get 1 + 3 + 0 = 4. And then 1+3+1=5, etc.

Edit: people are fast here. By the time I write my answer, already 2 others posted theirs :D

Andéol Evain
  • 507
  • 2
  • 12