Iterating & Updating Arrays
Iterating Arrays
In the last post, we learned what arrays are and how we can create, initialize and access an array. For accessing array elements we printed every element of array one by one manually.
Something like this!
Now suppose the size of array is 100 and I need to print all the elements of array. No way, I am going to access and print all elements from the first to the hundredth position. What's the solution then? LOOPS!
Observe that to access any element at position i, we print the expression arr[i]
and this i ranges from 0 to n -1 (indices of array arr) where n is the size of array. Hence we can run a loop on i from 0 to n-1 and print the array element at the corresponding index i.
Example
Let's solve the same problem using a for loop.
Output
1
2
3
4
5
It's clearly visible that accessing elements via loops is simpler and more efficient for any array size.
Quiz 1
What is the output of the following code?
Quiz 2
What is the index number for element 97 in the following array?
Updating Array elements
Suppose I create an array as
But now I want to change the element at index 3 (7) to some other value say 16. In other words, I need to update my array arr
to {11, 9, 2, 16, 5}
. Should I create a new array? No way!
So let's see how can we update the same array arr
according to our requirements.
Output
11
9
2
16
5
Here, arr[3] = 16;
changes the value of the fourth element to 16.
Quiz 3
What is the output of the following code?
Quiz 4
We are given an array arr as:
How can we change the first element of this array to 200?
Problem
Now let's solve a problem and apply the concepts that we covered till now!
Problem Statement
- Create a
double
type array namedarr
with values: 2.7, 4.3, 12.8, 5.4 - Print the array values in separate lines
- Update the 2nd and 4th element to 3.7 and 6.6 respectively
- Print the array values in separate lines
Solution
I hope you learned and enjoyed all the concepts of arrays done till now. We'll meet with a few more in the upcoming articles.
Happy learningπ
Join Our Course

Offer ends in:
Days
Hours
Mins
Secs