1D Arrays and 2D Arrays

Pages: 12
I am a beginning computer science major and coming up on my final lab exam which is unknown exactly what it will be covering. I know that I really do not understand how to use 1D or 2D Arrays, I have been given a homework assignment that looks like this:

The head coach of a local baseball team would like to hire you to write a program that calculates the batting average of every player on his team. Below is the output that he would like displayed. Write a C++ program to accomplish this task. You must design the program yourself using the appropriate input, process, and output functions.

Player AB HITS AVE
Allan 521 192 .369
Brett 493 180 .365
Carl 451 160 .354
Derek 590 205 .347
Mike 501 167 .333
Henry 485 156 .321
Paul 562 180 .320
Steve 499 159 .318
Josh 480 149 .310
Lee 490 150 .306

Totals 5072 1698 .335



I have read over how to do arrays in my textbook, online, and heard explanations from my prof. I just cant wrap my head around it. If anyone could help me out it would be greatly appreciated!

(update) I just submitted and it should be displaying a table above not all together like that, tried fixing it and it just went back like it is.. sorry it's not working with me.
Last edited on
Have you tried watching videos? Becasue there are plenty of them online, and some very good.

Here are two playlists -

https://www.youtube.com/playlist?list=PLAE85DE8440AA6B83
https://www.youtube.com/playlist?list=PL2DD6A625AD033D36

Find the video(s) for arrays, hope it helps :)
To store the data you normally would create an array like that:

 
float PlayerStat[10][3];


PlayerStat[0][0] would store AB of player Allan
I will check out those videos and I will try working on this code tomorrow night and I will post my progress and troubles with it when they occur! Thanks guys!
Okay, I am just now working on this, I have been moving unfortunately. So I declare an array with my constants above main, correct?
closed account (48T7M4Gy)
So I declare an array with my constants above main, correct?

The short answer is no. Declaring anything 'above main' implies global constants which in this problem are not necessary. But you will need an array or two

Please show us some code or pseudocode that you have mapped out and when you reach a stumbling block someone will help if they can.

If the videos don't work for you then the tutorials here might. If all else fails read your textbook and/or your class notes.

Assuming you must use arrays and vectors etc aren't allowed.
Arrays: http://www.cplusplus.com/doc/tutorial/arrays/

Might also be useful:
Data structures: http://www.cplusplus.com/doc/tutorial/structures/
This is where I am right now, it is not very well put together, but just trying to get it working. Lost as can be lol.


#include <iostream>
#include <string>
using namespace std;

//function prototypes
void getNames(string);
void getAverages();

//symbolic constants
int MAX = 100;



int main()
{
float PlayerStat[10][3];
string name, dummy;


getNames(dummy);


}
void getNames(string dummy)
{
for (int i = 0; i < MAX; i++)
{
cout << "Please enter the name's for the each player. " << endl;
getline(cin, dummy);
}
}
//The way I have this is to maybe prompt and get all three scores at once then move on to the next person. Not sure though.
void getAverages()
{
for (int i = 0; i < 3; i++)
{
cout << "Please enter each players AB, hits, and average." << endl;
cin >> ???
}
}

I am going through my textbook right now and will go to tutoring tomorrow to see if I can get help with someone in person, but more that I can get done now the better.
closed account (48T7M4Gy)
it is not very well put together,

You're not kidding!

Here's your error list. How come you haven't even tried to compile it?

Also, please use code tags (<> in the toolbox on the right) and properly indent your code. Getting help is more than just throwing your stuff at people. :)

In function 'int main()':
16:7: warning: unused variable 'PlayerStat' [-Wunused-variable]
In function 'void getAverages()':
38:8: error: expected primary-expression before '?' token
38:9: error: expected primary-expression before '?' token
38:10: error: expected primary-expression before '?' token
39:1: error: expected primary-expression before '}' token
39:1: error: expected ':' before '}' token
39:1: error: expected primary-expression before '}' token
39:1: error: expected ':' before '}' token
39:1: error: expected primary-expression before '}' token
39:1: error: expected ':' before '}' token
39:1: error: expected primary-expression before '}' token

C++ Shell, 20
closed account (48T7M4Gy)
THis is what you have so far after I tidied it up out of the kindness of my heart

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 <string>

void getNames(string);
void getAverages();

int main()
{
    float PlayerStat[10][3];
    string name, dummy;

    int MAX = 100;

    getNames(dummy);
}

void getNames(string dummy)
{
    for (int i = 0; i < MAX; i++)
    {
        std::cout << "Please enter the name's for the each player. " << endl;
        std::cin >> dummy;
    }
}

void getAverages()
{
    for (int i = 0; i < 3; i++)
    {
        cout << "Please enter each players AB, hits, and average." << endl;
        cin >> ???
    }
}
closed account (48T7M4Gy)
The way I suggest you tackle it is to have four arrays (in main) name[], AB[], HITS[], AVE[] and work from there.

Loop in main through each player to get (cin) name[i], AB[i], HITS[i], AVE[i]

Once you have that data loop completed you can create other loops to get totals and averages.
Last edited on
I had compiled my code, just hadn't messed with all of the errors yet, I was more trying to figure out arrays and the way you have it here doing the 4 arrays in main kind of makes a little sense to me. I'll see if I can work with that a little and figure it all out. Also, out of curiosity why remove the using namespace std;? is just doing the std::cin or cout better? I really appreciate the help though!
closed account (48T7M4Gy)
No problem.

Keep it simple and you should be OK. (Multiple dimension arrays won't help all that much. The index value of each element works the same as a key to all the arrays so they are all linked anyway.)

The namespace thing is based on good programming practice to ensure there is no ambiguity in using (standard) functions.

If it all seems a bit heavy stick with using namespace std or google "using namespace std"

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
#include <iostream>
#include <string>

using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	const int MAX = 100;
	string name[MAX];
	string response = "";

	int limit = 0;
        cout << "How many players? ";
        cin >> limit;

        for( int index = 0; index < limit; index++)
	{
		cout << "Player " << index << " name: ";
		cin >> name[index];
	}

	for (int i = 0; i < limit; i++)
		cout << name[i] << endl;

	return 0;
}
Last edited on
Okay, so how do I make it to where I enter in the number of players on the team? Because I want the max players to be 100, but if the user enters in say, 5 they would only put in 5 names and then continue?
closed account (48T7M4Gy)
I'd first write a line or two to get input from the user.
I have that right now, and it allows me to input it how many just not stopping at whatever number I type in.
closed account (48T7M4Gy)
See my revised code.
In C, 2-dimensional arrays are just a neat indexing scheme for 1-dimensional arrays. Just like with a 1D array, 2D arrays allocate a single block of contiguous memory, and the
A[row][col] notation is just like saying A[row*NCOLS+col].

Usually if you were to implement your own multidimensional arrays using single dimensional arrays, you'd write an indexing function:int getIndex(int row, int col) return row*NCOLS+col;
Assuming your compiler inlines this function, the performance here would be precisely the same as if you used the built in 'indexing function' of 2D arrays.

To illustrate:

#define NROWS 10
#define NCOLS 20
This:

int main(int argc, char *argv[]) {
int myArr[NROWS*NCOLS];
for (int i=0; i<NROWS; ++i) {
for (int j=0; j<NCOLS; ++j) {
myArr[getIndex(i,j)] = i+j;
}
}
return 0;
}
Should perform the same as this:

int main(int argc, char *argv[]) {
int myArr[NROWS][NCOLS];
for (int i=0; i<NROWS; ++i) {
for (int j=0; j<NCOLS; ++j) {
myArr[i][j] = i+j;
}
}
return 0;
}
Though as AraK pointed out, if you are jumping around rows alot, and the rows are very large, you could hit a lot of page faults... in that case the custom indexing function (with rows and cols switched around) could help, but so could simply changing which of the dimensions in a 2-dimensional array you treat as the rows and which you treat as the columns.

http://www.traininginsholinganallur.in/java-training-in-chennai.html# | http://www.traininginsholinganallur.in/android-training-in-chennai.html#
That kind of make sense, arrays are starting to come together for me in my head, just putting it down in the code is a little confusing! But I'll be sure to reference that! Thank you Jackman!

and for kemort, I ran that revised code and it wont enter in just 2 members, and when I do submit just the 2, it says enter number 0's name instead of number 1's. Should I just change that from being index = 0 to index = 1?

My professor told us that we should use a structure which is also very new to me! But I will post what I have of that. It has a lot of errors though!

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

//structure declaration
struct PlayerRecord
{
	string name;
	double AB;
	double hits;
	double totalAB;
	double totalHits;
	double average;
	char letter;
	int players;
};


//symbolic constants
const int MAX = 50;

//function prototypes
void getInfo(PlayerRecord player);
void calculateSums(int, int, int, int, double);
void displayResults(struct PlayerRecord player);







int main()
{
	//user defined variables
	char letter;
	double totalPoints = 0.0;
	int totalAB = 0;
	int totalHits = 0;
	int AB = 0;
	int hits;
	double average;
	int limit;
	string name;


	PlayerRecord players;



	getInfo(players);
	calculateSums(totalAB, AB, totalHits, hits, average);
	displayResults(players);


}
//gathers player info
void getInfo(PlayerRecord players[], int limit, string name)
{
	cout << "Enter the number of players. " << endl;
	cin >> players;
	

	for (int i = 0; i < players[MAX]; i++)
	{
		cout << "Name: " << endl;
		cin >> players[i].name;
		cout << "AB: " << endl;
		cin >> players[i].AB;
		cout << "Hits: " << endl;
		cin >> players[i].hits;
	}
	for (int i = 0; i < limit; i++)
		cout << name[i] << endl;

	
}
//calculates the sum of each column
void calculateSums(int totalAB, int AB[] , int totalHits, int hits[], double average, int players[])
{
	totalAB += AB[i];
	totalHits += hits[i];
	average = totalHits / players[MAX];
}
//displays the table of each players, AB, Hits, Average and the total of all three columns
void displayResults(int players, int totalAB, int totalHits, double average)
{
	cout << "Player Name		AB		Hits		Average " << endl;
	cout << "-----------	   ----    ------	    ------- " << endl;

	for (int i = 0; i < MAX; i++)
	{
		cout << setw(15) << left << players[i].name;
		cout << setw(15) << left << players[i].AB;
		cout << setw(15) << left << players[i].hits;
		cout << setw(15) << left << players[i].average;

		cout << endl;

		cout << "Totals: " << totalAB << "     " << totalHits << "     " << average << endl << endl;
	}
}
On the first cout where I am getting the number of players the cin operators >> are saying that there is no operator that matches these operands. Any idea what that is?

I am not worried about the display so much, except where it says players[i] on all of them the [i] says expression must have pointer-to-object type.
Pages: 12