I've been at this project for hours and hours trying to figure this out but I'm to the point of brain dead where everything I read leaves me confused.
The idea is to enter a number and the program will tell me whether it is right or wrong. Every single time, the end response after I enter a number is that the number is too low.
Also, the final answer states that the answer is too low and that it's correct at the same time.
Finally, this thing is suppose to ask again if the number entered is incorrect, yet I have no knowledge of how to do this.
Literally, the tiniest advice is much appreciated at this point. It's been a long, groaning night.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int number;
//new function
void welcomeMessage(){
printf("Welcome to my new guessing game!\n");
printf("Let's get started!\n");
}
//new function
int randomNumber(){
int range;
srand(time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return 0;
}
//new function
int guessInput(){
int guess, range;
printf("I'm thinking of a number between 1 and 20\n");
printf("Care to give it a guess? Be careful! You only get 4 tries!\n");
scanf("%d", &guess);
return 0;
}
//new function
int wrongAnswer(){
int guess, number;
if(guess < number)
{
printf("Try again, your guess is too low\n");
return 0;
}
else if(guess > number)
{
printf("Give it another try, your guess was a bit to high\n");
return 0;
}
return 0;
}
//new function
int correctAnswer(){
int guess, number;
if(guess == number)
printf("Great job! That time you got it right!\n");
return 0;
}
int main(){
welcomeMessage();
randomNumber();
guessInput();
wrongAnswer();
correctAnswer();
}
You're not actually passing the value of guess to wrongAnswer() or correctAnswer(). guess in those two functions is uninitialized and doesn't contain the value stored in guessInput(). This is why wrongAnswer tells you that the guess is too low and correctAnswer tells you that it's correct.
You'll also want to remove the number declaration within those functions. You have a global number right now that stores the random number, but the new number variable declared within your functions will take precedence -- it's uninitialized and doesn't contain the random number like you think it does.
You may want to adjust your wrongAnswer() and correctAnswer() functions to take guess as an integer argument, and remove the guess and number declarations within those two functions. Something like
int wrongAnswer(int guess);
int correctAnswer(int guess);
You may also want to consider having your guessInput() function return the value of guess. Try something like
int guessInput()
{
int guess;
printf("I'm thinking of a number between 1 and 20\n");
printf("Care to give it a guess? Be careful! You only get 4 tries!\n");
scanf("%d", &guess);
return guess;
}
int main()
{
...
int guess = guessInput();
wrongAnswer(guess);
correctAnswer(guess);
...
}
This way you're passing the value of guess to your two functions so that they can actually evaluate whether the number is correct or incorrect.
You'll also want to look at the value of your return functions. Right now they aren't really telling you anything, and they return 0 regardless. Consider changing them to return 0 if the guess was correct and return 1 if the guess was incorrect.
int correctAnswer(int guess)
{
if(guess == number) {
printf("Great job! That time you got it right!\n");
return 0;
} else {
return 1;
}
}
With this information you can create a while loop to continually ask the user for input until they input the correct answer. Something like
int main()
{
...
int is_correct = 1, is_wrong = 1;
int guess;
while (is_correct == 1) {
guess = guess_input();
is_wrong = wrongAnswer(guess);
is_correct = correctAnswer(guess);
}
...
}
The while loop above will call each of the three functions, forever, until the user guesses the correct input. It evaluates is_correct == 1, constantly checking the value of is_correct, and repeating itself. When is_correct == 0 the loop will break and your program will terminate. This is where the return values I mentioned above come in -- a return value of 0 indicates a correct answer and will allow your program to stop. A return value of 1 will repeat the loop. There are other ways to do this, but it may help while you're starting out.
Hopefully this helps you out. I'd also consider redesigning your wrongAnswer() and correctAnswer() functions -- do you really need two? Could you reduce that to one function?
The Most basic issue that i see with the program is that you are not passing values to the functions. Each function is just working in itself and the value or should i say the 'number' it has to work with is not being passed into them.
You can use global variables or pass the values directly. This is what i would do:
The input function:
int guessInput(){
int guess, range;
printf("I'm thinking of a number between 1 and 20\n");
printf("Care to give it a guess? Be careful! You only get 4 tries!\n");
scanf("%d", &guess);
return guess;}
The Random Number Generator Function:
int randomNumber(){
int range;
srand(time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return number;}
The Answer Function: ( you really don't need 2 functions for this )
int Answer(int guess, int number){
int counter=0;
if(guess < number)
{
printf("Try again, your guess is too low\n");
counter=1;
}
else if(guess > number)
{
printf("Give it another try, your guess was a bit to high\n");
counter=1;
}
else if(guess == number)
{
printf("Great job! That time you got it right!\n");
counter=2;
}
return counter;}
Now that all your functions can accept variables, Modify the Main function
int main(){
int number=0;
int guess=0;
int answr=0; // This does not have to exist but since your doing a return.
welcomeMessage();
number=randomNumber();
guess=guessInput();
Do {
answr=Answer(guess,number);
}(while answr<2)
}
So when the counter reaches 2, which means that the answer is right, the while loop will stop when the correct answer is guessed by the user.
PS: You may need to polish my code a bit since im also in a brain dead mode atm. :D
Related
I'm trying to make an algorithm in C that asks you to input any number, and stops asking when you input the number 0. I'm supposed to do it with a while loop, but it doesn't work and I tried everything I've learned. This is my code that doesn't work:
#include<stdio.h>
int main()
{
int number;
while(number != 0)
{
printf("Introduce a number: ");
scanf("%i",&number);
}
return 0;
}
Hopefully it's not too late to bring my two cents to the party.
The solution which others suggest is definitely possible and working solution, however, I think it can be done in a slightly neater way. For cases like this, do while statement exists:
#include <stdio.h>
int main() {
int number; // Doesn't need to be initialized in this case
do {
printf("Introduce a number: ");
if (scanf("%i", &number) != 1) { // If the value couldn't be read, end the loop
number = 0;
}
} while (number != 0);
return 0;
}
The reason I think this solution is better is just that it doesn't bring any other magic constants to the code, hence it should be better readable.
If someone saw int number = 42;, for example, he'd be asking - Why 42? Why is the initial value 42? Is this value used somewhere? The answer is: No, it is not, thus it's not necessary to have it there.
You need to assign a number to number before using it in the condition.
You have two options: a) use a dummy initial value, or b) scanf before test
// a) dummy value
int number = 42;
while (number != 0) { /* ... */ }
or
// b) scanf before test
int number; // uninitialized
do {
if(scanf("%i", &number) != 1) exit(EXIT_FAILURE);
} while (number != 0);
int number = 1;
while(number != 0){
printf("Introduce a number: ");
scanf("%i",&number);
}
Scanf will pause loop and waiting for typing a number
Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}
Ok, so as a beginner programmer, I have been tasked with creating a simple math quiz program. It is supposed to prompt the user for how many questions to ask, congratulate or inform the user when their answer is either right or wrong. And then print out the number correct and the number incorrect at the end of the program. I have done all of this successfully, the only issue with my code now is that it asks the same questions over and over. I'm at a loss here so any help would be appreciated, thanks.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int i;
int response;
int correctAnswers = 0;
int incorrectAnswers = 0;
printf("\nMath Quiz\n");
printf("Please enter # of problems you would wish to try:");
scanf("%d", &response);
if(response == 0)
{
printf("\nThanks for playing!\n");
return 0;
}
for(i=0; i<response; i++)
{
int answer = 0;
int a = rand() % 12;
int b = rand() % 12;
printf("\n%d * %d = ",a ,b);
scanf("%d", &answer);
if((a * b) == answer){
printf("\nCongratulations You are correct!\n");
correctAnswers++;
}
else{
printf("Sorry you were incorrect!\n");
incorrectAnswers++;
}
}
printf("\n\nYour Results:\n\n\n");
printf("Number Incorrect: %d\n", incorrectAnswers);
printf("Number Correct: %d\n", correctAnswers);
if(correctAnswers > incorrectAnswers){
printf("You Passed!\nGood work!\n\n");
}
else{
printf("You did not pass!\nYou need more work!\n\n");
}
return 0;
}
Additionally, any critiques as far as formatting are more than welcome. Thanks!
You need to understand how the randon number generator works in C.
rand() generates only pseudorandom numbers. This means that every time you run your code you will get exactly the same sequence of numbers.
Use the srand function to generate random numbers based upon a source number. If you want one that changes often, use the system time.
srand(time(NULL));
Also include the header file time.h to use the time function.
Call that function before any calls to rand(). If you don't call srand() before a call to rand() in your program, it is as if srand(1) was called: the seed value will be 1 at every execution of the program and the generated sequence will be always the same.
Use this srand in your code, like this...
int a;
int b;
srand(time(0));
a = rand() % 12;
b = rand() % 12;
I have just started my Intro to Programming class (so please bear with me) and I am a bit stuck on one of the first assignments.
I am supposed to code a number guessing game to store a random number between 1 & 10 into a variable, prompt the user for a number, & notify if user guessed the same number or not.
I have been messing with it for some time now, and the code has changed quite a bit from what I started with. Currently, the program is saying "Congrats, you're a winner" no matter what I guess...
If anyone could just point me in the direction of what I am doing wrong, that would be great.
THE CODE HAS BEEN EDITED SINCE THE ORIGINAL POSTING OF QUESTION
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
int main()
{
//Declare Variables
int RandomNum;
int UserGuess;
//Initialize Variables
RandomNum=0;
srand ( (unsigned)time ( NULL ) );
char UserInput = 'a';
int a = UserInput;
//Generate RandomNum
RandomNum = (rand() % 10)+1;
//Prompt User for UserInput
printf("Guess the random number!\n");
printf("Enter your guess now!\n");
scanf("%d", &UserInput);
//Determine Outcome
if (UserInput == RandomNum)
printf("You're a WINNER!\n");
else
printf("Incorrect! The number was %d\n", RandomNum);
//Stay Open
system("PAUSE");
}
Change this line -
if (UserGuess = RandomNum)
to this -
if (UserInput == RandomNum)
The first one assigns the user input stored in RandomNum into UserGuess, which is then converted to either true or false implicitly, and then the truth value of the if condition is checked by the compiler. I am assuming that you are entering non-zero value as your program input. If this is the case, then C will consider it as true. In fact, any non-zero value (whether positive, negative or fractional) is considered to be true by C.
The second expression checks for equality of two variables, rather than assigning one to another. So, you will get the desired behavior.
You are confusing = with ==
if (UserGuess = RandomNum) will not give the boolean result which you want to check that whether the guess is equal to random no generated..
Use
if (UserGuess == RandomNum)
Your if is incorrect. == is equality, = is assignment.
Change the type of UserInput, remove UserGuess and the spurious call to atoi(), and it'll work:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
//Declare Variables
int RandomNum;
int UserInput; // Changed to int
//Initialize Variables
RandomNum = 0;
UserInput = 0; // Changed initialization
srand((unsigned) time(NULL));
//Generate RandomNum
RandomNum = (rand() % 10) + 1;
//Prompt User for UserInput
printf("Guess the random number!\n");
printf("Enter your guess now!\n");
scanf("%d", &UserInput);
//Determine Outcome
if (UserInput == RandomNum)
printf("You're a WINNER!\n");
else
printf("Incorrect! The number was %d\n", RandomNum);
//Stay Open
system("PAUSE");
}
Are you sure that atoi() function takes an integer argument ?
because atoi() function is used to convert string to integer.
Read this article.
Can someone please help me figure out what is wrong with my program it is prety complex for me. It is a number guessing game where two player can play. It starts by saying which player goes first and the player then has to input his number either 1 or 2 and then enter a guess or either pass (players can't pass more than 3 times or twice in a row). It is working very good except that everytime player 1 starts it asks him for a guess twice in a row bu then works fine, and when player 2 starts it alternates like it should like this:
And this is my code It quite a lot of code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <malloc.h>
int main(void) {
int playerNumber = 0;
int number = 0;
int playerInput = 0;
int guess = 0;
char input;
char str[6] = {0};
int playerA = 1;
int playerB = 2;
int passA = 3;
int passB = 3;
int i = 1;
int playerTurn = 0;
int turn = 0;
srand(time(NULL));
playerNumber = 1 + rand() % 2; /* Random number is generated */
srand(time(NULL));
number = 0 + rand() % 100; /* Random number is generated */
while(number != guess) {
printf("\nIt's player's %d turn\n", playerNumber);
printf("Player Number?\n");
scanf("%d", &playerInput);
while (playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
if (playerA != playerNumber)
playerB = playerNumber;
if (i%2 == 1) {
playerNumber = playerA;
}
else {
playerNumber = playerB;
}
i = i+1;
printf("Enter Your Guess, 0 - 100 or Pass: ");
scanf("%s", str);
if (strcmp(str, "pass") == 0){
if (playerNumber == playerA){
passB = passB -1;
printf("Player 2 has %d more 'Pass' left!\n", passB);
}
else{
passA = passA -1;
printf("Player 1 has %d more 'Pass' left!\n", passA);
}
}
else {
guess = atoi(str);
if(guess < number) /* if the guess is lower, output: the guess is to low */
printf("Your guess was to low.\n ");
else if(guess > number) /* if the guess is higher, output: the guess is to high */
printf("Your guess was to high.\n ");
else /* is the guess is equial to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}
return 0;
}
First of all, you should use consistent indentation. That will make it easier to read your code.
Second, you should use newlines and whitespace to group like-lines together. Think of writing code like writing prose, and newlines as ways to separate paragraphs. You don't double-space almost anything, because it wastes space and is harder to read (people aren't used to it) so don't double-space your code.
Third, your use of the playerA and playerB variables is an OK concept, but there are better ways to do it. The typical convention in C/C++ is to use a #define for magic numbers, with all caps - #define PLAYER_A 1. Following this convention will make your code more readable. Also, since your players are "1" and "2" it is more readable to use #define PLAYER1 1 or PLAYER_1.
You use the variable "i" but the convention for using variables named i, j, k, m, or n is as loop counters that are incremented either at the top of the loop or at the bottom of the loop. Incrementing the loop counter in the middle of the loop makes it much easier for the counter to get lost. Move the increment to the top or the bottom.
Do the work by hand to see what your variables are as the program executes. Your teacher has done this in class. Just write down each variable and write its value next to it, then change the variables as they will change while the program executes. This technique will help you fix other difficult bugs in the future, rather than me giving you the answer.
You have an infinite loop in your code,
your code given below is wrong,
while(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
It should be,
if(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}