Array problems

Hi, all. I'm having some trouble with using an array in a program that I'm working on for class. The specifications call for a program that asks the user to input a number and then returns a multiplication table up to the 10th multiple of that number. I'm supposed to use an array to store the table and then display it on screen, but I haven't been able to get it working as of yet. I've scoured the forums and haven't come up with anything useful, so I was hoping some of you might be willing to help out. Thanks! (code below)

#include <iostream>
using namespace std;
int main()
{
int x = 0;
int table = 0;
int multiples[10] = {0};
cout << "Please enter a number between 1 and 10: ";
cin >> x;
for (int y = 1; y < 11; y += 1)
{
table = x * y;
}
for (int sub = 0; sub < 11; sub +=1) {
multiples[sub] = table;
}
do
{
cout << multiples[x] << endl;
x += 1;
} while (x < 11);
}

EDIT: Thanks, everyone. I think I'll be able to get it working now.
Last edited on
It's crashing because your index is outside the bounds of the array.
You don't need that first for loop you have there. It's just changing the value of the same table variable each time through. You can merge those first two for loops into one, where multiples[sub] is assigned the value of the number the user entered, x, multiplied by (sub + 1) - the current array element offset by one to account for the array numbering starting at 0 while the multiples start at 1 (I'm assuming).

With the while loop you have now, you're using x to access the array to print it out, but x is the number the user entered. You can use a while loop, but you'd want whatever variable you use to access the array to start at 0. You could also use a for loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <iomanip>//std::setw: http://www.cplusplus.com/reference/iomanip/setw/

const size_t SIZE = 10;

int main()
{
    int tables[10];
    std::cout << "Enter the number: \n";
    int num{};
    std::cin >> num;
    for (size_t i = 0; i < SIZE; ++i)
    {
        tables[i] = num * (i + 1);
        std::cout << num << " X" << std::setw(3) << (i+1) << " = " << tables[i] << "\n";
    }
}
Topic archived. No new replies allowed.