KnowledgeBoat Logo

Computer Applications

A student wrote the following code segment, intending to print 11 22 33 44:

int arr[] = {11, 22, 33, 44};
for (int i = 1; i <= 4; i++)
    System.out.println(arr[i]);

However, the program crashed with a run-time error. Can you explain the reason for this?

Java Arrays

14 Likes

Answer

Array index starts at 0 not 1. In the given program, the for loop run from 1 to 4 whereas the indexes of the array range from 0 to 3. When i becomes 4, the program tries to access an index of arr that is not present in the array and this causes the program to crash. The correct way will be to run the for loop from 0 to 3 instead of 1 to 4.

Answered By

10 Likes


Related Questions