In: Computer Science
C++ CLion
using Namespace std
Draw a picture of the array that would be created by the following code
int data[10] = {1, 1};
for( int index = 2; index < 8; ++index )
data[ index ] = data[index – 1] + data[index – 2];
int data[10] = {1, 1}; // will create an array of int
data of size 10 where the first 2 elements i.e index 0 and 1 will
have value 1 and other locations will have value of 0 (since by
default integer variables are set to 0 in C++)
data[0] = 1
data[1] =1
data[2] ... data[9] = 0
// loop that starts from 2 and continues till index
7 (inclusive)
for(int index = 2; index < 8; ++index)
data[index] = data[index-1] +
data[index-2]; // sets data at index to sum of values of data at
index-1 and index-2
The above loop iterations :
1st Iteration, index = 2,
data[2] = data[1] + data[0]
= 1 + 1 = 2
2nd Iteration , index = 3
data[3] = data[2] + data[1]
= 2 + 1 = 3
3rd Iteration , index = 4
data[4] = data[3] + data[2]
= 3 + 2 = 5
4th Iteration , index = 5
data[5] = data[4] + data[3]
= 5 + 3 = 8
5th Iteration , index = 6
data[6] = data[5] + data[4]
= 8 + 5 = 13
6th Iteration , index = 7
data[7] = data[6] + data[5]
= 13 + 8 =21
7th Iteration , index = 8
Since index = 8 , it exits the loop
After the loop, array:
array = {1,1,2,3,5,8,13,21,0,0}
After the execution of above code the array will look like:
1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 0 | 0 |