2

I'm using a for loop to create the first 400 multiples of 13, and I'm trying to to store these numbers into an array. The specific issue is on 5th line. I understand that this code is making the programme write to the first element of the array, which is causing the issue. Is there any way I can store the numbers sequentially?

    public static void main(String[] args) {
    int[] thirteenMultiples = new int[400];
    for (int dex = 1; dex < thirteenMultiples.length; dex ++) {
        int multiples = 13 * dex; 
        thirteenMultiples[0] = multiples;
        System.out.println(Arrays.toString(thirteenMultiples));
3
  • 3
    Use dex, since it's incremented each loop: thirteenMultiples[dex] = multiples. Commented Jan 25, 2018 at 17:49
  • Voted to close, simple typo/syntax problem. Commented Jan 25, 2018 at 17:50
  • This deserves an upvote? I rather start believing! Commented Jan 25, 2018 at 17:52

3 Answers 3

6

Array indices start at 0, so change int dex = 1 to int dex = 0. Also, you should use your counting variable dex to write to the right array index:

public static void main(String[] args) {
    int[] thirteenMultiples = new int[400];
    for (int dex = 0; dex < thirteenMultiples.length; dex ++) {
        int multiples = 13 * dex; 
        thirteenMultiples[dex] = multiples;
        System.out.println(Arrays.toString(thirteenMultiples));
    }
}

BTW: Arrays.toString(thirteenMultiples) is quite an expensive operation to do on every iteration (try to code this method yourself and you'll see what i mean). Maybe you should just print the current value of thirteenMultiples[dex] and print you array once the loop has finished. I assume you're just testing and trying stuff for now, but i think it's good to keep such things in mind from the beginning ;)

Sign up to request clarification or add additional context in comments.

Comments

4

thirteenMultiples[dex] in place of thirteenMultiple[0], because dex is equal to the index each time for loop runs. For ex - for dex =1 you store multiple at [1], then it increases to 2 then it becomes [2] and you store the next multiple at 2. Hence it stores each new value at new index.

Also start dex from 0 as array starts from 0 index.

Comments

0

I guess in this case, it is better to use a List rather than an array. Your code will look cleaner

public static void main(String[] args) {
    List<Integer> thirteenMultiples = new ArrayList<Integer>;
    for (int dex = 0; dex < 400; dex ++) {
        thirteenMultiples.add(13 * dex)
    }
    System.out.println(thirteenMultiples);

}

1 Comment

Thank you for the alternate perspective. I'll look into this.

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.