+ 2
How can i determine the length of an array
array length
6 Respostas
+ 15
int[] arr = new int[42];
System.out.print(arr.length); // outputs 42
+ 3
Tashi is right, that is the simplest way.
However, if you are new to programming and need to work on loops, you can use them to get your answer with the added bonus of practicing other things
+ 1
you can do that using the simple example below
int[ ] intArr = new int[5];
System.out.println(intArr.length);
//Outputs 5
Note:the variable name is intArr , and the method is .length and the value initialized in our array is 5 which it returns as the output
0
Hello Everyone,
this is a question in "Summing Elements in Arrays"
The answer is x++ and sum.
I wanted to run this as a program.
public class MyClass {
public static void main(String [] args) {
int [] myArr = new int[4];
double sum = 0.0;
for(int x = 0; x < 4; x++) {
sum += myArr[x];
}
System.out.println(sum);
}
}
// output answer 0.0
// would the correct way to write this
// this code be: int[] myArr = {0, 1, 2, 3}; ?
// in place of int [] myArr = new int[4]; ?
Thanks in advance, Darryl
0
both are correct ways to do it.
The reason your output is 0 however is because you defined an array, but didn't give each index a value. you can say myArr[0]=1; and do that for each index if you want.. then when you run thru the for loop and add each index to your sum it will work. quick way to fill your array with values would be another for loop.
0
int [] myArr = new int[4];
double sum = 0.0;
//Fill your array with values
for(int i=0; i <myArr.length; i++){
myArr[i]=i;
}
for(int x = 0; x < 4; x++) {
sum += myArr[x];
}
System.out.println(sum);
// output answer 6.0