Reputation: 1
#include <conio.h>
#include <time.h>
int i = 1;
int main()
{
int nums[20];
srand(time(NULL));
while(i < 20){
nums[i] = rand()% 10;
i++;
}
printf("%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n", nums[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]);
}
when I run this code I am given values I expect, Ie under 10, except for the values for 2, 3, and 4, and more often than not 4 is negative.... Any help on what I have done wrong would be appriciated
Upvotes: 0
Views: 41
Reputation: 32576
nums[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
is equivalent to
nums[20]
due to the funny ,
-operator.
Try enumerating elements like this (starting with 0
):
nums[0], nums[1], ..., num[19]
And initialize i
to 0
:
i = 0;
Or, although it is usually looks suspicious, start at 1
, but then declare
int nums[21];
Upvotes: 3
Reputation: 27201
Write your last line as a loop instead:
for(int i = 0; i < 20; i++)
printf("%d\n", nums[i]);
Upvotes: 2