J
J
Junior77712021-06-01 14:48:25
Java
Junior7771, 2021-06-01 14:48:25

Why does the array give the wrong result?

public class Main {
    static void bar() {
        int[] nums = {1, 2, 3};
        for ( int x = 0; x < nums.length; x++ ) {
            x += nums[x];
        System.out.println(x);
        }
    }
    public static void main(String[] args) {
            Main.bar();
        }}

When compiled, the result is:

1
5

I can’t understand why, because first 1 is written to the x variable, then it is displayed on the screen, then 2 should be added and 3 should be displayed in the console, and 5 is displayed immediately.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-06-01
@Junior7771

First, the array does not produce anything anywhere.
Secondly, you use the same variable to iterate over the array and for the accumulator. Use different ones.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question