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.
Now let's write a program to input some numbers from the user and display the greatest among them on the screen. Now let's first develop a logic. We will pick the first element of the array and store it in the variable named great. Then we will compare it with the second value in the array and if the second value is greater than great, that value will be stored in great. In this way the great will be compared to all other values in the array and at the last we will have the largest value in the great.
Practice Corner:
- 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.
0 Comments
Thanks for leaving a comment. I will try to reply you soon.