Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Build a number guessing game that uses input validation (isdigit() function) to

ID: 640663 • Letter: B

Question

Build a number guessing game that uses input validation (isdigit() function) to verify that the user has entered a digit and not a non-digit (letter) to store a random number between 1 and 10 into a veriable each time the program is run. Prompt the user to guess a number between 1 and 10 and alert the user if he was correct or not.

This is what I have but if I guess correctly it still says I guessed incorrectly

#include <stdio.h>

#include <ctype.h>

main()

{

int iRandomNum;

iRandomNum = (srand() % 10 ) + 1;

int iResponse;

printf(" Guess a number between 1 and 10. ");

scanf("%c", &iResponse);

if (isdigit(iResponse))

{

if (iResponse==iRandomNum)

{

printf(" You have correctly guessed %d", iRandomNum);

}

else

{

printf(" You have incorrectly guessed %c", iResponse);

printf(" The Correct answer is %d", iRandomNum);

}

}

else

{

printf(" Your input was invalid ");

}

}

Explanation / Answer

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
   srand(time(NULL));
   int iRandomNum;
   iRandomNum = (rand() % 10) + 1;
   int iResponse;
   printf(" Guess a number between 1 and 10. ");
   scanf("%c", &iResponse);
   if (isdigit(iResponse)) {
       if (iResponse - 48 == iRandomNum) {
           printf(" You have correctly guessed %d", iRandomNum);
       } else {
           printf(" You have incorrectly guessed %d", iResponse - 48);
           printf(" The Correct answer is %d", iRandomNum);
       }
   } else {
       printf(" Your input was invalid ");
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote