Created
March 11, 2013 19:28
-
-
Save ereidland/5136943 to your computer and use it in GitHub Desktop.
Example 3 at Library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
using namespace std; | |
int main() | |
{ | |
//Note that in the below example I do not validate the numbers. This is bad practice. Don't do it. | |
int numStudents, | |
numScores, //Values can be separated by comma if they have the same base type. | |
**scores; //For declaring pointers like this, the ** is associated with the value separated by the comma. | |
//scores is an array of arrays. | |
//scores is a pointer to the first element in an array of pointers, where each pointer points to the first element | |
//of the array of scores for that specific student. | |
cout << "Enter a number of students: "; | |
cin >> numStudents; //Get number of students. | |
scores = new int*[numStudents]; //Create scores as a new array of int arrays of numStudents size. | |
//Note that arrays are just pointers to the first element in the array. | |
cout << "Enter number of scores: "; | |
cin >> numScores; //Get number of scores. | |
for (int i = 0; i < numStudents; i++) //Loop from 0 to < numStudents. Note that the value at numStudents is not included. So: 0 to numStudents - 1 | |
{ | |
scores[i] = new int[numScores]; //Set the scores pointer at i to be a new array of numScores size. | |
for (int j = 0; j < numScores; j++) //Loop from 0 to < numScores | |
{ | |
cout << "Enter score[" << j << "] for student[" << i << "]: "; | |
cin >> scores[i][j]; //Set value of array at i, at that array's element j, to the read value. | |
} | |
} | |
for (int i = 0; i < numStudents; i++) //Loop from 0 to < numStudents. | |
{ | |
//Show the score array at i. | |
cout << "Student " << i << ":" << endl; | |
for (int j = 0; j < numScores; j++) //Loop from 0 to < numScores. | |
{ | |
cout << setw(4) //Set next width to 4 characters. | |
<< scores[i][j]; //Print scores at array i, at that array's element j. | |
} | |
cout << endl; //New line in prep for outputting next student. | |
} | |
return 0; //Result to be sent back to the OS once this is complete. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment