Page 287 - Cs_withBlue_J_C11_Flipbook
P. 287
The output of the preceding program is as follows:
Enter marks 45
Enter marks 65
Enter marks 98
Enter marks 74
Enter marks 95
Enter marks 68
Enter marks 79
Enter marks 85
Enter marks 94
Enter marks 82
45, 65, 98, 74, 95, 68, 79, 85, 94, 82,
Total: 785 and Average: 78.5
In Program 1, we could see that more variables had to be created and the nextInt() method had to be called 10 times.
On the other hand, in Program 2, when we are applying an array, the size of the array is declared as required and only
the ‘for’ loop is executed 10 times for the calculation.
Thus, the advantage is that if the number of values to be taken is increased, then only the size of the array will be
increased along with the ‘condition’ portion of the loop, i.e., in this case, i<10 whereas in the first program more
variables had to be created for the same purpose.
So, using an array is definitely helpful when we have a large number of values (of similar data type) to be declared.
In the above programs, the numbers are stored in an array of int data type.
ar[ ] = Array to store integer numbers(Data type: int)
n[0] n[1] n[2] n[3] … ….. …. …. n[9]
45 65 98 74 … …. …. …. 82
Arrays are basically of two types. They are as follows:
• Single dimensional array
• Double dimensional array
11.3 SINGLE-DIMENSIONAL ARRAY
Two or more elements arranged row-wise containing separate subscript values indicating the position of the element
is known as a single-dimensional array or 1D array.
Let us understand how an array stores its elements in the memory. For example, a single-dimensional array car[ ] of
size 5 of String data type is as shown below:
0 1 2 3 4
car[ ] Maruti Ford Hundai Honda Tata
In the above example, the name of the array is car and 0,1,2, 3, 4 are the index positions of the elements. So, the 1st
element is referred to as car[0] containing the data Maruti, the 2nd element is referred to as car[1] containing the
value Ford, and so on.
Note: The index of the array always begins with 0 (zero).
285
Arrays 285

