# Thread: random number generator array

1. ## random number generator array

hey i having problems with solving this question:
Write a program that generates an array of 20 random numbers between 1 and 100. Use a loop to
output the numbers on the screen with a field width of 4 characters. Write code that will reverse the
numbers in the array and then output the numbers to the screen with a copy of the same output loop
used with the original numbers.

2. What kind of errors are you getting?

3. array of 20
Code:
`int arr [20] ;`

20 random numbers
rand () and srand ()

Use a loop
Code:
```int i ;
for (i = 0; i < 20; ++i) {
...
}```

output the numbers on the screen with a field width of 4 characters
printf () formatting

reverse the numbers
A swap () function

Or copy them backwards into a second array.

Homework help

4. i have filled the array with random numbers and got it to print with a feild width of 4 characters i just dont know figure out how to print the array data in reverse. this is what i have:
Code:
```int main()
{
int array[20], i;
for(i = 0; i < 20; i++)
{
array[i] = (rand() % 100)+1;
printf("%4d\n", array[i]);
}
return 0;
}```

5. Write a second loop that starts from the last element to print them.

6. Originally Posted by laserlight
Write a second loop that starts from the last element to print them.
hey laserlight
so say the first 3 integers in the array are:
45
100
20
how would i switch all numbers in the array to:
54
001
02
(opposite)?
thankyou for your help

7. It's easy enough to print numbers in reverse.

Just go

Code:
```for(i=N-1;i>=0;i--)
printf("%d\n", array[i]);```
But you're not allowed to do this. You have to reverse the array. So you have to step throuhg half of it, swapping very ith element with the N-i-1th element. It's a bit tricky to get all the cases right.

To generate random number on 0 to N-1, the cheap and nasty way is rand() % N. This doesn't give a very good distribution, because rand() isn't truly random and the lower bits are less random than the whole.
So the best way to to say

Code:
```/* random number on 0-1 minus a tiny epsilon */
#define uniform() (rand()/RAND_MAX+1.0))

/* random number on 0-N */
#define rnd(N) (int) (uniform() * (N))```

8. Originally Posted by werty2480
so say the first 3 integers in the array are:
45
100
20
how would i switch all numbers in the array to:
54
001
02
(opposite)?
If you need to reverse the order of the digits in a number you could use a combination of modulo (%) and divisior.

Bye, Andreas

Popular pages Recent additions