patterncModerate
Randomized response generator for number-guessing game
Viewed 0 times
numberresponserandomizedgeneratorgameforguessing
Problem
I am currently learning C and playing around with the
The code below works fine, it's just randomize the output every time someone answers the question incorrectly.
Is there any way to make it shorter, instead of using
rand() and if/else statement. This code looks long, just curious if there is another way to make the code shorter?The code below works fine, it's just randomize the output every time someone answers the question incorrectly.
while(input != c){
srand(time(NULL));
int i;
i = rand() % 5 + 1;
if (i == 1)
{
printf("No. Please try again.\n");
scanf("%d", &input );
}
else if(i == 2){
printf("Wrong. Try once more.!\n");
scanf("%d", &input );
}
else if(i == 3){
printf("Don't give up!\n");
scanf("%d", &input );
}
else if(i == 4){
printf("No. Keep trying.!\n");
scanf("%d", &input );
}
}Is there any way to make it shorter, instead of using
if/else over and over?Solution
A standard technique is to setup an array of strings and index it with a random number:
char * answers[] = { "Wrong!", "No", "Try again"};
....
if (guess_is_wrong) {
int i = random() % (sizeof(answers) / sizeof(answers[0]));
printf("%s\n", answer[i]);
}Code Snippets
char * answers[] = { "Wrong!", "No", "Try again"};
....
if (guess_is_wrong) {
int i = random() % (sizeof(answers) / sizeof(answers[0]));
printf("%s\n", answer[i]);
}Context
StackExchange Code Review Q#66815, answer score: 17
Revisions (0)
No revisions yet.