I have to enter grades and if I enter a negative grade then the program is supposed to terminate. I came up with this code but it doesn't terminate it just asks for another grade.

if (grade[i]<0)
		cout << "This is not a correct grade";

Any suggestions?

#include "stdafx.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	const int MAXGRADES = 5;
	int i, grade[MAXGRADES], sum = 0;
	double Avg;

	for (i=0; i < MAXGRADES; i++)
	{
		cout << "Enter a grade: ";
		cin  >> grade[i];

    if (grade[i]<0)
		cout << "This is not a correct grade";
			
	}

    

	cout << endl;

	for (i=0; i < MAXGRADES; i++)
		cout << "grade " << i << " is " << grade[i] << endl;

	cout <<"\nThe sum of the grades";
	
	for (i=0; i<MAXGRADES; i++)
	{
		
		cout << "  " << grade[i];
		sum = sum + grade[i];
	}
	cout << " are " << sum << endl;

	if (MAXGRADES>0)
		Avg = sum / MAXGRADES;
	
	cout << endl << "The average is: " << Avg << endl;

	return 0;
}

try this:

if (grade[i]<0)
{
    cout << "This is not a correct grade";
    break; // exit the loop
 }

Also -- you need a counter to count the number of grades entered because there may be fewer than MAXGRADES. Then use that counter in the code that follows.

>>if (MAXGRADES>0)
That is an impossible comparison because MAXGRADES will never be anything other than what it is initialized to be at the beginning of the program. Instead of MAXGRADES you need to use the counter that I mentioned above.

That worked for the termination. When I enter a negative number the program ends but gives a value of -858993460 to the remaining values up to 5. Is that why I need to change the counter?

>> Is that why I need to change the counter?
yes, because the elements of the array that you did NOT enter contain random values. You should probably initialize the array elements to all 0 at the time it is declared like this

int grade[MAXGRADES] = {0};

not necessary, just declare another int named count , initilize it to 0, then increment it in that loop maybe something like this:

for (i=0; i < MAXGRADES; i++, count++)

Then replace for (i=0; i<MAXGRADES; i++) with this for (i=0; i<count; i++)

not necessary, just declare another int named count , initilize it to 0, then increment it in that loop maybe something like this:

for (i=0; i < MAXGRADES; i++, count++)

Then replace for (i=0; i<MAXGRADES; i++) with this for (i=0; i<count; i++)

Or to make it simple, specify the first loop as for (count = 0; count < MAXGRADES; count++) This will automatically count the grades entered, and you won't need i at all.

This article has been dead for over six months. Start a new discussion instead.