array question

I am trying to fill my array with even numbers 2to30 in a 5x3 array. Im a newbie and am quite clueless. Looking for some help. Im doing something wrong but not sure what I have included the coded and the output of what I am currently getting.

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
// variables
int array_1[5][3];

int x=2;




for (int r=0; r<=4; r=r+1)

{
for (int c=0; c<=2; c=c+1)
{
array_1[r][c]=x;
x=x+2;
}
}
cout<<"hello""\n";
for (int r=0; r<=4; r=r+1)
for (int c=0; c<=2; c=c+1){
cout<<array_1[r][c]<<" "<<array_1[r][c]<<" "<<array_1[r][c]<<"\n";
}

return 0;
}


// output that I get is below

hello
2 2 2
4 4 4
6 6 6
8 8 8
10 10 10
12 12 12
14 14 14
16 16 16
18 18 18
20 20 20
22 22 22
24 24 24
26 26 26
28 28 28
30 30 30
Program ended with exit code: 0

looking to get what I have below in an array

2 4 6
8 10 12
14 16 18
20 22 24
26 28 30


thanks for the help in advance
Your code to output the array
1
2
3
for (int r=0; r<=4; r=r+1)
for (int c=0; c<=2; c=c+1){
cout<<array_1[r][c]<<" "<<array_1[r][c]<<" "<<array_1[r][c]<<"\n";

should look something like this, notice the endl after the closing brace of the inner loop:
1
2
3
4
5
6
7
8
    for (int r=0; r<=4; r=r+1)
    {
        for (int c=0; c<=2; c=c+1)
        {
            cout << setw(3) << array_1[r][c];
        }
        cout << endl;
    }


Also I'd recommend the use of defined constants for the array dimensions, to avoid repeatedly coding magic numbers such as 2 or 4 throughout the code. Perhaps like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
    const int height = 5;  // constants for array size
    const int width  = 3;
    int array_1[height][width];

    int x=2;

    for (int r=0; r<height; r++)
    {
        for (int c=0; c<width; c++)
        {
            array_1[r][c]=x;
            x += 2;
        }
    }
    cout<<"hello""\n";
       
    for (int r=0; r<height; r++)
    {
        for (int c=0; c<width; c++)
        {
            cout << setw(3) << array_1[r][c];
        }
        cout << endl;
    }

    return 0;
}

This approach not only is clearer to read and understand, but also makes it very simple to change the values of height or width, it would need to be altered just once on a single line of code.
Last edited on
Topic archived. No new replies allowed.