#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0));
int random = 0, guess, guesses = 1;
random = rand() % 100 + 1;
printf("The number has been generated. Input 0 to quit.\n");
do {
scanf("%d", &guess); //takes user input for guess
if (guess > random && guess != 0)
printf("Lower!\n");
else
if (guess < random && guess != 0)
printf("Higher!\n");
else
if (guess == random) {
printf("Bingo!");
return 0;
} else
if (guess == 0) {
printf("Thanks for playing, the number was %d\n", &random);
return 0;
}
guesses++;
} while (guesses != 6); //maximum of 5 guesses
printf("Thanks for playing, the number was %d\n", &random);
return 0;
}
Whenever I display the random variable when it has already generated a number a garbage value will be outputted. But the code snippet works of checking the comparison between the guess and the random number, I just can't seem to output the random number correctly.
%d in printf expects an argument of int data type. You are passing int * data type (&random).
Remove & before random in last two printfs.
printf("Thanks for playing, the number was %d\n", random);
You should pass the value of random instead of its address:
printf("Thanks for playing, the number was %d\n", random);
Note also that you should check the return value of scanf(): if you type a letter, the program will have undefined behavior, it may exit after iterating 5 times, or iterate forever or do something else entirely...
Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int random, guess, guesses;
srand(time(0));
random = rand() % 100 + 1;
printf("The number has been generated. Input 0 to quit.\n");
for (guesses = 0; guesses < 5; guesses++) {
// take user input for guess
if (scanf("%d", &guess) != 1 || guess == 0)
break;
if (guess > random) {
printf("Lower!\n");
} else
if (guess < random) {
printf("Higher!\n");
} else {
printf("Bingo!\n");
return 0;
}
}
printf("Thanks for playing, the number was %d\n", random);
return 0;
}
Related
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num, rnum, times = 1;
srand(4383);
rnum=rand() % 300 + 1;
while(times <=8)
{
printf("Guess the numper random number between 1-300: ");
scanf("%d", &num);
if (num<rnum)
{
printf("The random number is biger\n");
}
if (num>rnum)
{
printf("The magic number is smaller\n");
}
if (num == rnum)
{
printf("RIGHT!");
break;
}
times++;
}
printf("FAILURE!");
return 0;
}
The point of the task is to make a program for a user to type and try to guess a numper from 1–300 with 8 attempts. If you find the number it shows RIGHT! and if not it guides you by telling that the number is biger/smaller. If you fail in your 8 atemts then it shows failure. The problem is that it shows failure when you fail to guess in your 8 atempts but when you find the number it prints both RIGHT & FAILURE. What should i correct for the program to print failure only when you cant’t find the number within your 8 tries?
My 2 cents, path of least resistance is to simply return rather than break when the user guesses correctly:
if (num == rnum)
{
printf("RIGHT!");
return 0; // program exits here, no FAILURE print
}
You should also seed the rand function with a changing number, like time. With a constant, you'll find your number to guess is the same every time.
srand(time(NULL)); // randomize seed
You should check if they exceeding the 8 try limit before executing the print statement:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num, rnum, times = 1;
srand(4383);
rnum=rand() % 300 + 1;
while(times <=8)
{
printf("Guess the numper random number between 1-300: ");
scanf("%d", &num);
if (num<rnum)
{
printf("The random number is biger\n");
}
if (num>rnum)
{
printf("The magic number is smaller\n");
}
if (num == rnum)
{
printf("RIGHT!");
break;
}
times++;
}
if (times > 8)
{
printf("FAILURE!");
}
return 0;
}
I think you should write return 0; instead of break; after printing RIGHT. because if you guess the rnum it will print RIGHT and breaks out and after that it will print FAILURE too but if you write return 0; it will end the program.
When you break; out after having printed RIGHT! you end up where you print FAILURE! so you need to check this somehow.
Here's my take on it:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int num = 0, rnum;
// This game will get boring with a static seed.
// I'm assuming you use this seed for testing only.
srand(4383);
rnum = rand() % 300 + 1;
for(int times = 0; times < 8; ++times) { // simpler loop
printf("Guess the random number between 1-300: ");
// if the user fails to enter a number - make it print FAILURE
if(scanf("%d", &num) != 1) break;
if(num < rnum)
puts("The random number is bigger");
else if(num > rnum) // added "else"
puts("The magic number is smaller");
else
break; // neither less nor greater than rnum so it must be correct
}
if(num == rnum) // added check
printf("RIGHT!\n");
else
printf("FAILURE!\n");
}
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main() {
int num, result_odd, result_even, even_count, odd_count;
char name;
printf("What is your name?\n");
scanf("%s", &name);
while (num != 0) {
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 1) {
printf ("odd\n");
odd_count++;
} else
if (num == 0) {
printf("%s, the numbers you have entered are broken down as follows:\n",
name);
result_even = add_even(num);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(num);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
} else {
printf("even\n");
even_count++;
}
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 != 0) {
return 0;
}
sum += add_even(num);
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 == 0) {
return 0;
}
sum += add_odd(num);
return sum;
}
Can anyone give me some insight as to what I did wrong exactly?
The point of the code is to get inputs from the user until they decide to stop by inputting 0. Separating the evens from the odd. Tell them how many even/odd they put and the total of all the even/odd numbers.
I understand how to separate the evens from the odds. I think my issue is with my function.
There are multiple problems in your code:
scanf() causes undefined behavior when trying to store a string into a single character. Pass an array and specify a maximum length.
you should check the return value of scanf(): if scanf() fails to convert the input according to the specification, the values are unmodified, thus uninitialized, and undefined behavior ensues. In your case, if 2 or more words are typed at the prompt for the name, scanf("%d",...) fails because non numeric input is pending, no further characters are read from stdin and num is not set.
num is uninitialized in the first while (num != 0), causing undefined behavior.
functions add_even() and add_odd() are only called for num == 0, never summing anything.
functions add_even() and add_odd() should always return the sum and add the value of the argument num is it has the correct parity. They currently cause undefined behavior by calling themselves recursively indefinitely.
odd_count and even_count are uninitialized, so the counts would be indeterminate and reading their invokes undefined behavior.
In spite of all the sources of undefined behavior mentioned above, the reason your program keeps prompting without expecting an answer if probably that you type more than one word for the name. Only a single word is converted for %s, leaving the rest as input for numbers, which repeatedly fails in the loop. These failures go unnoticed as you do not verify the return value of scanf().
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
int add_even(int);
int add_odd(int);
int main(void) {
int num, result_odd, result_even, even_count = 0, odd_count = 0;
char name[100];
printf("What is your name? ");
if (scanf("%99[^\n]", name) != 1)
return 1;
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1 || num == 0)
break;
if (num % 2 == 1) {
printf("odd\n");
odd_count++;
add_odd(num);
} else {
printf("even\n");
even_count++;
add_even(num);
}
printf("%s, the numbers you have entered are broken down as follows:\n", name);
result_even = add_even(0);
printf("You entered %d even numbers with a total value of %d\n",
even_count, result_even);
result_odd = add_odd(0);
printf("You entered %d odd numbers with a total value of %d\n",
odd_count, result_odd);
}
return 0;
}
int add_even(int num) {
static int sum = 0;
if (num % 2 == 0) {
sum += num;
}
return sum;
}
int add_odd(int num) {
static int sum = 0;
if (num % 2 != 0) {
sum += num;
}
return sum;
}
You declared:
char name; // One single letter, such as 'A', or 'M'
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", &name); // Not enough space to store the response!
What you really want is more like
char name[31]; // Up to 30 letters, and an End-of-String marker
printf("What is your name?\n"); // Please enter a whole bunch of letters!
scanf("%s", name); // name is the location to put all those letters
// (but not more than 30!)
I'm self-studying C and I'm trying to make 2 programs for exercise:
the first one takes a number and check if it is even or odd;
This is what I came up with for the first one:
#include <stdio.h>
int main(){
int n;
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
return 0;
}
the second one should take n numbers as input and count the number of even numbers, odd numbers, and zeros among the numbers that were entered. The output should be the number of even numbers, odd numbers, and zeros.
I would like to ask how to implement the loop in this case: how can I set an EOF value if every integer is acceptable (and so I cannot, say, put 0 to end)? Can you show me how to efficiently build this short code?
#include <stdio.h>
int main(void) {
int n, nEven=0, nOdd=0, nZero=0;
for (;;) {
printf("\nEnter a number that you want to check: ");
//Pressing any non-numeric character will break;
if (scanf("%d", &n) != 1) break;
if (n == 0) {
nZero++;
}
else {
if (n % 2) {
nEven++;
}
else {
nOdd++;
}
}
}
printf("There were %d even, %d odd, and %d zero values.", nEven, nOdd, nZero);
return 0;
}
Check the return value of scanf()
1, 1 field was filled (n).
0, 0 fields filled, likely somehtlig like "abc" was entered for a number.
EOF, End-of-file encountered (or rarely IO error).
#include <stdio.h>
int main(void) {
int n;
for (;;) {
printf("Enter a number that you want to check: ");
if (scanf("%d",&n) != 1) break;
if((n%2)==0)
printf("%d is even.",n);
else
printf("%d is odd.",n);
}
return 0;
}
Or read the count of numbers to subsequently read:
int main(void) {
int n;
printf("Enter the count of numbers that you want to check: ");
if (scanf("%d",&n) != 1) Handle_Error();
while (n > 0) {
n--;
printf("Enter a number that you want to check: ");
int i;
if (scanf("%d",&i) != 1) break;
if((i%2)==0) {
if (i == 0) printf("%d is zero.\n",i);
else printf("%d is even and not 0.\n",i);
}
else
printf("%d is odd.\n",i);
}
return 0;
}
hey look at this
#include<stdio.h>
#include<conio.h>
void main()
{
int nodd,neven,num,digit ;
clrscr();
printf("Count number of odd and even digits in a given integer number ");
scanf("%d",&num);
nodd = neven =0; /* count of odd and even digits */
while (num> 0)
{
digit = num % 10; /* separate LS digit from number */
if (digit % 2 == 1)
nodd++;
else neven++;
num /= 10; /* remove LS digit from num */
}
printf("Odd digits : %d Even digits: %d\n", nodd, neven);
getch();
}
You can do something like this:
#include <stdio.h>
int main(){
int n,evenN=0,oddN=0,zeros=0;
char key;
do{
clrscr();
printf("Enter a number that you want to check: ");
scanf("%d",&n);
if(n==0){
printf("%d is zero.",n);
zeros++;
}
else if((n%2)==0){
printf("%d is even.",n);
evenN++;
}
else{
printf("%d is odd.",n);
oddN++;
}
puts("Press ENTER to enter another number. ESC to exit");
do{
key = getch();
}while(key!=13 || key!=27) //13 is the ascii code fore enter key, and 27 is for escape key
}while(key!=27)
clrscr();
printf("Total even numbers: %d",evenN);
printf("Total odd numbers: %d",oddN);
printf("Total odd numbers: %d",zeros);
return 0;
}
This program ask for a number, evaluate the number and then ask to continue for another number or exit.
I am practicing the basics of C programming using the book SAMS Teach yourself C in 21 days.
On one of the type and run sections, they have the find the number (or guess the number) program, I typed it and run it, however the program on the console gets stuck showing the following:
Getting a random number
I waited for some time but nothing happens, even pushing some keys it doesn't do anything.
I am not familiar yet with the srand(), time() and rand() routines so I don't know how to fix it and make it run properly.
below is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NO 0
#define YES 1
int main (void)
{
int guess_value = -1;
int number;
int nbr_of_guesses;
int done = NO;
printf("\nGetting a random number\n");
/*use the time to seed the random number generator*/
srand( (unsigned) time(NULL));
number = rand();
nbr_of_guesses = 0;
while (done == NO);
{
printf("\nPick a number between 0 and %d>", RAND_MAX);
scanf("%d", &guess_value); /*get a number*/
nbr_of_guesses++;
if (number == guess_value)
{
done = YES;
}
else
if (number < guess_value)
{
printf("\nYou guessed high!");
}
else
{
printf("\nYou guessed low!");
}
}
printf("\nCongratulations! you guessed right in %d Guesses!", nbr_of_guesses);
printf("\n\nThe number was %d", number);
return 0;
}
I can see 2 problems.
There is a semicolon on the while that's causing the program to hang.
There is nothing that ensures that the output buffer is flushed before you read the guess.
I have put comments to indicate the code changes.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NO 0
#define YES 1
int main (void)
{
int guess_value = -1;
int number;
int nbr_of_guesses;
int done = NO;
printf("\nGetting a random number\n");
/*use the time to seed the random number generator*/
srand( (unsigned) time(NULL));
number = rand();
nbr_of_guesses = 0;
while (done == NO) // Removed the ;
{
printf("\nPick a number between 0 and %d>", RAND_MAX);
fflush(stdout); // stdout is line buffered, and since there is no \n in the printf we need an explicit call to fflush,
scanf("%d", &guess_value); /*get a number*/
nbr_of_guesses++;
if (number == guess_value)
{
done = YES;
}
else
if (number < guess_value)
{
printf("\nYou guessed high!");
}
else
{
printf("\nYou guessed low!");
}
}
printf("\nCongratulations! you guessed right in %d Guesses!", nbr_of_guesses);
printf("\n\nThe number was %d", number);
return 0;
}
Hey guys take a look at this program.
/* The craps game, KN king page 218 */
#include <stdio.h>
#include <time.h>
#include <stdbool.h>
#include <stdlib.h>
int roll_dice(void);
bool play_game(void);
int roll_dice(void)
{
int roll;
getchar();
srand((unsigned) time(NULL));
roll = rand() % 13;
if(roll == 0)
roll = roll + 1;
return roll;
}
bool play_game()
{
int sum = 0, wins = 0, loss = 0, point;
sum = roll_dice();
printf("You rolled: %d", sum);
if(sum == 7 || sum == 11)
{
printf("\nYou won!\n");
return true;
}
if(sum == 2 || sum == 3 || sum == 12)
{
printf("\nYou lost!!");
return false;
}
point = sum;
printf("\n\nYour point is: %d", point);
do
{
sum = roll_dice();
printf("\nYou rolled: %d", sum);
}while(sum != point);
if(sum == point)
{
printf("\nYou won!!!");
return true;
}
}
int main()
{
char c, wins = 0, losses = 0;
bool check;
do
{
check = play_game();
if(check == true)
wins++;
else if(check == false)
losses++;
printf("\nPlay Again? ");
scanf("%c", &c);
}while(c == 'Y' || c == 'y');
printf("\nWins: %d Losses: %d", wins, losses);
return 0;
}
The srand function keeps returning, same value 3 or 4 times, y is that?
I want different values each time when i roll the dice, copy the code and run it to see what i mean
srand() is a function that sets the seed for the rand() function. What you are doing here is setting the seed to the current time before every rand() you call, which, if called fast enough, will get you the same value (since it will reset to the same seed, which if fast enough will be the same time value).
What you'll want to do is call srand() once, when the program starts (at the start of your main() function)
Then call rand() every time you want a random number, like you are doing currently, but without calling srand() every time.