-6
int arr[] = new int[10];
int size=0;
while(???)
{
    i++;
}

System.out.println(size);  // Should print 10

How can I loop over the array without using arr.length or other library functions?

dehrg
  • 1,661
  • 14
  • 17
Navchetan
  • 113
  • 1
  • 2
  • 9

2 Answers2

2
int arr[] = new int[100];

int sum = 0;
int i = 0;
while (true) {
  try {
    sum += arr[i];
  } catch (ArrayIndexOutOfBoundsException e) {
    break;
  }
  i++;
}

System.out.println("Array is of size " + i);

I'm assuming array is of ints, but the idea is the same.

Simone Gianni
  • 10,588
  • 36
  • 45
  • So ... basically we are using the ArrayOutOfBoundsException to break and hence calculate. Is there any way to calculate size without using this exception? – Navchetan Sep 03 '14 at 01:10
  • This is not a dig at you, but a note to other people reading this that don't know better, [Why not use exceptions as regular flow of control?](http://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control), [Dont Use Exceptions For Flow Control](http://c2.com/cgi/wiki?DontUseExceptionsForFlowControl), [Are exceptions as control flow considered a serious antipattern? If so, Why?](http://programmers.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why)...and I could go on... – MadProgrammer Sep 03 '14 at 01:11
  • Yes .. quite bad, but works .. the sum += arr[i] is there cause otherwise the compiler MAY remove the "arr[i]" statement, seeing it is not used for anything. – Simone Gianni Sep 03 '14 at 01:11
  • @MadProgrammer yes, using exceptions as flow control is bad. The question however, which quite obviously comes from some homework or trivia, points to this direction. Obviously is a bad homework or trivia. – Simone Gianni Sep 03 '14 at 01:13
  • @Navchetan Within Java, no, that's the reason why there is a `.length` attribute. The ONLY other possible solution would be to use a terminator of some kind in the array which allowed you to determine that you've reached the end of the "valid" entries, but this is not a measure of how large the array "might" be, but a measure of the number of "valid" elements it contains – MadProgrammer Sep 03 '14 at 01:13
0

Under the hood you'll get a .length (unless you use a strange compiler), but since the question's kinda weird...

int[] array = new int[100];
int size = 0;

for(int i : array){
    ++size;
}

System.out.println("Size: " + size);

I still don't understand the point

JSlain
  • 536
  • 3
  • 18