I am learning how to use "rand()" and "srand()" in C. In the book that I am reading, it asks to modify a program that generates random numbers so that the user supplies a seed. This ensures the numbers are random. I am able to generate new numbers using the basic code directly below, but it will not work when I try to use it within the program beneath it.
int main()
{
int seed;
srand(seed);
printf("Please enter a seed: ");
scanf("%d", &seed);
printf("The random number is: %d\n", rand());
return (EXIT_SUCCESS);
}
Here is the program I am having trouble getting "srand() to work in below. I have tried asking the user for the seed in "main", rather than the prn_random_numbers function and everything else I could think of. It still only behaves like "rand()" and spits out the same number regardless of the seed that I enter. What am I doing wrong? Unfortunately, the book doesn't give any answers to the exercises. I greatly appreciate any help. I am just learning on my own.
max(x, y)
int x, y;
{
if (x > y)
return (x);
else
return (y);
}
min(x, y)
int x, y;
{
if (x < y)
return (x);
else
return (y);
}
prn_random_numbers(k) /* print k random numbers */
int k;
{
int i, r, smallest, biggest;
int seed;
srand(seed);
printf("Please enter a seed: ");
scanf("%d", &seed);
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 1; i < k; ++i)
{
if (i % 5 == 0)
printf("\n");
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main()
{
int n;
printf("Some random numbers are to be printed.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
while (n < 1)
{
printf("ERROR! Please enter a positive integer.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
}
prn_random_numbers(n);
return (EXIT_SUCCESS);
}
Part 1
In the first block of code, you call srand() with an uninitialized variable — this is not good. You need to move that call after where you read the seed from the user. You should also check that you got a valid result from the input.
int main(void)
{
int seed;
printf("Please enter a seed: ");
if (scanf("%d", &seed) != 1)
{
fprintf(stderr, "Failed to read seed - exiting\n");
return EXIT_FAILURE;
}
srand(seed);
Part 2
In the second block of code, you are writing K&R-style function definitions.
DON'T!!!
And yes, I would shout louder if I could. If your text book is teaching you this style, hurl the book into the rubbish bin and get another book. You have to have an extraordinary reason to use K&R-style definitions in new code. Prototypes have been available via standard compilers for about thirty years now, and have been generally available everywhere for twenty years.
Your code calling srand() in the second example also has the same flaw as in the first — calling the function before you get a seed from the user.
Also, the chances of users giving a different seed each time the program is run are approximately nil. Your claim that it "ensures the numbers are random" is a very optimistic view.
Related
My program asks the user for a numerator and then a denominator right after (If option 1 is chosen). I am pretty sure i got that part correct.I can not seem to figure out how to display the fraction(s) though when I hit option 2.
This is my code:
#include<stdio.h>
#include<string.h>
typedef struct fraction
{
int numerator, denom;
} fraction; //defined the fraction.
int main()
{//start of program
int z = 0;
int y = 0;
while (1)
{ //start of while loop
int choice;
printf("\nPress 1 to enter a fraction\n");
printf("Press 2 to view the entered fraction\n");
scanf("%d", &choice);
fraction arrFraction[100];
arrFraction[0].numerator = 0;
arrFraction[0].denom = 0;
if (choice == 1) // first option (enter numerator and then denom after)
{
printf("Enter the fraction\n");
scanf("%d", &arrFraction[y].numerator);
scanf("%d", &arrFraction[z].denom);
y++
z++;
}// end of first if statement(to enter the fraction)
if (choice == 2) //to view the entered fractions.
{
printf("\n-----------------------------");
for (int m = 0; m < z; m++)
{
printf(" %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);
}
printf("\n\n-----------------------------");
} // end of second if statement (to view the fraction entered earlier)
} // end of while loop
system("pause");
return(0);
}
You need to move fraction arrFraction[100]; out of while loop, otherwise, every iteration, there will be a new array.
That said,
printf(" %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);
is wrong, you're supplying two format specifiers but one argument. This invokes undefined behavior. Your compiler should have warned you.
I believe, what you want instead is
printf(" %d / %d \n", arrFraction[y].numerator, arrFraction[z].denom);
That said, I'm not very convinced with the overall logic. Why do you seem to need an array of 100 elements? If you're only interested in previous record (not records), use only a simple variable, not an array. Besides, you don;t need to have two separate index/ counters anyway. A single index will be able to manage the inputs in much concise and robust way.
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");
}
}
I'm trying to write a c program that uses a function that adds 2 integers to a random number. Which I have accomplished below. My problem is, I set a variable to a secret number and when that number is found, I need the program to terminate and it does not.
int x,y,secretnumber;
secretnumber = 5;
do
{
printf("Please enter two integers to be added together to a random number from 0-99 \n"
"Keep entering numbers until you hit the secret number!\n");
scanf("%i%i", &x, &y);
if(sumintsrand(x,y) != secretnumber)
{
printf("The summation of integers %i and %i and a random number is %i \n\n",x,y,sumintsrand(x,y));
}
else
{
printf("You have found the secret number: %i! Goodbye!\n", secretnumber);
}
}
while(sumintsrand(x,y) != secretnumber);
return 0;
}
int sumintsrand(int x, int y)
{
int sumintsrand = x + y + rand()%5;
return sumintsrand;
}
If anyone has any idea where I'm going wrong I would really appreciate it
UPDATE
I compiled your program with my earlier suggested mod, and I didn't get silly large numbers, so pass on that - different question?
It seems a bit strange to keep changing the random number - the same guess might fail once but work the next time. Also there is a confusion about whether the range is 5 or 99.
So I've simplified your work, to make you guess two numbers that sum to the secret number. If that's not your intention, perhaps you can draw on my code.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAXVAL 5
int main(){
int x, y, secretnumber, testval;
srand ((unsigned)time(NULL));
secretnumber = rand() % (MAXVAL+1);
do
{
printf("Enter two integers to be added to equal a secret random number from 0-%d\n"
"Keep entering numbers until you hit the secret number!\n", MAXVAL);
if (scanf("%d%d", &x, &y) != 2)
return 0; // exit program
testval = x + y;
if(testval != secretnumber)
printf("Sorry - try again!\n\n");
else
printf("You have found the secret number: %d + %d = %d! Goodbye!\n",
x, y, secretnumber);
}
while(testval != secretnumber);
return 0;
}
You are calling your sumintsrand() function thrice. Each time, the result of the function is going to be different based on what rand() returns.
Your call to sumintsrand()within the while loop may have found the secret number, but that is not retained. You need to store it for checking whether while loop needs to be terminated.
UPDATE:
int sum = 0;
do {
scanf("%i%i", &x, &y);
sum = sumintsrand(x,y);
} while(sum != secretnumber);
It's not working, because in that line while(sumintsrand(x,y) != secretnumber); you are calling sumintsrand a second time - and it gives other result.
Possible solutions:
Save the result of first call of sumintsrand and check if it(the saved result) is the same as secretnumber
Use break
Make bool variable which will end the loop - at the beginning it will be true, when you will find the number just set it to false.
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'm trying to right a program in C where I have to ask the user a certain multiplication question, I'm using rand() to generate the numbers.
If the user gets the answer wrong, then they will be asked to enter it again once they get it right, when they do get it right, the program should loop and ask the user a different question.
I'm using a separate function to generate the answer each time the 2 random values are passed to that function.
My problem is that once I get the answer correct, the program loops and asks the same question, it picks the same number! so how do I make it that everytime it loops, it picks a different number?
#include <stdio.h>
int multiply(int x, int y);
int main()
{
srand (time(NULL));
int x = rand()%20;
int y = rand()%20;
int i, answer;
i = multiply(x,y);
do {
printf("what is %d multiplied by %d?:", x, y);
scanf("%d", &answer);
while(answer != i)
{
printf("wrong try again!");
scanf("%d", &answer);
}
printf("very good!\n");
} while(i==answer);
}
int multiply(int x, int y)
{
int k;
k=x*y;
return k;
}
You need to move the assignments of x and y into the loop. This way they will get a new value in each round. In fact, you can move their whole definition in there.
Moreover, the loop coondition while(i==answer) is superfluous as at that point it is always going to be true. For the sake of clarity, you should replace it with true to make it explicit that it is an infinite loop. (And you may want to extend your program with a way to exit gracefully, e.g. if 'q' or an empty string is entered - but I will leave this as an exercise for you :-).
while(true) {
int x = rand()%20;
int y = rand()%20;
int i, answer;
i = multiply(x,y);
printf("what is %d multiplied by %d?:", x, y);
scanf("%d", &answer);
while(answer != i)
{
printf("wrong try again!");
scanf("%d", &answer);
}
printf("very good!\n");
}
Abstractly, your logic should go like this:
// seed random number generator
while (true) // ask infinitely many questions
{
int x, y, expected_result; // populate randomly
printf("Please compute the result of %d and %d: ", x, y);
while (read_answer() != expected_result)
{
printf("Sorry, wrong answer. Try again: ");
}
}
That is, for each question you generate new parameters.
You just need to implement read_answer() as a helper function that reads one integer from the input, e.g. using fgets and strtol.