Simple C Program Math Quiz - c

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;

Related

Using srand() within a function

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.

i have a problem with my code and i'm not sure if i even wrote it correctly

so i'm practicing c and i built a program that says if its prime number or not and i tried to execute it but it wont work it doesnt shows me the output oh and im still new to this i started learning c one week ago.
i dont know how to fix this.
#include <stdio.h>
void Num();
int main()
{
void Num();
return 0;
}
void Num()
{
int n, i, flag = 0;
printf("Enter a num: ");
scanf("%d", &n);
for(i = 1; i <= 10; i++)
{
for(n = 1; n <= 10; n++)
{
flag = 1;
}
}
if( flag == 1)
{
printf("its not the prime num ");
} else{
printf("its the prime num" );
}
}
it wont even show the printf output
You need to go back to the basics (this means: reading a good C book before diving in). You are confusing declaration and calling of functions.
int main()
{
void Num();
return 0;
}
main contains two statements:
A local (re)declaration of Num as a function without return value.
A return statement.
Since you want to call Num rather than redeclaring it, you need to use the function call syntax:
int main()
{
Num();
return 0;
}
This is just the first step, however. Your Num function does not perform the correct actions to determine primality.

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.

Guess the number game, every # is low

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

C Program to find prime 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");
}
}

Resources