So in my code you have to guess a number if you under or overestimate. How do I get the while loop to loop back to the input so you can input another number?
#include <stdio.h>
int main(int argc, const char * argv[])
{
int number = 45;
printf("Please insert a number");
scanf("%d", &number);
if (number == 45){
printf("good job! You got the number right.");
return 0;
}
else if (number < 45){
while (number < 45 || number > 45){
printf("Your number is too low");
return 1;
}
}
else if (number > 45){
printf("Your number is too high!");
return 1;
}
}
Just put a while (1) around your code and remove the one wrongly placed :
#include <stdio.h>
int main(int argc, const char * argv[])
{
while (1) {
int number = 45;
printf("Please insert a number");
scanf("%d", &number);
if (number == 45){
printf("good job! You got the number right.");
return 0;
}
else if (number < 45){
printf("Your number is too low");
}
else{
printf("Your number is too high!");
}
}
}
return is closing the program. So you don't want to return when the user hasn't guessed your number.
while (1) is the loop which will only exit when return 0 is launched (when the player has won).
Also, your last else if is not needed. Replace it by a else, because it is the only remaining case.
Wrap your code with a loop:
int number = 45;
while (1) {
printf("Please insert a number");
if (scanf("%d", &number) != 1) {
printf("not valid number, try again");
continue;
}
if (number == 45){
printf("good job! You got the number right.");
return 0;
}
if (number < 45){
printf("Your number is too low");
continue;
}
if (number > 45){
printf("Your number is too high!");
continue;
}
}
Note that you should also check the return value of scanf to find out whether the number has been successfully read.
Related
I wrote up a piece of code to find whether a number is prime or not and here it is.
#include <stdio.h>
void main() {
int i, n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 3) {
printf("It is a prime number");
}
for (i = 2; i < n; i++) {
if (n % i == 0) {
printf("It's not prime number \n");
break;
} else {
printf("It is a prime number \n");
break;
}
}
}
However, when my input is 33, instead of the output printing It's not a prime number, since 33 is divisible by 3 and 11, it prints that It is a prime number.
What is the problem with my code here?
In your code, the first time the for loop is executed it immediately triggers either the if condition or else, then breaks, reaches the end and returns. The loop runs a total of 1 iteration max. Change to the following:
for (i = 2; i <= n / i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
Here the for runs correctly. It checks for all dividends, only then it's over and prints the false condition. Note you can optimize your code and only check up to the square root of n, because after that it can't hit true.
And add a return statement here, because the program is already over and doesn't need to continue:
if (n <= 1){
printf("It's not a prime number");
return 0;
}
if (n <= 3){
printf("It is a prime number");
return 0;
}
This also screens off 0, 1, and negative integers which are not prime numbers.
You almost got it right: you just have to make sure the program exits after having established whether a number is prime.
Also, you can stop the loop at n/i.
Last, but not least: main should return a int.
#include <stdio.h>
int main(void){
int i,n;
printf("Enter value for n: \n");
scanf("%d", &n);
if (n <= 3){
printf("It is a prime number\n");
return 0;
}
for (i = 2; i < n/i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
return 0;
}
There are multiple problems:
void main() should be int main()
you should check the return value of scanf and reject negative numbers
0 and 1 are not considered prime numbers.
you should end the program if the number matches the first test.
you output the result after a single test: it is correct if the test if (n % i == 0) is true as you have found a divisor, but if you have not, you should iterate, testing all possible divisors up to and including floor(sqrt(n)).
Here is a modified version:
#include <stdio.h>
int main() {
int i, n;
printf("Enter value for n: ");
if (scanf("%d", &n) != 1) {
printf("input error, not a number\n");
return 1;
}
if (n < 0) {
printf("number should be positive: %d\n", n);
return 1;
}
if (n <= 1) {
printf("%d is not a prime number\n", n);
return 0;
}
for (i = 2; i < n / i; i++) {
if (n % i == 0) {
printf("%d not prime number (divisible by %d)\n", n, i);
return 0;
}
}
printf("%d is a prime number\n", n);
return 0;
}
You might want to try this:
#include <bits/stdc++.h>
int main(){
int i,n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 1){
printf("It is a prime number");
}
for (i = 2; i <= sqrt(n); i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("A prime Number");
return 0;
}
This is happening because in your code for i = 3 and n = 33, if condition is failing which leads to else block directly and hence you are getting output as "It is a prime number".
I am trying to get the program to allow the user to input a number and then have the computer tell the user if the number is too small, too big, or equal to a randomly generated number. The prompt and input work, but it gets stuck after the first scanf.
I think it has to do with scanf and not the conditionals, because I added printf("Testing stopping point") and that doesn't get printed to the user's screen. What am I doing wrong?
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <stdlib.h>
int main()
{
//Generate a random number
int n = 1;
int count = 0;
int randomNumber;
srand(time(NULL));
for (int i = 1; i <= n; i++)
{
randomNumber = rand() % 101;
}
printf("Guess a number between 1 - 100: ");
int input;
scanf("%d\n",&input);
printf("Testing stopping point");
do
{
if (input > randomNumber)
{
count +=1;
printf("Too large!Try again: ");
getchar();
}else if (input < randomNumber)
{
count += 1;
printf("Too small!Try again: ");
getchar();
}
}while (input != randomNumber);
if(input == randomNumber)
{
count +=1;
printf("Correct!\n");
printf("You guessed %d times\n", count);
return 0;
}
}
You have to remove the \n in the scanf,try like this:
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <stdlib.h>
int main()
{
//Generate a random number
int count = 0;
int randomNumber;
srand(time(NULL));
randomNumber = (rand() % 101)+1;
int input=-1;
while (input != randomNumber)
{
printf("Guess a number between 1 - 100: ");
scanf("%d",&input);
if (input > randomNumber)
{
count +=1;
printf("Too large!Try again: ");
}else if (input < randomNumber)
{
count += 1;
printf("Too small!Try again: ");
}
}
if(input == randomNumber)
{
count +=1;
printf("Correct!\n");
printf("You guessed %d times\n", count);
}
return 0;
}
i'm new to C - I have intended to make a program that shows whether the user input int is odd or even, until the user decides to quit by inputing a char 'x'. The loop kind of works by detecting odd numbers and terminating the program with 'x', however glitches with even numbers - why is that so? Would appreciate it if you could point out the flaws in the code. Thank you
#include <stdio.h>
int main(void)
{
int i=0;
char x = "x";
printf("Enter an integer to check whether your number is odd or even\n");
printf("Enter an ´x´ at any time to quit the program\n");
do
{
scanf("%d", &i);
if (i % 2 == 0)
{
printf("The number is even\n");
}
else if (i % 2 != 0)
{
printf("The number is odd\n");
}
else("%c ", &x);
{
scanf(" %c", &x);
getchar();
printf("The program will now terminate\n");
return 0;
}
}
while (i > 0);
i++;
return 0;
}
Very close but I've marked a couple of changes:
#include <stdio.h>
int main(void)
{
int i=0;
char x = 'x'; // Note: single quotes for char, double for string
printf("Enter an integer to check whether your number is odd or even\n");
printf("Enter an ´x´ at any time to quit the program\n");
do
{
int n = scanf("%d", &i); // Check if number was read
if (n == 1) {
if (i % 2 == 0)
{
printf("The number is even\n");
}
else // Only other possibility
{
printf("The number is odd\n");
}
} else // No number, see if there's an 'x'
{
scanf(" %c", &x);
if (x == 'x')
{
printf("The program will now terminate\n");
return 0;
} else
{
printf("Unknown input %c\n", x);
}
}
}
while (i > 0); // Will also end if user enters <= 0
return 0;
}
I got my program to fully work, all except I need the program to stop asking after 5 failed attempts. I have absolutely no idea how to go about that. What it is suppose to do, if the number entered is incorrect 5 times in a row, there would then be a sorry message at the end. I can't figure out how to insert the counter into the code, I know what I put in is probably nowhere near correct.
P.S. The code has to have multiple functions. Some I'd rather put into one myself but instruction say multiple.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int number;
void welcomeMessage(){
printf("Welcome to my new guessing game!\n");
printf("Let's get started!\n");
}
int randomNumber(int number){
int range;
srand(time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return number;
}
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 5 tries!: ");
scanf("%d", &guess);
return guess;
}
int guess_input(){
int guess;
scanf("%d", &guess);
return guess;
}
int wrongAnswer(int guess){
if(guess < number)
{
printf("Try again, your guess is too low: ");
return 1;
} else if(guess > number) {
printf("Give it another try, your guess was a bit too high: ");
return 1;
}
return 0;
}
int correctAnswer(int guess){
if(guess == number){
printf("Great job! That time you got it right!\n");
return 0;
} else{
return 1;
}
}
void sorryMessage(int number){
printf("Sorry, the correct number was %number.\n");
printf("Better luck next time!");
}
int main(){
int number;
int loopCount = 5
int guess;
int correct_answer = 1;
int wrong_answer = 1;
welcomeMessage();
number = randomNumber();
guessInput();
do {
correct_answer = correctAnswer(guess);
wrong_answer = wrongAnswer(guess);
guess = guess_input();
}
while(correct_answer == 1);
if(loopcount = 5){
sorryMessage
}
return 0;
}
I have made minimal changes to your program to get it to compile and run as expected.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int number;
void welcomeMessage(){
printf("Welcome to my new guessing game!\n");
printf("Let's get started!\n");
}
int randomNumber(){
int range;
srand((int)time(NULL));
range = (20 - 1) + 1;
number = rand() % range + 1;
return number;
}
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 5 tries!: ");
scanf("%d", &guess);
return guess;
}
int guess_input(){
int guess;
scanf("%d", &guess);
return guess;
}
int wrongAnswer(int guess){
if(guess < number)
{
printf("Try again, your guess is too low: ");
return 1;
}
else if(guess > number)
{
printf("Give it another try, your guess was a bit too high: ");
return 1;
}
return 0;
}
int correctAnswer(int guess){
if(guess == number){
printf("Great job! That time you got it right!\n");
return 1;
} else{
return 0;
}
}
void sorryMessage(int number){
printf("Sorry, the correct number was %d\n",number);
printf("Better luck next time!");
}
int main(){
int number;
int loopCount = 0;
int guess;
int correct_answer;
int wrong_answer;
welcomeMessage();
number = randomNumber();
do
{
loopCount += 1;
if( loopCount > 5)
{
sorryMessage(number);
break;
}
guess = guessInput();
correct_answer = correctAnswer(guess);
wrong_answer = wrongAnswer(guess);
} while( !correct_answer );
return 0;
}
I have a two player guess random number game; player number (1 0r 2) with turn is randomly generated as the game begins and it's prompted to enter the player number. If the player number entered does not match the random player number then it should print "You have to wait your turn" and return to the enter Player number prompt. My program goes directly to the randome number that is to be guessed by the player instead of going back to asking for player number first and then moving onto asking for entering the random number that's to be guessed by player with his/her turn. How do I get it to go back to asking for the correct player number before moving forward.
Also one correct player number is entered; each player can choose to pass by entering "PASS" twice consecutively and thrice throughout the life of the game. How do I make these conditions work in the game. Thanks in advance to all.
Here is the code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <malloc.h>
int main(void) {
int player_num = 0; int number = 0; int player_input = 0;
int guess = 0; char input; char str[6] = {0}; int Player_1 = 1;
int Player_2 = 2; int Pass_1 = 3; int Pass_2 = 3; int i = 1;
int player_turn = 0; int turn = 0;
srand(time(NULL)); player_num = 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", player_num);
printf("Player Number?\n");
scanf("%d", &player_input);
while (player_num != player_input) {
printf("You Have to wait your turn.\nPlayer number?\n");
}
if (Player_1 != player_num)
Player_2 = player_num;
if (i%2 == 1) {
player_num = Player_1;
} else {
player_num = Player_2;
}
i = i+1;
printf("Enter Your Guess, 0 - 100 or Pass: ");
scanf("%s", str);
if (strcmp(str, "pass") == 0){
if (player_num == Player_1){
Pass_2 = Pass_2 -1;
printf("Player 2 has %d more 'Pass' left!\n", Pass_2);
}
else {
Pass_1 = Pass_1 -1;
printf("Player 1 has %d more 'Pass' left!\n", Pass_1);
}
} else {
guess = atoi(str);
if(guess < number) /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
else if(guess > number) /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
else /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}
return 0;
}
First, srand needs to be invoked only once and at the start of the program.
Second, scanf was moved inside the second while loop to force user to enter the correct player number or keep asking until he/she gets it right.
The following code fixes all of the above. Please read the comments in the code to see the reasons for the changes:
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
int main(void) {
int player_num = 0; int number = 0; int player_input = 0;
int guess = 0; char input; char str[15] = {0}; // size was increased to compensate for pass pass input
int Player_1 = 1;
int Player_2 = 2; int Pass_1 = 3; int Pass_2 = 3; int i = 1;
int player_turn = 0; int turn = 0; int alternate=0;
int player1Flag=0,player2Flag=0;
int lastPlayer=0;
srand(time(NULL));
player_num = 1 + rand() % 2; /* Random number is generated */
lastPlayer = player_num;
number = 0 + rand() % 100; /* Random number is generated */
while(number != guess) {
while (player_num != player_input) {
printf("\nIt's player's %d turn\n", player_num);
printf("Player Number?\n");
scanf("%d", &player_input);
getchar();// to get rid of \n after the input
if(player_input!=player_num){
printf("You Have to wait your turn.\n");
}
}
if (Player_1 != player_num) Player_2 = player_num;
printf("Enter Your Guess, 0 - 100 or Pass: ");
scanf("%s",str);
if (strcmp(str, "pass") == 0){
if (player_num == Player_1){
player1Flag = player1Flag+1; // flag to detect if last input was a pass
if(player1Flag>1){
printf("Dude you passed in your last attempt .. dont be a pus*y\nEnter a guess : ");
scanf("%s",&str);
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
player1Flag = 0; // reset the pass flag = 1 as this pass isn't counted
}else{
Pass_2 = Pass_2 -1;
if(Pass_2<0){
printf("You have already passed Thrice\nEnter a guess: ");
scanf("%s",&str);
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}else{
printf("Player 1 has %d more 'Pass' left!\n", Pass_2);
}
}
}
else{
player2Flag = player2Flag + 1;
if(player2Flag>1){
printf("Dude you passed in your last attempt .. dont be a pus*y\nEnter a guess : ");
scanf("%s",&str);
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
player2Flag=0;// reset the player2Flag = 1 as this pass isn't counted
}else{
Pass_1 = Pass_1 -1;
if(Pass_2<0){
printf("You have already passed Thrice\nEnter a guess: ");
scanf("%s",&str);
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}else{
printf("Player 2 has %d more 'Pass' left!\n", Pass_2);
}
}
}
}else {
if (player_num == Player_1){
player1Flag = 0;//reset pass flag as this player enetered a guess
}else{
player2Flag = 0;
}
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}
if(lastPlayer==1){
player_num = 2;
lastPlayer = 2;
}else if(lastPlayer==2){
player_num = 1;
lastPlayer = 1;
}
}
return 0;
}
You need to add an input within your while. In other words, instead of:
while (player_num != player_input) {
printf("You Have to wait your turn.\nPlayer number?\n");
}
try this:
while (player_num != player_input) {
printf("You Have to wait your turn.\nPlayer number?\n");
scanf("%d", &player_input);
}