Hi, this is my first post here so I hope I include everything I need to.
The purpose of this program is to compare the correctAnswers array to the studentAnswers array and determine how many the student got correct. That part seems to be compiling fine...the problem is when I try to execute the 'if' statement concerning if the user does not enter A, B, C, or D. Xcode keeps telling me the code will never be executed and for the life of me I can't figure out why not. That line never executes even if I input letters that aren't A, B, C, or D.
#include <iostream>
usingnamespace std;
int main()
{
char A ='A';
char B= 'B';
char C= 'C';
char D= 'D';
char i;
char correctAnswers[]={'B','D','A','A','C','A','B','A','C','D'};
char studentAnswers[10];
int matchingCount=0;
for (int i=0; i<10; i++)
{
cout<<"Enter your test answers: "<<endl;
cin>>studentAnswers[i];
}
for (int i=0; i<10; i++)
if (studentAnswers[i]==correctAnswers[i])
matchingCount++;
if (matchingCount>=8){
cout<<"Congratulations!"<<endl;
cout<<"You passed the exam."<<endl;
cout<<"Total number of correct answers: "<<matchingCount<<endl;
cout<<"Total number of incorrect answers: "<<10-matchingCount<<endl;
}
elseif (matchingCount<=7){
cout<<"Sorry, you have not passed the exam!"<<endl;
cout<<"Total number of correct answers: "<<matchingCount<<endl;
cout<<"Total number of incorrect answers: "<<10-matchingCount<<endl;
}
elseif (studentAnswers[i]!='A'||'B'||'C'||'D'){
cout<<"A, B, C, and D are the only valid inputs."<<endl;
}
return 0;
}
You actually want to check if the user input a valid answer when they actually provide it, so your bit of code you're struggling with actually needs to be in your first for statement where the user enters the test answers.
As to why it never executes, notices your first two if, if-else statements.
if ( matchingCount >= 8 )
If that evaluates to false, it MUST be less than or equal to seven, which is your next condition:
else if ( matchingCount <= 7 )
The third if-else never executes because one of the conditions above it must be true.
Finally, you're conditions for valid answers are incorrect. You need to compare each character to the variable.
At what point would matchingCount ever not be >= 8 or <= 7? Once one of those conditions is true the loop ends, therefore the last part will never be checked.
Wow, thank you both so much. That was such an easy solution I just couldn't see it, I've been staring at my code for too long.
It works perfectly now, you saved me many more hours of frustration.