c++coutactivity-finish

Program exits before executing rest of the program


I am trying to create a students program but it stops after I put the 4th name, it doesn't allow me to put the grades neither shows the list at the end...

#include<iostream>

using namespace std;

int main()

{

    string name[4];
    double g1[4],g2[4],avg[4];
    int cont;
    for(cont=1;cont<=4;cont++)
    {
        cout<<"STUDENT "<<cont<<"\n";
        cout<<"Name: ";
        cin>>name[cont];
        cout<<"First Grade: ";
        cin>>g1[cont];
        cout<<"Second Grade: ";
        cin>>g2[cont];
        avg[cont]=(g1[cont]+g2[cont])/2;
    }
    cout<<"STUDENTS LIST"<<"\n";
    cout<<"--------------"<<"\n";
    for(cont=1;cont<=4;cont++)
    {
        cout<<name[cont]<<" "<<avg[cont]<<"\n";
    }
}

Solution

  • The two loops for(cont=1;cont<=4;cont++) is wrong because you can only use indice 0, 1, 2, 3 for 4-element arrays.

    You should use for(cont=0;cont<4;cont++) instead and change cout<<"STUDENT "<<cont<<"\n"; to cout<<"STUDENT "<<(cont+1)<<"\n";.

    Another option is to add one more elements to each arrays. First elements of the arrays won't be used then, but this may contribute for readability for you.