Consider the following array: int[] a = { 3, 5, 2, 2, 4, 7, 0, 8, 9, 4 }; What are the contents of the array a after the following loops complete? (show how you arrive at the answer)
a) for (int i = 1; i < 10; i++) { a[i] = a[i - 1];
b) for (int i = 9; i > 0; i--) { a[i] = a[i - 1]; }
Given, Asked to solve and explain logical code where an array is given with some pre-defined value and 2 questions with different iteration logic.
[Answer]
a) for (int i = 1; i < 10; i++)
{
a[i] = a[i - 1];
}
For this part as we can see in code that in for loop we are iterating the value from 1 to 9 which is the total index of array a. Inside loop we are exchanging the value of previous element with current one.
Also we can notice that we started loop with index 1 but array stores the value from index 0.
Therefore, a[i] = a[i-1] => a[1] = a[0] (a[i-1] => a[0] => 3) and hence the value of current index will be changed with value 3.
Same happened in next iteration when i=2
a[i] = a[i-1] => a[2] = a[2-1] => a[2] = a[1] (a[1] in previous iteration we got the value 3. So again the value 3 will go inside the current index of a)
Same exchange of value will continue will loop ends and all the array value will be changed to 3.
Output:
b) for (int i = 9; i > 0; i--)
{
a[i] = a[i - 1];
}
As we already saw how the data got exchange as we took the previous element in loop.
Here, in this, code the iteration starts from the max length of array that means here we are exchanging the value of current one with previous in descending order as index.
When i=9: a[i] = a[i-1] => a[9] = a[9-1] => a[9] = a[8] => a[9] = 9
Therefore, the value 4 which was there in a[9] will be changed to value in a[8] which is 9.
Again when i=8: a[i] = a[i-1] => a[8] = a[7] =>a[8] = 8
Hence, we can see the pattern that the array is shifting values by 1.
For the value when i=1: a[i] = a[i-1] => a[1] = a[0] => a[1] = undefined(no value in array)
So the array will omit one of the end value and print rest.
Output:
Please let me know in the comments if you need more help in this.
Get Answers For Free
Most questions answered within 1 hours.