1

hey guys i'm having some trouble working this out. The aim is to convert an int array like this {1, 2, 3, 4} by adding one to each element and printing it using an ENHANCED for loop, so it will look like this {2, 3, 4, 5}. This is what i got so far :

    int myArr[] = {1, 2, 3, 4};

    for (int i: myArr){
        i =+1;
        myWindow.writeOutLine(i);
    }

Pretty sure that is not close, i'm unsure how to store the new value in the array and go to next.

3 Answers 3

4

You can't do it with the enhanced for loop, since that loop hides the indices of the array, so you can't modify the array.

Use a traditional for loop instead.

for (int i = 0; i < myArr.length; i++) {
    myArr[i]++;
    myWindow.writeOutLine(myArr[i]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well, technically he could use the for each loop if he uses his own index variable in addition, but that would pretty much defeat the purpose of the for each.
@domdom That's true.
1

you can use separate index variable if you have to use enhanced loop.

int myArr[] = {1, 2, 3, 4};
int count = 0 ;
for (int i: myArr){
     myArr[count] = i+1;
     myWindow.writeOutLine(myArr[count]);
     count++;
}

Comments

0
    int[] myArr = {1, 2, 3, 4};

    for(int i = 0; i < myArr.length; i++){
        int x = 1; // Amount to increment each value by
        myArr[i] = myArr[i] + x;
    }

    System.out.println(Arrays.toString(myArr));

Comments

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.