Looping through the elements in an array backwards [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
Here's my code:
int myArray[]={1,2,3,4,5,6,7,8};
for(int counter=myArray.length; counter > 0;counter--){
System.out.println(myArray[counter]);
}
I'd like to print out the array in descending order, instead of ascending order (from the last element of the array to the first) but I just get thrown this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at task1.main(task1.java:14)
Why is this happening? I was hoping that by using myArray.length to set the counter to 8, the code would just print out the 8th element of the array and then keep printing the one before that.

Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {

The first index is 0 and the last index is 7 not 8
The size of the array is 8

use myArray.length-1
for(int counter=myArray.length-1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}

The problem here is this piece of code: myArray.length. In Java, as in most other languages, Data structures are 0 based, so the last element has an index of structure.length - 1 (and the first being 0). So in your case, you should change your loop as follows:
for(int counter=myArray.length - 1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}

You're starting at the wrong index. Do it like this:
for(int counter= myArray.length - 1; counter >= 0;counter--) {
The last index of an array is its length minus 1.

the counter is starting at the index of myArray.length which is actually counted from 1 instead of 0..
for(int counter=myArray.length - 1; counter > 0; counter--){

int myArray[]={1,2,3,4,5,6,7,8};
Here, given array length is 8 as the count starts from 1 but coming for the index myArray[0] = 1;
and so on.... here index count starts from 0.
So in your piece of code
for(int counter = myArray.length - 1; counter >= 0; counter--) {
goes out of the array boundary so it shows you ArrayIndexOutOfBoundsException.

Related

what's wrong with this for loop? weird error [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I was learning about for loops and whenever I do this loop
String[] fruits = {"Apple", "Banana", "Orange"};
for (int k = fruits.length;k > 0; k--) {
System.out.println(fruits[k]);
}
and I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at helloworld.HelloWorld.main(HelloWorld.java:439)
Java Result: 1
BUILD SUCCESSFUL (total time: 10 seconds)
and I don't want to do a for each loop.
Thanks in advance
Array indexes for a Java array start at 0. So if there are 3 things in the array, their indexes are 0, 1 and 2.
You've set up your loop so that it starts at k = 3, and on subsequent iterations (if it reached them), it would have k = 2 then k = 1.
But these don't match the indexes in the array. In particular, when k = 3, there's no matching entry in the array, which is what's making your program crash.
You need to change the way your loop is set up, so that it iterates k = 2, then k = 1, then k = 0. May I suggest the following change?
for (int k = fruits.length - 1; k >= 0; k--) {
Everything else can stay the same.

Trying to display the last index of a item in array Java

I am trying to display the last index of an item in array, an example:
{6,4,7,3,11,4} Last index of 4 = 5
I have written this method so far:
public int lastIndexOf(int[] nums, int num) {
int found = 0;
for (int i = nums.length; i < 0 ; i--) {
if (nums[i] == num) {
return i;
}
}
return -1;
}
Why does this not work? I am under the impression that you need to start the for loop at the start of the arrays length and then work backwards. I want to be able to use a for loop to do this, I set up a condition if there are no occurrences of the number to return -1 but when I am running this code I always return -1 no matter what numbers I am putting in.
How would I solve this using a for loop?
Your for loop conditions are not correct. Should be
for (int i = nums.length-1; i >= 0 ; i--) {
The "i<0" from before prevented it from entering the loop.
But the "i = nums.length" would have given you an Index out of bounds error. Need to subtract by 1 because Arrays are 0 indexed
You can also turn the array into list and use List's lastIndexOf method so you don't have to implement yourself.
Arrays.asList(nums).lastIndexOf(num)
note that lastIndexOf return -1 if num is not found in nums

i want fix my method to reverse int array

trying to write a method reverseIntArray(int[] array) which should return a reverse copy of an integer array. For example, if array = [1,2,3,4], then the method should return the array [4,3,2,1].
The program compiles without any error messages. What are the errors causing incorrect incorrect behavior of the program at runtime?
public static int[] reverseIntArray(int[] array) {
int[] result = new int[10];
int j = array.length;
for (int i = 1; i < array.length; i++ ) {
result[i] = array[j];
j++;
}
return result;
}
how should the error be corrected?
what exactly is the error?
what effect the error would have?
You need to set j to be array.length -1 instead of array.length and decrement it instead of incrementing it, and start your for loop index at 0 not 1.
There are a couple of issues with your code:
Your result array is being created with a size of 10 rather than the size of the array being passed in. This will cause an issue if you pass in an array with a smaller or larger size than 10. You can resolve this with: int[] result = new int[array.length];
You're initializing i with a value of 1. Java arrays start at index 0, so your loop will skip populating the first element of the array. You instead want: for (int i = 0; i < array.length; i++) {
Because java arrays start at index 0, the last element's index will be 1 less than array's size. You want: int j = array.length - 1;
You want to retrieve array's elements in reverse order, but your code is incrementing j rather than decrementing it. You want j-- where you have j++
To solve array related problem you must know only about its storage in memory and its index.
In your solution you are trying to overwrite values. In your solution you need to make sure that you are saving older value before writing any new value to any index.
NOTE: You must know that how to swap two numbers.
int[] arr={1,2,3,4};
int i=0;
int j=arr.length-1;
while(i<j)
{
//Swapping two numbers
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
You can also do the same using for loop.

How to check index of integer array element in java? [duplicate]

This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
In the below code I can get the length and element of array. if I have to check what is the index number at run time for every element, how can I check that?
If I print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?
Another confusion in during the debug in eclipse it shows id value of array is different than the loop value.
public class FirstArray {
public static void main(String[] args) {
int[] arr = {11,12,13,14,15,16,17,18,19,20};
int onelength = arr.length;
System.out.println("Size of Array is: " + onelength);
for(int i = 0; i < arr.length; i++){
System.out.println("element of aray is: "+ arr[i]);
}
}
}
Yes, value of i will be the index value. I would suggest you to go through basics of Java arrays.
The question itself is not clear. The loop bounds are definitely different from the index value of the array. If you want to print the loop bounds along with the value at the index, just print i in the loop.
For your question "what is the index number at run time for every element, how can i check that?" Refer to the solution bellow:
Where is Java's Array indexOf?
For your question "If i print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?"
The array index starts from 0, so if your array length is 10 then index values will be 0 to 9. Thus, if you start your loop from i=0 then the index value will be same as i, but if you start your loop from i=1 then the index value will be i-1.
Will that be correct to consider the value of i as index value of
array?
Of course it'll be correct, i is actually the index of the array.
Another confusion in during the debug in eclipse it shows id value of
array is different than the loop value
Yes, it shows because it's really different, take a look:
for(int i = 0; i < arr.length; i++) {
System.out.println("element of aray is "+ arr[i]); // It prints the element itself -> 11 12 13 14 15.. and so on
System.out.println("iteration number "+ i); // It prints the index of iteration -> 0 1 2 3 4 5.. and so on
}
You may want to clarify what exactly you are searching for.
An array stores a value at a given index (starting at index zero, and going up to index length-of-the-array-minus-one).
The traditional way of creating an array is the following:
// Create an empty array that is able to hold 3 values
int[] numbers = new int[3];
numbers[0] = 11;
numbers[1] = 15;
numbers[2] = 13;
If we now print the values in the index order, we receive 11, 15 and 13. Here's the code:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
So, we see with numbers[i] = 14 we can assign the value 14 to the index i of the array. And with System.out.println(numbers[i]), we can print the value the array has stored at index i.
An array has a fixed length which needs to be specified at creation, it is not a flexible data structure (but pretty fast and small). Thus, if you are trying to access numbers[100] but we said numbers can only hold 3 values, then you will get an ArrayIndexOutOfBoundsException.
Your provided code is a short-hand for the traditional way:
int[] arr = {11,12,13};
which does the same as
int[] arr = new int[3];
arr[0] = 11;
arr[1] = 12;
arr[2] = 13;
If you want to search for the index, given the value (assuming the values are unique), you need to search the whole array until you find the index. Here's some code:
public int getIndex(final int[] array, final int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
// Value found
return i;
}
}
// Value not found
return -1;
}
Note that the search code is pretty slow, because you may need to search the whole length of the array (worst case). Other data structures may be more useful depending on your usage.

What is this algorithm doing?

I got a pseudocode:
Input: Array A with n (= length) >= 2
Output: x
x = 0;
for i = 1 to n do
for j = i+1 to n do
if x < |A[i] - A[j]| then
x = |A[i] - A[j]|;
end if
end for
end for
return x;
I have converted that to a real code to see better what it does:
public class Test
{
public static void main (String[] args)
{
int A[] = {1,2,3,4,5,6,7,8,9};
int x = 0;
for (int i = 1; i < A.length; i++)
{
for (int j = i + 1; j < A.length; j++)
{
if (x < Math.abs(A[i] - A[j]))
{
x = Math.abs(A[i] - A[j]);
}
}
}
System.out.println(x);
}
}
The output was 7 with the array in the code.
I have used another array (1 to 20) and the putput was 18.
Array 1-30, the output was 28.
The pattern seems clear, the algorithm gives you the antepenultimate / third from last array value. Or am I wrong?
I think the pseudo code tries to find the greater of the difference between any 2 elements within an array.
Your real code however, starts from 1 instead of 0 and therefore excludes the first element within this array.
I think pseudocode is trying to find the greatest difference between two numbers in an array. It should be the difference between the minimum and maximum value of the array.
I personally think this is a really poor algorithm since it is doing this task in O(n^2). You can find the min and maximum value of an array in O(n). and take the difference between those numbers and result will be the same. check the pseudocode
Input: Array A with n (= length) >= 2
min=A[0];max = A[0];
for i = 1 to n do
if min > A[i] then
min = A[i];
end if
if max < A[i] then
max = A[i]
end if
end for
return (max-min);
The code gives the biggest difference between any two elements in the array.
There are 2 nested loops, each running over each element of the array. The second loop starts at the element after the first loop's element, so that each possible pair is considered only once.
The variable x is the current maximum, initialized to 0. If x is less than the absolute value of the current pair's difference, then we have a new maximum and it is stored.
However, because you directly copied the pseudocode's starting index of 1, you are inadvertently skipping the first element of the array, with index 0. So your Java code is giving you the maximum difference without considering the first element.
If you have an array of values between 1 and n, you are skipping the 1 (in index 0) and the returned value is n - 2, which happens to be the third-to-last value in the array. If you had shuffled the values in the array as a different test case, then you would see that the returned value would have changed to n - 1 as now both 1 and n would be considered (as long as n itself wasn't in the first position).
In any case, you would need to set the index of the first element to 0 so that the first element is considered. Then {1,2,3,4,5,6,7,8,9} would yield 8 (or any other order of those same elements).
Assuming all positive integers, the algorithm in a nutshell finds the difference between the maximum and the minimum value in the array. However, it will not work correctly unless you initialize i to 0 in the for loop.
for (int i = 0; i < A.length; i++)

Categories