Hey, me again i need help with 2D Arrays

Hey guys so i just watched a lesson about 2D arrays and in the end of the video, the teacher said "you should challenge yourself with doing a multiplacition table" so i tried to do it but i couldn't so i looked it up in google and youtube and i learned some things and i created this code, but i didn't understand the logic behind " multip[i][j] = i*j;" this code, and my program doesnt show "100" at the end stops at 81 i'd like to know why this happens too. Thankssss

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  #include <iostream>
using namespace std;
int main()
{
    int multip[10][10] {

    };
    for (int i = 1 ;i < 11; i++){
        for (int j = 1; j<11; j++){
           multip[i][j] = i*j;

          cout <<multip [i][j] << " " <<  flush;

        }cout << endl;
    }

    return 0;
}
Last edited on
I see you have edited your post, so I don't know if this is a change you have made or not. The failure is because in C and C++, all arrays are indexed starting with zero, not one.

The point of a matrix is that it is a 2D array, with row indices i and column indices j. As with any multiplication table, the cell at row i and column j has value i×j. However, in C++, you need that index to be i-1 and j-1.

You do not need to flush after every single output.

This code is technically doing two things at the same time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iomanip>
#include <iostream>

int main()
{
  int multiplication_table[10][10];

  // fill the table
  for (int i = 1; i < 11; i++)
  for (int j = 1; j < 11; j++)
    multiplication_table[i-1][j-1] = i*j;

  // display the table
  for (int i = 0; i < 10; i++)
  {
    // print a single row
    for (int j = 0; j < 10; j++)
      // print each cell
      std::cout << std::setw(4) << std::right << multiplication_table[i][j];
    // newline for next row
    std::cout << "\n";
  }
}

Doing it at the same time means you don’t actually need the table:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iomanip>
#include <iostream>

int main()
{
  for (int i = 0; i < 10; i++)
  {
    for (int j = 0; j < 10; j++)
      std::cout << std::setw(4) << std::right << ((i+1) * (j+1));
    std::cout << "\n";
  }
}

Hope this helps.
Last edited on
Both dimensions of multip are size 10. this means valid indices are 0 - 9. i < 11 will result in i = 10 at some point which is an error.

There is no reason to use an array in this example;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()
{
    const int SIZE = 11;

    for (int i = 1 ;i < SIZE; i++){
        for (int j = 1; j<SIZE; j++){


          cout << i * j << " " <<  flush;

        }cout << endl;
    }

    return 0;
}
Topic archived. No new replies allowed.