Write a program that displays a new random permutation of the integers 0 to 9 at the request of its user. For example, the program’s output could be as follows:
Your program should prints how many 7 was printed when user type no.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
int i , total , r;
char ans;
srand(time(NULL));
do{
for( i=0 ; i < 10 ; i++)
{
r= (rand()%(9-1+1)) + 1;
printf ("%d ",r);
}
total =0;
if (r==7) // Here how can I correct this so total will increase every time
{ // there is a 7 in the string
total++;
}
printf("\nAnother permutation: y/n?\n");
scanf(" %c",&ans);
if (ans != 'y')
{
printf("Bye!\n");
printf("The number of 7's is: %d", total);
}
}while(ans=='y');
return 1;
}
I have a problem with my code. How can I increment the 7's shown in this program after != 'y'.
Set total=0 before entering into the do-while loop, to get the correct total.
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");
}
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.
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.
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}
This is a program that gets numbers input. From the numbers given or inputted, store in an array those numbers only that are even. Input will stop/terminates once 5 even numbers are already stored in the array. So here's my code:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int x, counter, even[5], numEven=0;
for(counter=0; counter<5; counter++){ //loop for getting the numbers from the user
printf("Enter number: ");
scanf("%d", &num[counter]);
if(num[counter]%2==0){ //storing the even numbers
even[numEven] = num[counter];
numEven++;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(counter=0; counter<numEven; counter++){
printf("%d, ", even[counter]);
}
getch();
return 0;
}
I have confusion in the part where will I stop the inputting when there's already 5 even numbers stored. Is there something missing? Or am I doing the wrong way? I hope I can get help and suggestions with the code. Thank you very much.
#include <stdio.h>
#include <conio.h>
int main()
{
int x, even[5], numEven = 0;
while (numEven < 5)
{
scanf("%d", &x);
if (x % 2 == 0)
{
even[numEven++] = x;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(x=0; x<numEven; x++)
{
printf("%d, ", even[x]);
}
getch();
return 0;
}
You keep readin inputs till numEven reaches 5. If the read input is an even number store it in the array and increment numEven.
Use a while loop if the number of times the program will ask the user for input is not fixed and dependent on the user's input.
while (numEven < 5) {
printf("Enter number: ");
scanf("%d", &num[counter]);
if (num[counter] % 2 == 0) {
even[numEven] = num[counter];
numEven++;
}
}