program using the rand () function - c

I want to make a simple program in which the rand() function generates a random number out of 1,2,3 and the user is asked to predict the number. if the user predicts the number correctly then he wins otherwise he looses.
Here's the program-
#include <stdio.h>
#include <stdlib.h>
int main()
{
int game;
int i;
int x;
printf("enter the expected value(0,1,2)");
scanf("%d\n",&x);
for(i=0;i<1;i++){
game=(rand()%2) + 1
if(x==game){
printf("you win!");
}
else{
printf("you loose!");
}
} return 0;
}

Some issues with your code:
Point 1:
scanf("%d\n",&x);
should be
scanf("%d",&x);
Point 2:
for(i=0;i<1;i++)
this for loop is practically useless. It only iterates one. either use a longer counter, or get rid of the loop.
Point 3:
It's better to provide a unique seed to your PRNG. You may want to use srand() and time(NULL) in your function to provide that seed.
Point 4:
game=(rand()%2) + 1
should be
game = rand() % 3; // the ; maybe a typo in your case
^
|
%3 generates either of (0,1,2)
Point 5:
When you use % with rand(), be aware of modulo bias issue.
Note:
The recommended signature of main() is int main(void).
Always initialize your local variables. Good practice.

Remove \n from your scanf()
scanf("%d\n",&x); to
scanf("%d",&x);
and place a semicolon(;) after game=(rand()%2) + 1;
it works.
Your for loop is not required here.

You didn't ask any question but I guess it is "Why my rand() function doesn't work?"
You need to add these lines
#include <time.h>
and the random initialization at the beginning of the main function:
srand(time(NULL));
Which should give:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int game;
int i;
int x;
printf("enter the expected value(0,1,2)");
scanf("%d",&x);
for(i=0;i<1;i++){
game=(rand()%2) + 1;
if(x==game){
printf("you win!");
}
else{
printf("you loose!");
}
} return 0;
}
Edit: there are other problems as Sourav said

Related

How to quit loop when requirement is met in C

I have made a while loop and it works partly. I want the code to stop when the values entered are under the parameter, but it keeps going regardless of the output. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>
int main()
{
// defining variables until "till here" comment
int i;
int rollDice;
int firInp;
int secInp;
srand (time(NULL)); // seeding rand so that we get different values every time
// till here
while(rollDice > 0)
{
printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=1): "); // prints the message
scanf("%d", &firInp); // user input stored into firInp
printf("Enter the amount of throws you want(MAX=499, MIN=1): "); // this message is printed after the users first input
scanf("%d", &secInp); // user input stored into secInp
if (((firInp < 25)&&(firInp > 1))&&((secInp < 500)&&(secInp > 1))){ // if statement to check parameters
for(i = 0; i < secInp; i++){
rollDice = (rand()%firInp) + 1;
printf("%d \n", rollDice);
}
}
else{
printf("Sorry, these numbers don't meet the parameters\nPlease enter a number in the right parameters.\n");
}
}
return 0;
}
I'm new to C btw.
edit: I want the loop to continue if the user input is more than 24, 499 respectively.
What you're doing is wrong. Variable rollDice is for storing the values of the outcomes rather than doing a condition check. It will have random values and since the values on the dice can't be negative or zero it may not exit the while loop. I don't know what will rand() will produce so I'm just assuming.
The range for rand() is [0,RAND_MAX), including zero and excluding RAND_MAX. But because of this expression (rand()%firInp) + 1 , you're adding one to it. So it will never become Zero.
You can use a flag variable and set it to 1. When the if conditions are met, you can set the flag to 0. It will exit the while loop.
Corrected code :-
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>
int main()
{
// defining variables until "till here" comment
int i;
int rollDice;
int firInp;
int secInp;
int flag = 1;
srand (time(NULL)); // seeding rand so that we get different values every time
// till here
while(flag)
{
printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=1): "); // prints the message
scanf("%d", &firInp); // user input stored into firInp
printf("Enter the amount of throws you want(MAX=499, MIN=1): "); // this message is printed after the users first input
scanf("%d", &secInp); // user input stored into secInp
if (((firInp < 25)&&(firInp > 1))&&((secInp < 500)&&(secInp > 1))){ // if statement to check parameters
for(i = 0; i < secInp; i++){
rollDice = ((rand() + 1)%firInp);
printf("%d \n", rollDice);
}
flag = 0;
}
else{
printf("Sorry, these numbers don't meet the parameters\nPlease enter a number in the right parameters.\n");
}
}
return 0;
}
EDIT :-
Also, division with 0 is undefined. rand() can attain value 0. You should add 1 to rand() rather than adding to whole modulus. It can create an error if the rand() will give 0 as an output.

find sum of infinite series.Why does it issue a zero amount?

You need to find the sums of an infinite series with a given accuracy.(the picture with the task is given as a link)
the program constantly counts the zero amount. I don't understand what my mistake is
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int i;
int n =1;
double E,x,q;
double sum = 0;
scanf ("%f",&E) ;
scanf ("%f",&x) ;
q=pow(x,3)/6;
while(fabs(q)>=E){
if (n/2==0) {
sum=sum+q;
}
else {
sum=sum-q;
}
q=(q*pow(x,2))/(n+3);
n=n+1;
}
printf("%f",sum);
return 0;
}
It will never going to enter to that if statement. You are letting n=1 and it will be always 1, and u are doing n=n+1 in the else.

Checking for a prime number through user input in a given range in C

#include <stdio.h>
#include <stdlib.h>
int main()
{
int n=0;
int x;
printf("Please enter a number:");
scanf("%d", &n);
(x<=1)&&(x>=1000)&&(x=(!(n)));
if((n/1)&&(n/n)&&(!(n/x)))
{
printf("P\n");
}
else
{
printf("C\n");
}
system("pause");
return 0;
}
My code keeps outputting "P" from the if statement when run, can anyone explain why? Is there a way to make the code work with just if and else functions? If so please help
I believe the intent of this if((n/1)&&(n/n)&&(!(n/x))) statement is saying "if n is divisible by one and if n is divisible by n and if n is not divisible by x" however this is not how we express these ideas in C. Look at the % or modulo operator and see if you can figure out how we can express these ideas using logic

Random number generator game in C

I have started C recently and am having trouble make the computer think of a random number.
This is the code so far. I need help!
#include <stdio.h>
#include <stdlib.h>
int main ()
{
time_t t;
int userin;
printf("Guess a number from 1 to 10\n");
scanf("%d", userin);
int r = rand() % 11;
if (r == userin)
{
printf ("you are right");
}
else
{
printf("Try again");
}
return 0;
}
Thx a lot guys it worked out!!!!
In your code, r will be a random number from 0 to 10. For a random number between 1 and 10, do this:
int r = rand() % 10 + 1;
Also, you should call
srand(time(NULL));
at the beginning of main to seed the random number generator. If you don't seed the generator, it always generates the same sequence.
There is issue in your scanf statement as well.
You should use
scanf("%d", &userin);
instead of
scanf("%d", userin); /* wrong - you need to use &userin */
scanf needs the address of variables at which it will store the value. For a variable, this is given by the prefexing the variable with &, as in &userin.
There are few issues in your code.
not reading into the address & of your variable using scanf
not considering "legitimate" values of input, result of rand()%11 can also be 0
not checking against "illegal" input values, which can "alias" the result.
not properly initializing seed of the pseudo-random rand() function, so it always returns the same result.
Using printf for debugging your code, as in the following example, based on your code can help a lot:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DEBG 1
int main (void)
{
time_t t;
int userin;
printf("Guess a number from 1 to 10\n");
if(scanf("%d", &userin) != 1){ // read into the variable's address
printf("Conversion failure or EOF\n");
return 1;
}
if(userin < 1 || userin > 10){ // check against "illegal" input
printf("Offscale, try again\n");
return 1;
}
srand(time(NULL)); // initialize the seed value
int r = 1 + rand() % 10; // revise the formula
if (DEBG) printf("%d\t%d\t", r, userin); //debug print
if (r==userin){
printf ("you are right\n");
}else{
printf("Try again\n");
}
return 0;
}
Please, also consult this SO post.
Problems :
scanf("%d", userin); //you are sending variable
This is not right as you need to send address of the variable as argument to the scanf() not the variable
so instead change it to :
scanf("%d", &userin); //ypu need to send the address instead
and rand()%11 would produce any number from 0 to 10 but not from 1 to 10
as other answer suggests, use :
(rand()%10)+1 //to produce number from 1 to 10
Solution :
And also include time.h function to use srand(time(NULL));
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int userin;
printf("Guess a number from 1 to 10\n");
scanf("%d", &userin);
int r = (rand() % 10)+1;
if (r==userin)
{
printf ("you are right");
}
else
{
printf("Try again");
}
return 0;
}
Why use srand(time(NULL)) ?
rand() isn't random at all, it's just a function which produces a sequence of numbers which are superficially random and repeat themselves over a period.
The only thing you can change is the seed, which changes your start position in the sequence.
and, srand(time(NULL)) is used for this very reason
This should work
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int userIn = 0; //I like to initialize
printf("Guess a number from 1 to 10\n");
scanf("%d", &userIn);
srand(time(NULL)); //seed your randum number with # of seconds since the Linux Epoch
int r = (rand()%10)+1; //rand%11 gives values 0-10 not 1-10. rand%10 gives 0-9, +1 makes sure it's 1-10
if (r == userIn)
{
printf ("you are right\n");
}
else
{
printf("Try again\n");
}
return 0;
}
Edit: You may want to implement code to verify that the user input is in fact an integer.

Simple C Program Math Quiz

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;

Resources