In the previous videos, you learnt how to implement loops and perform operations on strings and numbers. In this lecture, you will understand how to use loops to perform operations on arrays.
You know how to define an array. You must have used a command such as this in the past:
int[] array = {29, 34, 12, 45, 56, 02, 43, 19};
In a practical scenario, an array would be created by values input by the user. The size of the array would also be dependent on the user. Let’s now see how you can use a loop to take inputs from users.
There might be some cases in which you wish the user to input a number of elements such as strings or numbers, and store it inside an array. Now, if that array was to be of size, say 100 or 1000, then for each time you wish to insert an element in the array, you would have to write a statements like these. But inserting elements into the array a can be done using a for loop because we know that that insertion is a repetitive process. So let us see an example here. Here I'm taking a number n, which is input from the user. This n can be anything like it can be 100 or 1000 depending on how many elements the user wishes to insert into this array. Then after taking the user input n here I'm declaring a new array called Arr, which will contain integers and I define its size as being n. I have defined that they're going to be n elements inside this. Now, I start a for loop here and I say that for int I equals to zero. Notice that here I am beginning my indexing from I equals to zero because the first index of any array begins from zero. And then I say that int I equals to zero and I less than n because the last index of any array is n minus one. So the maximum point till which I is going to go is till n minus one, which is less than n. So basically that is why I have written here I less than.
Inserting elements into a large array can be a repetitive process and time-consuming.
A for loop can be used to simplify the process of inserting elements into an array.
The size of the array can be defined by taking user input.
The for loop starts with an index of 0 and goes up to n-1 (the last index of any array).
The loop simplifies the process of inserting elements into an array of any size.
So you learnt how it is possible to create an array using loops. Let us now dive deeper into how this happens.
What you basically did was you traversed through all the indices from 0 to (arraysize) and took the input for each index.