We usually use loops to read from or write to an array. Let’s revise something from the previous lesson. To set elements of an array, we use
arrayName[index] = value ;
and to read those values, we use
output = arrayName[index] ;
So, if we use a loop to cycle through that index, we will be able to access all the elements with less code.
Size of an array:
Before starting, let’s learn how to determine the size of an array programatically. We use the .length parameter with the array name to determine its size (or the capacity).
int size = arrayName.length ;
The index of an array starts from zero. It means that if we have an array of length 5, it will have indices 0,1,2,3,4 only. No 5 index. Because if we start counting 0 1 2 3 4, we actually counted 5 numbers. This is where the following joke comes in:
So we have to write a loop that starts from zero and ends at one less than the size of the array. Let’s take an example for that:
Now let’s take another example in which we will input some numbers from the user into an array.
We learnt about storing and retrieving the elements of an array. Now let’s dive into more practical examples. We will write a program that will input some numbers from the user and display their sum on the screen.
- Write a program to input some numbers from the user and display the smallest on the screen.
- Write a program to input some numbers from the user and display the even numbers among them on the screen.