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";
}
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:
#include <iostream>
#include <cmath>
#include <iomanip>
usingnamespace std;
int main()
{
constint height = 5; // constants for array size
constint 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.