Question

I am trying to write a program that will assign 5 random integers to an array but so far it is filling the array with zeroes. Also, the first number can't be a zero. What am I doing wrong?

#include <stdio.h>
#include <stdlib.h>

int number[5];

int main()      {
    int i;
    int t=0;
    for (int t=0;t<5;t++)  {
        if (i=0)
        {number[i] = rand()%8+1;}
        else
        {number[i] = rand()%10;}
        i++;
        printf("%d", number[i]);
    }           
    return (0);
}

No correct solution

OTHER TIPS

if (i=0)

That's assignment, not equality comparison.

int i;

Also, i is uninitialized, so accessing its value is undefined behavior. Since you accidentally assigned to it instead of comparing to it, if (i=0) doesn't invoke undefined behavior, but it would if you fixed the first bug.

i++;

printf("%d", number[i]);

Incrementing i before the print means you always print the cell right after the one you were working on.

You don't actually need i; t does everything you want i to do. We'll remove i and rename t to i:

for (int i = 0; i < 5; i++) {
    if (i == 0) {
        number[i] = rand() % 8 + 1;
    } else {
        number[i] = rand() % 10;
    }

    printf("%d", number[i]);
}

Several things are wrong in your code ...

1) You didn't initialize the variable i

2)

if(i=0)

should be

if( i == 0 )

3) You can use variable t instead of i -- means variable i is unnecessary

4) You should have a function call for randomize() function before rand() function call, so that you can get the real random numbers

5) If you just want to show the random numbers, you don't even need to use array

You will get the same sequence of 'pseudo-random' values by calling rand() in your program. To change this sequence the Random Number generator has to be 'seeded'. This is done by calling srand() function once with a seed value at the beginning of your program.

Ideally the value used for seed should change with each run of the program. Things that you could use as the seed are the process id, time, date or any other system provided value that is guaranteed to be different for each run of the program.

void srand(unsigned int seed);

Apart from that there are logical flaws in your program as others have highlighted, of which the if conditional assignment error is the most serious.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top