Why this for loop of array uses newARRAY.length-1? - java

Hello I'm beginner at java now I've arrived to arrays here is a for loop to sort number from highest to lowest, my question is why the instructor used
newARRAY.length-1
?
public static int [] integers;
public static int [] sortArray(int[] array){
boolean PeaceArray = true;
int temp;
int [] newARRAY = Arrays.copyOf(array,array.length);
while(PeaceArray){
PeaceArray = false;
for(int i=0;i<newARRAY.length-1;i++){
if(newARRAY[i]< newARRAY[i+1]){
temp = newARRAY[i];
newARRAY[i] = newARRAY[i+1];
newARRAY[i+1] = temp;
PeaceArray = true;
}
}
}
return newARRAY;
}

Normally the first index of a java array starts from zero (0), but the length property of
the arrays gives an actual count of the array.
For example, consider the following integer array:
int[] numbers = {40, 55, 63, 17, 22, 68, 89, 97, 89}
This array can be represented graphically as well like below
So if we are to run a loop for this array like:
for(int i=0; i<numbers.length; i++){
//this loop runs 9 times
}
I the above loop i was initialized to 0 and the maximum value i can get to is 8 but the loop will run 9 times because if you count all the way from 0 to 8 you get 9
But if you run a loop like this
for(int i=0; i<numbers.length-1; i++){
//this loop runs 8 times
}
The loop will run 8 times but the maximum value i can get to is 7
Your instructor used newARRAY.length-1 because he didn't want the maximum value of i to exceed the immediate lower number following newARRAY.length-1 because he was using the value of i+1 to index the array newArray somewhere in the code.
If he hadn't used newARRAY.length-1 in the code, when i gets to its maximum value, newARRAY[i+1] would give an IndexOutOfbounds error, because the last index of newARRAY would have been exceeded because of the 1 he is adding to i to access the newARRAY
I hope you understood this.

Array start the index with 0
ex:
int a[]={1,2,3,4,5};
then a.length=5 but a[5] does't exits in the array
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5
for this reason we use a.length-1 instead of a.length

Related

Getting indexes of maximum number in array

I have an array containing numbers which are ranks.
Something like this :
0 4 2 0 1 0 4 2 0 4 0 2
Here 0 corresponds to the lowest rank and max number corresponds to highest rank. There may be multiple indexes containing highest rank.
I want to find index of all those highest rank in array. I have achieved with following code:
import java.util.*;
class Index{
public static void main(String[] args){
int[] data = {0,4,2,0,1,0,4,2,0,4,0,2};
int max = Arrays.stream(data).max().getAsInt();
ArrayList<Integer> indexes = new ArrayList<Integer>();
for(int i=0;i<12;i++){
if(data[i]==max){
indexes.add(i);
}
}
for(int j=0;j<indexes.size();j++){
System.out.print(indexes.get(j)+" ");
}
System.out.println();
}
}
I have got result as : 1 6 9
Is there any better way than this ?
Because, In my case there may be an array containing millions of elements due to which I have some issue regarding performance.
So,
Any suggestion is appreciated.
One approach would be to simply make a single pass along the array and keep track of all indices of the highest number. If the current entry be less than the highest number seen so far, then no-op. If the current entry be the same as the highest number seen, then add that index. Otherwise, we have seen a new highest number and we should throw out our old list of highest numbers and start a new one.
int[] data = {0,4,2,0,1,0,4,2,0,4,0,2};
int max = Integer.MIN_VALUE;
List<Integer> vals = new ArrayList<>();
for (int i=0; i < data.length; ++i) {
if (data[i] == max) {
vals.add(i);
}
else if (data[i] > max) {
vals.clear();
vals.add(i);
max = data[i];
}
}
You are on the Stream- way... I would suggest you to stay there :)
int[] data = { 0, 4, 2, 0, -1, 0, 4, 2, 0, 4, 0, 2 };
int max = Arrays.stream(data).max().getAsInt();
int[] indices = IntStream.range(0, data.length).filter(i -> data[i] == max).toArray();
As i see your program goes through the array 2 times.You can try this:
Run through the array finding the max of this array.When you find a max just save every other element that is equal to the current max and their values.This way you only go through the array only once.
Here is an example: Let's say you have the following array {1,3,5,3,4,5} and you go through it.You will first save the 1 as max then the 3 then the 5 which is the max of this array.After saving 5 you won't save 3 or 4 but you will save 5 as it is equal to the max.Hope i helped.

Given an integer "n", return an array of size "n" that contains the numbers 0, 1, 2, 3, ...?

My code so far:
public int[] arrayCreation1(int n) {
int[] a = new int[0];{}
int i = 0;
for (int i = 0) i<size.length) i++); {
}
return i;
}
How would I go about completing this?
the variable i is defined twice. If the variable "i" is for the for loop, you can initialise the variable in the loop itself just like you did "int i = 0".
the question stated that you are trying to fill in array with integers starting from 0 to n. You have accept a console input or hard code the value n.
Look up array initialisation and how to assign values.
I think this should get you started atleast.
I am new to programming too and this is what I felt was wrong.
As the comments have stated, your code has many issues:
You are defining a as an array of length 0
You define i as 0 twice
Your for loop is malformed
You have a semicolon after your for loop, which is seen as an empty stament and will prevent the loop from iterating over the block.
Size is not defined anywhere
You return i, which is an int not an array
Here's some code that will work, but I suggest you spend some time with a book or tutorial:
public int[] createArray(int n){
int[] out = new int[n];
for(int i = 0; i < n; i++){
out[i] = i;
}
return out;
}

reverse for loop for array countdown

I get the error..
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Reverse.main(Reverse.java:20).
There is not wrong in the syntax so im not sure why when it compiles it gets an error?
public class Reverse {
public static void main(String [] args){
int i, j;
System.out.print("Countdown\n");
int[] numIndex = new int[10]; // array with 10 elements.
for (i = 0; i<11 ; i++) {
numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
}
for (j=10; j>=0; j--){ // could have used i, doesn't matter.
System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?
}
}
}
You declared array on integers of 10 elements. And you are iterating from i=0 to i=10 and i=10 to i=0 that's 11 elements. Obviously it's an index out of bounds error.
Change your code to this
public class Reverse {
public static void main(String [] args){
int i, j;
System.out.print("Countdown\n");
int[] numIndex = new int[10]; // array with 10 elements.
for (i = 0; i<10 ; i++) { // from 0 to 9
numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
}
for (j=9; j>=0; j--){ // from 9 to 0
System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?
}
}
}
Remember indices starts from 0.
.
Java uses 0-based array indexes. When you create an Array of size 10 new int[10] it creates 10 integer 'cells' in the array. The indexes are: 0, 1, 2, ...., 8, 9.
Your loop counts to the index which is 1 less than 11, or 10, and that index does not exist.
The array is of size 10, which means it is indexable from 0 to 9. numIndex[10] is indeed out of bounds. This is a basic off-by-one error.
An Array in java that has 10 elements goes from 0 to 9. So your loops need to cover this range. Currently you are going from 0 to 10, and 10 to 0.

Searching specific rows in a multi-dimensional array

I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.

ArrayIndexOutOfBoundsException when iterating through all the elements of an array

how to handle this exception "ArrayIndexOutOfBoundsException"
my code : I create an array of 64 length then I intialized every index then I print the indexes to make sure I am fulling all indexes but it prints up to 63 then gives the exception !! any idea
public static void main(String [] arg) {
int [] a=new int [64];
for(int i=1;i<=a.length;i++){
a[i]=i;
System.out.println(i);
}
}
The array indexes in Java start from 0 and go to array.length - 1. So change the loop to for(int i=0;i<a.length;i++)
Indexes start from 0 so last index is 63. Change your for loop like this:
for(int i=0;i<a.length;i++){
See the JLS-Arrays:
If an array
has n components, we say n is the
length of the array; the components of
the array are referenced using integer
indices from 0 to n - 1, inclusive.
So you have to iterate through [0,length()-1]
for(int i=0;i<a.length;i++) {
a[i]=i+1; //add +1, because you want the content to be 1..64
System.out.println(a[i]);
}
Need Complete Explanation? Read this
The index of an Array always starts from 0. Therefore as you are having 64 elements in your array then their indexes will be from 0 to 63. If you want to access the 64th element then you will have to do it by a[63].
Now if we look at your code, then you have written your condition to be for(int i=1;i<=a.length;i++) here a.length will return you the actual length of the array which is 64.
Two things are happening here:
As you start the index from 1 i.e. i=1 therefore you are skipping the very first element of your array which will be at the 0th index.
In the last it is trying to access the a[64] element which will come out to be the 65th element of the array. But your array contains only 64 elements. Thus you get ArrayIndexOutOfBoundsException.
The correct way to iterate an array with for loop would be:
for(int i=0;i < a.length;i++)
The index starting from 0 and going to < array.length.
In Java arrays always start at index 0. So if you want the last index of an array to be 64, the array has to be of size 64+1 = 65.
// start length
int[] myArray = new int [1 + 64 ];
You can correct your program this way :
int i = 0; // Notice it starts from 0
while (i < a.length) {
a[i]=i;
System.out.println(i++);
}
You've done your math wrong. Arrays begin counting at 0. E.g. int[] d = new int[2] is an array with counts 0 and 1.
You must set your integer 'i' to a value of 0 rather than 1 for this to work correctly. Because you start at 1, your for loop counts past the limits of the array, and gives you an ArrayIndexOutOfBoundsException.

Categories

Resources