-1

So I created a program where a user would input how many students to calculate their quiz scores and asks the user for 3 quiz scores and sum it all up. I currently have it all working except for taking the sum of the quiz scores in which on the first loop it has a large value. (See image below)

Sample Output

And here is my code:

#include <iostream>
#include <conio.h>

using namespace std;
int main() {
    int count;
    string student[100];
    
    
    cout<<"How many students do you want to calculate for? ";
    cin>>count;
    cin.ignore();
    int grades[count][3];

    for (int i = 0; i<count; i++) {
        cout<<"Enter Student Name: ";
        getline (cin, student[i]);
        cout<<"Enter quiz scores: ";
        for (int a = 0; a<3; a++) {
        cin>>grades[i][a];  
        }
        cin.ignore();
    }
    
    int sum[count], sum2[count];
        
    for (int i = 0; i<count; i++) {
        for (int a = 0; a<3; a++) {
        sum[i] = grades[i][a];
        sum2[i] = sum2[i] + sum[i]; 
        }
    }
    
    cout<<"\n";
    
    for (int i = 0; i<count; i++) {
        cout<<"\nStudent Name: "<<student[i]<<" | Quiz Scores: ";
        for(int a = 0; a<3; a++) {
            cout<<grades[i][a]<<" ";
        }
        cout<<"| Sum of grades: "<<sum2[i];
    }
    
        
}
DeeMastah
  • 1
  • 1
  • 1
    If output is a text: please copy-paste it into a question, rather than creating an image out of it. – Algirdas Preidžius Dec 08 '20 at 16:09
  • 1
    Aside from using [variable length arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) you're not initializing the values in `sum` or `sum2`. What do you expect `sum2[i] = sum2[i] + sum[i]` to do when you haven't provided a starting value for `sum2[i]`? – Nathan Pierson Dec 08 '20 at 16:09
  • Oh thanks! I got it now :) – DeeMastah Dec 08 '20 at 16:12

1 Answers1

0

The first loop had a large value because I didn't set a starting value for sum2[i] so I added sum2[i] = 0; on the first for loop.

    for (int i = 0; i<count; i++) {
    sum2[i] = 0; \\Set the starting value for sum2[i] to 0
        for (int a = 0; a<3; a++) {
        sum[i] = grades[i][a];
        sum2[i] = sum2[i] + sum[i];
        ave[i] = sum2[i]/3;
        }
    } 
DeeMastah
  • 1
  • 1
  • It will have an intedetermine value and reading it will give the program undefined behaviour. You'll need to do the same for all other `sum2[i]` too, not just `sum2[0]`, because the latter will just move the problem to the 2nd iteration of the loop (whether or not it ends up manifesting; that's UB). – underscore_d Dec 08 '20 at 16:17
  • 1
    You may find it useful to initialize all variables as a good habit. That way when you see an uninitialized variable it will feel like a code smell. – EvilTeach Dec 08 '20 at 16:22