I have written following code where 2 numbers are generated randomly and added into third variable. It then asks the user for accurate answer. Currently right answer is always 'A'
. a1
is the actual answer whereas a2,a3,a4
are the randomly generated answers.
I have put condition to see if the answer given is in the range of a,b,c,d
or A,B,C,D
using ASCII values. If it does not fit then message given is invalid answer
.
If the answer is 'A'
or 'a'
it gives message "Answer is correct!\nDo you want to play again? (y/n)"
else it shows "Answer is incorrect!\nDo you want to play again? (y/n)"
.
After any answer it asks whether the user wants to continue. However after "Do you want to play again?"
it exits the compiler even the scanf
function is there.
I want to keep it repeating till user answers anything else than 'y'
or 'Y'
. As the char
data type was not working I have tried to uses integer variable 'condition' but still not getting desired answer.
#include <stdio.h>
#include <conio.h>
void main() {
int n1, n2, a1, a2, a3, a4, condition = 1;
char again = 0, answer;
srand(time(0));
while (condition == 1) {
n1 = rand() % 10;
n2 = rand() % 10;
printf("\n\n%d + %d=\n\n", n1, n2);
a1 = n1 + n2;
a2 = rand() % a1;
a3 = rand() % a1 + 10;
a4 = rand() % a1 + 2;
printf("Your options are:\n\nA) %d\nB) %d\nC) %d\nD) %d\n\n "
"What is your answer:\n", a1, a2, a3, a4);
scanf("%c", &answer);
if (answer > 64 && answer < 69) {
if (answer == 'a' || answer == 'A') {
printf("Answer is correct!\nDo you want to play again? (y/n)");
} else {
printf("Answer is incorrect!\nDo you want to play again? (y/n)");
}
} else if (answer > 96 && answer < 101) {
if (answer == 'a' || answer == 'A') {
printf("Answer is correct!\nDo you want to play again? (y/n)");
} else {
printf("Answer is incorrect!\nDo you want to play again? (y/n)");
}
} else {
printf("Invalid answer!\nDo you want to play again? (y/n)");
}
scanf("%c", &again);
if (again == 'y' || again == 'Y') {
condition = 1;
} else {
condition = 0;
}
}
getch();
}