Lambuss Lambuss - 3 months ago 4
C++ Question

I do not understand why I am getting this error: 'else' without a previous 'if'. please anyone?

I am trying to write a code that would calculate the average of as many test scores as the user wants. However, when compiling it with g++ compiler, I get the error:

'else' without a previous 'if'

the only 'else' statement of the code is in the following for loop. that's why i am omitting the rest of the code. Anyone, please tell me what i am doing wrong here. I can't seem to find the answer anywhere. Thanks in advance!

int i, j;
cout >>"How many tests' scores you want to average; \n";
cin << i;

// Assuming i > 0

int test[i]

for (j = 0; j < i; j++)
{
if (j == 0)
cout <<"Enter the 1st score: \n";
cin >> test[j];
if (j == 1)
cout <<"Enter the 2nd score: \n";
cin >> test[j];
if (j == 2)
cout <<"Enter the 3rd score: \n";
cin >> test[j];
else
cout <<"Enter the "<< (j+1) <<"th score: \n";
cin >> test[j];
}

Answer

None of your ifs are actually blocks; you need braces around the body, or they only control execution through to the next semi-colon.

Indenting it the way the compiler actually sees the control flow, this is what you have:

   if (j == 2)
       cout <<"Enter the 3rd score: \n";
   cin >> test[j];

   else
       cout <<"Enter the "<< (j+1) <<"th score: \n";
   cin >> test[j];

when what you want is:

   if (j == 2) {
       cout <<"Enter the 3rd score: \n";
       cin >> test[j];
   } else {
       cout <<"Enter the "<< (j+1) <<"th score: \n";
       cin >> test[j];
   }

You also probably want the two prior ifs to be blocks as well, and to make the second and third ifs into else ifs; otherwise, the else block will execute for any value of j aside from 2 (alternatively, you use a switch).