0

Currently, I am experimenting some codes regarding/about random numbers. The problem is, when I run the program, input any number (ex. 12), I, sometimes get the correct and sometimes wrong answer. The correct answer must be any non repeating random numbers based on user input. (ex. input 5, output must be 1. seats[12]=1, 2. seats[19]=1,..., 5. seats[47]=1). I do not know what to do and yeah help me coders!

Here's the code:

#include<stdio.h> 
#include<conio.h>
#include<time.h>
main()
{
    int x,y,chc1A,seats[50]={};
    printf("Enter a number: ");
    scanf("%d",&chc1A);
    srand(NULL);
    for(x=0;x<chc1A;x++)
    {
        if(seats[rand()%50]==0)
            seats[rand()%50]=1;
        else
            x--;
    }
    for(x=0,y=1;x<50;x++)
        if(seats[x]==1)
        {
            printf("%d. seats[%d] = %d\n",y,x,seats[x]);
            y++;
        }
    getch();
}

I do not really know what's wrong please enlighten me.

I run and coded this on Dev C++

What I want to do is: generate random numbers between 0-49 and putting it in an array seats[50]. (ex 38 then put 1 in array seats[38]). Btw this code represents passengers sitting on a bus with 50 seats. So the "1" means that the seat is occupied.

J...S
  • 4,713
  • 1
  • 15
  • 34

1 Answers1

2

This part may cause problem.

for(x=0;x<chc1A;x++)
{
    if(seats[rand()%50]==0)
        seats[rand()%50]=1;
    else
        x--;
}

I think by

    if(seats[rand()%50]==0)
        seats[rand()%50]=1;

you meant to generate a random number, use that as index to seats and if seats[random_no] is 0, set seats[random_no] to 1.

But the random number in the if statement and the one in its body are different numbers.

You could use

    int index = rand()%50;
    if(seats[index]==0)
        seats[index]=1;

Consider changing the signature of your main() function. See What are the valid signatures for C's main() function?


conio.h is not part of the standard, try to avoid its usage. Same goes for getch() as it's from conio.h.


srand() expects an unsigned int as argument and NULL is not of that type. See here.

Include stdlib.h to use srand().


And checking the return value of scanf() is a good idea. You can see if it failed or not.

J...S
  • 4,713
  • 1
  • 15
  • 34