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
11 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
7 Likes
Related Questions
Write a code segment to compute the sum of all positive real numbers stored in the following array.
double numb[] = new double[50];
Suppose x is an array of type int[] with 50 elements. Write a code segment that will count and print the frequency of number 42 in the array.
Declare and instantiate a one dimensional int array named evenNums with five elements. Use an initialiser list that contains the first five even integers, starting with 11.
Write a code segment that finds the largest integer in this two-dimensional array.
int data[][] = new int[5][5];