Simple C Program Error..Can't resolve it - c

I'm trying to generate random numbers in C using srand(). I want to generate numbers from 1 to 25 without duplication, So i have implemented the following program.
#include <stdio.h>
#include <time.h>
int main()
{
int i=0,n,a[25]={0},b[25]={0},cntr=0;
srand(time(NULL));
while(cntr!=25)
{
n=rand()%26;
if(n!=9)
{
if(a[n]!=1)
{
a[n]=1;
printf("%d ",n);
b[i]=n;
printf("%d\n",b[i]);
cntr++;
i++;
}
}
}
for(i=0;i<25;i++)
{
printf("%d ",b[i]);
}
return 0;
}
Now there is a weird problem. When i print the array b inside the loop where the random number is generated it prints correct numbers. But when i print it outside the loop the first element of the array b changes to 1 and i get duplicate value of 1 in the random numbers. I would appreciate if anyone can help to find error in the program.
Here is the link to ideone where i have provided the output of the program : Ideone Link

You declare a[25] but you access any of 26 elements since n=rand()%26;, so declare instead
int i=0,n,a[26]={0},b[26]={0},cntr=0;
BTW, compile with all warnings and debug info (e.g. gcc -Wall -Wextra -g). Then use the debugger (gdb). A watchpoint would have helped.

there are several little oops in the posted code.
the following corrects those oops
#include <stdio.h>
#include <stdlib.h> // srand(), rand()
#include <time.h> // time()
int main()
{
int i=0; // generated number counter
int n; // generated number
int a[25]={0}; // tracks which numbers have been generated
int b[25]={0}; // random array of numbers 1...25
srand(time(NULL));
while(i<25) // correct loop termination
{
n=rand()%25+1; // yields 0...24 +1 gives 1...25
if(a[n]!=1)
{ // then, number not previously generated
a[n]=1; // indicate number generated
printf("%d ",n); // echo number
// save number in current location in array 'b'
b[i]=n;
printf("%d\n",b[i]); // echo number again
i++; // step offset into array 'b' (and loop counter)
} // end if
} // end while
for(i=0;i<25;i++)
{
printf("%d ",b[i]);
} // end for
return 0;
} // end function: main

Related

How to insert output into an array in c

My code:
// DICE ROLL PROGRAM
#include <stdio.h>
#include <stdlib.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; // flag variable set to 1 which will later be set to zero
srand (time(NULL)); // seeding rand so that we get different values every time
// till here
while(flag) // while loop runs as long as flag variable has a value
{
printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=2): "); // prints the message
scanf("%d", &firInp); // user input stored into firInp
printf("Enter the amount of throws you want(MAX=499, MIN=2): "); // 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 met
for(i = 0; i < secInp; i++){
rollDice = (rand()%firInp) + 1; // added 1 to rand because if the value is ever zero, you will get an error
printf("%d \n", rollDice);
}
flag = 0; // now the flag variable is set to zero, exiting the while loop
}
else{
printf("Sorry, these numbers don't meet the parameters\nPlease enter a number in the right parameters.\n");
}
}
return 0;
}
I want to input the values I obtain from "rollDice" into an array.
for example: If the user enters firInp and secInp as 6, and they get the following values:
1
2
2
3
1
6
I want these numbers to be stored in an array like so:
arrayA = [1,2,2,3,1,6]
Well it really depends on the particular codebase - my example uses stack frame allocation but it could easily be done using the malloc/calloc method suggested in the comments
(The following is pseudocode, you wil need to integrate it into your application)
int main() {
int dice_rolls[6];
for(int i = 0; i < 6 i++) {
roll = rollTheDice(); // In your program you have your own method for getting this number - the point still stands
dice_rolls[i] = roll;
}
}

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.

How to use relational operators with a random number generator (c)

I am trying to make a program that generates a random number (this part works), and then prints something depending on whether the number is greater or less than 555,555,555. While the correct thing prints if the number is over 555,555,555, nothing at all prints when the number is below 555,555,555.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int rand();
time_t secondsFromEpoch = time(NULL);
srand(secondsFromEpoch);
printf("%d\n", rand());
if (rand() > 555555555) {
printf("hello");
}
else if (rand() < 555555555) {
printf("goodbye");
}
return 0;
}
You're calling rand multiple times. Each time you call it, it returns a different number.
Save the random number in a variable and use that.
int r = rand();
printf("%d\n", r);
if (r > 555555555) {
printf("hello");
}
else if (r < 555555555) {
printf("goodbye");
}

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.

i have some trouble in typecasting

i am working in a university project that i should write a minesweaper game with some array ...
i have written my program
the program will print the minesweaper table some cell in the table has bomb the program should print * in that cell.
and other cell should print number of bomb in eight surrounding cell
I don't know how to print this double sub-scripted array that can print character and number both.
#include <stdio.h>
#define max 100
int main()
{
int a,row,column,n,x,y,counter,i,j;
char table[max][max]={0};
scanf("%d%d",&row,&column);
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d%d",&x,&y);
table[x-1][y-1]='*';
}
for(counter=0,i=0;i<row;i++)
{
for(j=0;j<column;j++)
{
if(table[i-1][j-1]=='*')
counter++;
if(table[i-1][j]=='*')
counter++;
if(table[i-1][j+1]=='*')
counter++;
if(table[i][j-1]=='*')
counter++;
if(table[i][j+1]=='*')
counter++;
if(table[i+1][j-1]=='*')
counter++;
if(table[i+1][j]=='*')
counter++;
if(table[i+1][j+1]=='*')
counter++;
if(table[i][j]!='*')
table[i][j]=counter;
counter=0;
}
}
for(counter=0,i=0;i<row;i++)
{
for(j=0;j<column;j++)
printf("%d ",(char)table[i][j]);
printf("\n");
}
}
Not an answer, but your code will not work because
if(table[i][j]!='*')
table[i][j]=counter;
^^^^^^^^^^^^^^^
Will overwrite what is in the location at i,j and the later passes will not see a '*' there. So basically your counts are going to be all messed up. You need one array for the '*' and another for the neighbor counts.

Resources