Advertisement
steamengines

Dynamic 2D Array

Apr 16th, 2015
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. #include<iostream>
  2. #include<iomanip>
  3. #include<ctime>
  4. using namespace std;
  5.  
  6. int ** build2DArray(const int students, const int grades);
  7. void getGrades(int ** gPtr, const int students, const int grades);
  8. void displayGrades(int ** gPtr, const int students, const int grades);
  9. void getAverage(int ** gPtr, const int students, const int grades);
  10.  
  11. int main()
  12. {
  13.     int students, grades;
  14.     int ** gradePtr;
  15.  
  16.     cout << "How many students are there? ";
  17.     cin >> students;
  18.  
  19.     cout << "Enter how many grades there are. (Between 1 and 15) ";
  20.     cin >> grades;
  21.  
  22.     gradePtr = build2DArray(students, grades);
  23.     getGrades(gradePtr, students, grades);
  24.     displayGrades(gradePtr, students, grades);
  25.     getAverage(gradePtr, students, grades);
  26.  
  27.  
  28.     system("pause");
  29.     return 0;
  30. }
  31.  
  32. int ** build2DArray(const int students, const int grades)
  33. {
  34.     int** ptr;
  35.     if (grades <= 0)
  36.     {
  37.         ptr = NULL;
  38.         return ptr;
  39.     }
  40.  
  41.     ptr = new int*[students];
  42.  
  43.     for (int i = 0; i < students; i++)
  44.         ptr[i] = new int[grades];
  45.  
  46.     return ptr;
  47. }
  48.  
  49. void getGrades(int ** gPtr, const int students, const int grades)
  50. {
  51.     srand(time(NULL));
  52.  
  53.     for (int i = 0; i < students; i++)
  54.         for (int*p = gPtr[i]; p < &gPtr[i][grades];)
  55.             *p++ = rand() % 100 + 1;   
  56. }
  57.  
  58. void displayGrades(int ** gPtr, const int students, const int grades)
  59. {
  60.     cout << "STUDENT GRADES" << endl;
  61.  
  62.     for (int r = 0; r < students; r++)
  63.     {
  64.         cout << "Student " << r + 1 << " Grades: ";
  65.  
  66.         for (int c = 0; c < grades; c++)
  67.             cout << setw(4) << gPtr[r][c];
  68.         cout << endl;
  69.     }
  70.     cout << endl << endl;
  71. }
  72.  
  73. void getAverage(int ** gPtr, const int students, const int grades)
  74. {
  75.     float sum = 0.0;
  76.     float average;
  77.  
  78.     cout << "AVERAGE OF GRADES FOR EACH STUDENT" << endl;
  79.     cout << setprecision(1) << fixed;
  80.     for (int r = 0; r < students; r++)
  81.     {
  82.         cout << "Student " << r + 1 << " Grades: ";
  83.         sum = 0;
  84.         for (int c = 0; c < grades; c++)
  85.  
  86.             sum += gPtr[r][c];
  87.  
  88.         average = (sum / grades);
  89.         cout << setw(5) << average;
  90.         cout << endl;
  91.     }
  92.     cout << endl << endl;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement