0
    #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

2
  • #include <stdio.h> has also been included there Commented Oct 11, 2016 at 1:42
  • 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]); could perhaps be written more clearly. In fact, I don't think the last argument makes any sense Commented Oct 11, 2016 at 1:43

2 Answers 2

3
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];
Sign up to request clarification or add additional context in comments.

1 Comment

And make i into a local variable, not a global.
2

Write your last line as a loop instead:

for(int i = 0; i < 20; i++)
    printf("%d\n", nums[i]);

2 Comments

That has got it to run as expected, do you know what it was I was doing incorrectly?
As @AlexD said, you cannot index arrays like nums[1, 2, 3, ...] because (1, 2, 3, ...) evaluates to 20.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.