In: Computer Science
Write a C program that asks the user to guess a number between 1 and 15(1 and 15 are included). The user is given three trials.
This is what I have so far.
/*
Nick Chioma
COP 3223 - HW_2
*/
#include <iostream>
#include <time.h> // needed for time function
#include <stdlib.h> // needed for srand, rand functions
int main () {
int numbertoguess, num, correct, attempts;
srand(time(NULL)); //this initializes the random seed,
making a new one every time
numbertoguess = rand() % 15 + 1; //generates a number
between 1 and 15
//Guessing game begins
printf("Welcome to the guess-a-number game!\n");
printf("I'm thinking of a number between 1 and 15.
What is it? : ");
correct = 0;
attempts = 0;
while (attempts <= 3) {
scanf("%d", &num);
if (num > numbertoguess) {
attempts++;
printf("No, try something lower :
");
}
else if (num < numbertoguess); {
attempts++;
printf("No, try something higer:
");
}
if (attempts == 3); {
printf("Sorry, you failed!");
}
if (num == numbertoguess) {
printf("That was %d!",
numbertoguess);
correct = 1;
}
}
return 0;
}
My problem is:
1) The program does not actually end after 3 tries
2) If you do guess the correct answer the program does not stop looping and I am not sure why.
3) I also have been getting a weird "[Error] Id returned 1 exit status
If anyone could give me some insight that would be amazing, thank you.
Please find the updated program.. Let me know if you need any further assistance...
C Program:
/*
Nick Chioma
COP 3223 - HW_2
*/
#include <stdio.h>
#include <time.h> // needed for time function
#include <stdlib.h> // needed for srand, rand functions
int main () {
int numbertoguess, num, correct, attempts;
srand(time(NULL)); //this initializes the random
seed, making a new one every time
numbertoguess = rand() % 15 + 1; //generates a number
between 1 and 15
//Guessing game begins
printf("Welcome to the guess-a-number game!\n");
printf("I'm thinking of a number between 1 and 15.
What is it? : ");
correct = 0;
attempts = 0;
while (attempts < 3 && correct==0)
{
scanf("%d", &num);
if (num > numbertoguess)
{
attempts++;
if (attempts ==
3) {
printf("Sorry, you failed!");
correct = 1;
}
else {
printf("No, try something lower: ");
}
}
else if (num < numbertoguess)
{
attempts++;
if (attempts ==
3) {
printf("Sorry, you failed!");
correct = 1;
}
else {
printf("No, try something higher: ");
}
}
else if (num == numbertoguess)
{
printf("That was
%d!", numbertoguess);
correct =
1;
}
}
return 0;
}
Sample Run: