How I can index the array starting from 1 instead of zero? - java

for (int i = 0; i < reports.length; i++) {
Products[] products = reports[i].getDecisions;
for (int j = 0; j < products.length; j++) {
}
}
Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j

Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.
It's defined in JLS §10.4, if you are interested in it.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.

You can't do that as array index in Java starts from 0.
But you can access array with index 1 with little modifications.
Example:
Consider an integer array "a" with length n
for(int i=0;i<n;i++) {
System.out.println(a[i]);
}
This can be modified as:
int a[] = new int[n+1];
for(int i=1;i<n+1;i++) {
System.out.println(a[i]);
}

Just like in most languages arrays are indexed from 0. You better get used to it, there is no workaround.

Base Index of Java arrays is always 0. It cannot be changed to 1.

You can use pointers, to jump to a certain point of the array and start the array from there.
For example:
char str[20];
str={'H', 'E' ,'L' ,'L', 'O','W' ,'O ','R','L',' D'};
char *ptr;
*ptr=str[0];
//right now its pointing to the starting.
ptr=ptr+3;
//Now pointing at 3rd unit.
This doesn't work in every compiler.This is the closest thing that can be done for your question.

its all simple that in C , C++ , Java or etc.. the array index start from "0" only. and we can't change it. but sometimes in some Practice problems we are asked to use 1-indexed-based array, which we actually can't do that, so to tackle that, just leave 0th-index aside, and start using the array from 1th-index onwards, and while solving the situation always keep in mind that we have to never include or use that 0th-index in our operations.

Related

why do my averages not print out the way they're supposed to? [duplicate]

for (int i = 0; i < reports.length; i++) {
Products[] products = reports[i].getDecisions;
for (int j = 0; j < products.length; j++) {
}
}
Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j
Java arrays are always 0-based. You can't change that behavior. You can fill or use it from another index, but you can't change the base index.
It's defined in JLS §10.4, if you are interested in it.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
You can't do that as array index in Java starts from 0.
But you can access array with index 1 with little modifications.
Example:
Consider an integer array "a" with length n
for(int i=0;i<n;i++) {
System.out.println(a[i]);
}
This can be modified as:
int a[] = new int[n+1];
for(int i=1;i<n+1;i++) {
System.out.println(a[i]);
}
Just like in most languages arrays are indexed from 0. You better get used to it, there is no workaround.
Base Index of Java arrays is always 0. It cannot be changed to 1.
You can use pointers, to jump to a certain point of the array and start the array from there.
For example:
char str[20];
str={'H', 'E' ,'L' ,'L', 'O','W' ,'O ','R','L',' D'};
char *ptr;
*ptr=str[0];
//right now its pointing to the starting.
ptr=ptr+3;
//Now pointing at 3rd unit.
This doesn't work in every compiler.This is the closest thing that can be done for your question.
its all simple that in C , C++ , Java or etc.. the array index start from "0" only. and we can't change it. but sometimes in some Practice problems we are asked to use 1-indexed-based array, which we actually can't do that, so to tackle that, just leave 0th-index aside, and start using the array from 1th-index onwards, and while solving the situation always keep in mind that we have to never include or use that 0th-index in our operations.

What do array[] and array[i] operators do in Java?

I'm trying to teach myself coding, and I stumbled on an example I don't understand. Could someone give me an overview of what this code is supposed to do? I'm a bit confused about int a[] and what is later int a[i]. I know what an array is, but could someone please explain how this is being used in this context? Thank you in advance.
public class all {
public int select(int a[],int n,int x)
{
int i=0;
while(i<n && a[i]<x)
{
if(a[i]<0)
a[i]=-a[i];
i++;
}
return(a[i-1]);
}
}
This
if(a[i]<0)
a[i]=-a[i];
i++;
is he same like this
if(a[i]<0) {
a[i]=-a[i];
}
i++;
a[i] -> value at the position i, into the Array
if(a[i]<0) { -> if the value at position i is smaller than 0, also negative number
a[i]=-a[i]; -> replace the value with a reverse sign.
i++ -> increment loop Counter
Also what is done here: negative numbers convert to positive numbers.
while(i<n && a[i]<x) -> i = loop counter; if i smaller n and the value at position i in the array is smaller than x, then go into the loop.
return(a[i-1]); -> return the last value, that has been checked into the while loop
the method gets an array and two int args n and x (as a side note, I must say the names leave a lot to be desired...)
anyway, lets see what are the args for. they both are used in the while loop. the condition i<n tells us that n serves as upper limit to the iteration, while the condition a[i]<x tells us that x is used as upper limit to the values in the array.
so far, we can say:
select method receives an array, int arg specifying iteration-upper-limit and int arg specifying cell-value-upper-limit.
iterate over the array until you reach position specified by iteration-upper-limit or you reach a cell value that exceeds cell-value-upper-limit (which ever comes first)
can you continue to say what's being done inside the loop? it's fairly straightforward.
1.) a[] is the declaration of array.size is not defined.
2.)In a[i], i is the index number of the array...that means indicating the position of the element in array.
a[] is an array and we do not know its length. n must be lower than the length of a[] or it will throw an exception. It it traverses from the first element toward the last untill it one element is larger than x. it returns these element's absolute value which were traversed

Is there a difference in runtime efficiency if I evaluate the size of the array outside the loop?

The traditional way to iterate over an (integer, in this example) array of elements is the following:
int[] array = {5, 10, 15};
for(int i = 0; i < array.length; i++) [
//do something with array[i]
}
However, does this mean that after each iteration 'array.length' is re-evaluated? Would it not be more efficient to do this? :
int[] array = {5, 10, 15};
int noOfElements = array.length;
for(int i = 0; i < noOfElements; i++) {
//do something with array[i]
}
In this way, (to my understanding) the program only has to calculate it once and then look up the value of 'noOfElements' variable.
Note: I am aware of the enhanced for-loop, but it cannot be used when you want to use the variable that is being incremented ('i' in this example) to achieve other things within the for-loop.
I'm suspecting that this is actually a question of whether the Java compiler has the capability of realising that 'array.length' doesn't change and actually reusing that value after calculating it once.
So my question is: Is there a difference in runtime efficiency of the first block of code I wrote and the second one?
What I gather from the replies below, is that when an array is instantiated (is that the right word?) an instance variable called length is created and it is equal to the number of elements in the array.
What this means is that the statement array.length has nothing to do with calculation; it is only referencing the instance variable.
Thanks for the input guys!
See JLS- 10.7. Array Members:
The members of an array type are all of the following:
The public final field length, which contains the number of components
of the array. length may be positive or zero.
Calling array.length is O(1) (constant time operation - it's final member of the array).
Also note that as mentioned in the comments, "traditional" way is not necessarily the way you proposed. You can use for-each loop:
for(int i : array) {
...
}
length is a field, therefore is not calculated when examining the for loop condition.
Your second block of code introduces a field to represent the length, thus increases memory usage (slightly, but still an important factor).
Yet further, if the array were to be re-created/re-assigned at some point, with a different set of values, your field would not be updated, but the array's length field would.
length is a field of an array that is not being calculated if you call myArray.length, instead it is being set when you create the array. So no, it's not more efficient to save it to a variable before starting the for() loop.

checking if Index out of Range with array

I have written a program with a lot of operations on arrays. How I can check if I out of range with array, because I go Run Time Error at SPOJ.
Without knowing any more detailed context, the basic approach as outlined by Jon Skeet in the comments is something like the following:
if (index < 0 || index >= array.length) {
//Index Out Of Range
}
There is no code to refer and see if you have gone out of range. Maybe you want to post your code for reference.
As long as your index is not of negative value and 1 value under the length of your array, you will be within bounds of your array.
For example an array of length 10, you have to minus 1 and able to call indexes between 0 - 9.
for(int x=0; x < yourArray.length; x++){
//this for loop will nicely loop without going out of bounds unless your
//loop body contains something that will trigger the error.
}

bubble sort string array

I'm trying to use a bubble sort to alphabetize an array that I've read into a program. The code compiles without error but I get an Array Index Out Of Bounds Exception on my 'if' construct when I try to run the program. I have initialized int i to 0 to account for the first index of the array so I think my error is elsewhere. I'm not asking anyone to write code for me, just maybe a point in the right direction. Thanks for any help.
public static String[] bubbleSort(String[] inL)
{
String temp;
int i = 0, passNum;
for(passNum = 1; passNum <= (inL.length); i++) // controls passes through bubble sort
{
if(inL[i].compareToIgnoreCase(inL[i + 1]) < 0)
{
temp = inL[i];
inL[i] = inL[i + 1];
inL[i + 1] = temp;
}
}
return inL; // returns sorted array
} // end bubbleSort method
You compare passNum instead of i against the length of the array. Since passNum is never modified, the loop condition is always true, and i gets incremented until it exceeds the range of the array.
Even if this particular issue is resolved, you may still run into problems with off-by-one errors with your current implementation. Consider whether you should compare i against inL.length - 1.
You never increment passNum so i continues incrementing forever. Also, array indexing in Java is based at 0. That means that the largest valid index is inL.length - 1. Since the body of your loop accesses inL[i+1], you should arrange your code so that i never exceeds inL.length - 2. At a minimum, you should change <= to < in the for loop termination test. (However, the logic of your comparison and incrementing escapes me; you need to fix that as well.)
Array.length stores the total length of an array, starting counting at 1.
The first index in an array however is 0, meaning that the last index is length-1.
adjust your check in your for-loop to fix the error
Your problem is the passNum <= (inL.length) it should be passNum < (inL.length) due to 0 being the first index of an array in java

Categories