Problems with my table

So for part of my assignment I have to make a table with 12 rows and 3 columns. I wrote that but I'm not getting the output I want so far. This is what I have.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <iostream>
#include <iomanip>
using namespace std;
 
int main ()
{
   // an array with 5 rows and 2 columns.
   int a[12][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
 
   // output each array element's value  
   cout << left << setw(12) << "Month" << setw(12) << "Rainfall(mm)" << "\t" << setw(12) << "Classification" << endl;
   cout << left << setw(12) << "-----" << setw(12) << "-----------" << "\t" << setw(12) << "--------------" << endl;

                    
   for ( int i = 0; i < 12; i++ )
      for ( int j = 0; j < 3; j++ )
      {
       
         cout << a[i][j]<< endl;
      }
 
   return 0;
}


The output looks 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
35
36
37

Month       Rainfall(mm)	Classification

1
2
3
4
5
6
7
8
9
10
11
12
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0


So yeah there's too many rows. Any ideas on how to fix this?
Last edited on
Just have 3 arrays.

1
2
3
	int a[12] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
	int b[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	int c[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };



and have one loop.

1
2
3
	for (int i = 0; i < 12; i++) {
		cout << left << setw(12) << a[i] << setw(12) << b[i] << "\t" << setw(12) << c[i] << endl;
	}


You could create a struct if you wanted to contain the values together. The struct would have a month, rainfall and Classification then have a list or array of those. 3 separate arrays also works
Your array has 12x3 = 36 elements, but you are only declaring 12 of them.

You are starting a new line (with endl) at every pass of the inner (j) loop, but it only needs to be done at the end of the outer (i) loop.
OK thanks a lot that was it switchy!
Here is the struct version.
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
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main()
{
	// an array with 5 rows and 2 columns.
	struct readings {
		int month;
		int rainfall;
		int classification;
	};

	vector<readings> mylist;

	for (int i = 0; i < 12; i++) {
		readings myreading{ i+1,0,0 };
		mylist.push_back(myreading);
	}

	// output each array element's value  
	cout << left << setw(12) << "Month" << setw(12) << "Rainfall(mm)" << "\t" << setw(12) << "Classification" << endl;
	cout << left << setw(12) << "-----" << setw(12) << "-----------" << "\t" << setw(12) << "--------------" << endl;


	for (int i = 0; i < 12; i++) {
		cout << left << setw(12) << mylist[i].month << setw(12) << mylist[i].rainfall << "\t" << setw(12) << mylist[i].classification << endl;
	}

	system("Pause");
	return 0;
}
Topic archived. No new replies allowed.