I'm trying to write a program that uses vector to store the grades for the number of students entered.But i seem to be getting some problems with my code.
I am able to enter the number of students, but when it asks for the grades, the program exits.

I hope someone can tellme whats wrong with my code

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> Grades;
    int i= 0;

    cout << "Enter number of students: ";
    cin >> i;

    for( i = 0; i < 0; i++)
    {
            cout << "Enter grade for student" << (i + 1) << ": ";
            cin >> Grades[i];
    }


    int Total = 0;
    for(int i = 0; i < 0; i++)
    {
            // Add to the total
            Total += Grades[i];
    }

    double Average = (double)Total / i;
    cout << "Average Mark: " << Average << "\r\n";
    system("PAUSE");
    return 0;
}
  1. You are storing the number of students into i, which gets reassigned a new value. Store the number of students into another integer variable (num, perhaps?).
  2. At lines 15 and 23, you use i for the counter, starts at 0, but your condition is that it will end once i is greater than or equal to 0 which means your for loops do nothing at all. You are supposed to use another integer variable (num) at the condition. for(i = 0; i < num; i++);

ah.. thanks for pointing that out.

I've changed my code, however i'm getting a debug assertion failed! error after entering the no. of students.

#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> Grades;
    int num;
    int i;

    cout << "Enter number of students: ";
    cin >> num;

    for( i = 0; i < num; i++)
    {
            cout << "Enter grade for student " << (i + 1) << ": ";
            cin >> Grades[i];
    }

    int Total = 0;
    for(int i = 0; i < num; i++)
    {
            // Add to the total
            Total += Grades[i];
    }
    double Average = (double)Total / num;
    cout << "Average Mark: " << Average << "\r\n";
    system("PAUSE");
    return 0;
}

That happens because you are trying to access the elements of an empty vector. You could do two things: first would be to resize the vector after you input the number of students (syntax: Grades.resize(num); or, initialize the vector entirely after the number of students is entered (aka move line 9 to line 15, and include num as the size)

thanks, that solved my problems.
If I would like to count the number of passing & failing grades from the grades that are stored in the vector. How I am supposed to write a code for it?

Just use an if-else statement and a pair of counters within one of the for loops. (preferably the 2nd for loop)

ah, thanks for the tip. totally solved my problems.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.