Hey all, Im working on a number guessing game where a user has 10 tries to a guess a number. The program supposed to display user guesses and then the main menu after the game has finished.
Im running into a couple of problems. The first one being that for some reason if user guesses the number right it only displays the guesses up to that number, and i would like to display all guesses including the correct one. The second one being is if the user guesses the correct number and restarts the game, and then loses, the program does not display user guesses. I have tested the program many times and the second problem occurs only after the user wins the previous game. Hope you guys can steer me in the right direction.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <string.h>
#define SIZE 10
//displays the main menu
void DisplayMenu(); //Prototype
//display user guesses
void DisplayGuesses(int, int);
void main()
{
char selection;//menu selection
int randomNumber;//random number that user has to guess
int guess;//answer
int answers[SIZE];
int CorrectGuess = 0;
int GameOver = 0;
int n;
int count = 10;
while(!GameOver)
{
DisplayMenu(); //Function Call
scanf("%c", &selection);//gets the user input
if (selection == 'A' || selection == 'a')
{
system("cls");//clears screen
srand(time(NULL));//passes a time function to seed
randomNumber = rand() % 100;//creates random number between 0 and 100
for(n = 0; n<SIZE; n++)
{
printf("Please enter your guess: ");//prints the prompt
scanf("%d", &guess);//gets the user input
answers[n] = guess;
//checks to see if the answer is lower than the random number
if (answers[n] < randomNumber)
{
printf("\n\nMy number is higher than your guess, try again\n\n");//prints the result
}
//checks to see if the answer is greater than the random number
else if (answers[n] > randomNumber)
{
printf("\n\nMy number is lower than yours, try again\n\n");//prints the result
}
else
{
printf("\nCorrect!!! It only took you %d tries\n\n", n + 1);//prints the result
DisplayGuesses(answers, n);
CorrectGuess = 1;
break;
}
}
//if count is 10 and wrong guess, display message.
if (count == 10 && !CorrectGuess)
{
printf("You lose. The number was %d\n\n", randomNumber); //displays the random number
DisplayGuesses(answers, n);
}
}
else if (selection == 'B' || selection == 'b')
{
printf("\n\nGoodbye\n\n");
GameOver = 1;
}
getchar();
//memset(answers,0,sizeof(answers));
}
}
void DisplayMenu() //Function Header
{
printf("\n\nA: Start Game\n\n");
printf("B: Quit Game\n\n");
}
//Displays user guesses
void DisplayGuesses(int guesses[], int tries)
{
int i;
printf("Your guesses were:\n\n");
for(i = 0; i < tries; i++)
{
printf("%d\n", guesses[i]);
}
}
Btw, im following the pseudocode that was provided to me in class
Dont be too harsh on me! :D