Answer of the Dry run practice program no 2 is:
0, 1, 4, 3
to see the answer on compiler add the following code before return 0:
for(int i=0; i<4; i++)
cout<<arr[i]<<" ";
Like this:
How it Worked ?
At the 6th line of the above image , array of 4 element is created by this , at 7th line loop of 4 alternation is created after that the condition is that if the index of array is divided by 2 and its remainder is compared to 0 ,if the condition become true then the index will multiply with 2. and if the remainder is not equal to 0 then it will go for else statement. so how is it working. . . . Remember !! the "i " variable which is index of the loop is integer type. so the value stored in it will be integer. so see:
arr[0]= when i is 0, at 9th line , 0/2=0 ==0 true? yes ! then 2*i (i is 0), so arr[0]= 0
arr[1]= when i is 1, at 9th line , 1/2= 0.5==0 true? nope ! then arr[i]=i (i is 1), so arr[1]= 1
why 1? because "i " is integer so the "0.5" will be neglected so 1 will be stored.
arr[0]= when i is 0, at 9th line , 0/2=0 ==0 true? yes ! then 2*i (i is 0), so arr[0]= 0
arr[1]= when i is 1, at 9th line , 1/2= 0.5==0 true? nope ! then arr[i]=i (i is 1), so arr[1]= 1
why 1? because "i " is integer so the "0.5" will be neglected so 1 will be stored.
arr[2]= when i is 2, at 9th line , 2/2=0==0 true? yes ! then 2*i (i is 2), so arr[2]= 4
arr[3]= when i is 3, at 9th line , 3/2=1.5 ==0 true? nope ! then arr[i]=i (i is 3), so arr[3]= 0
why 3? because "i " is integer so the "0.5" again will be neglected so 3 will be stored.
So that's how it's worked, if you have any question then ask in comments :)
Question of the above answer is HERE (CLICK HERE).
No comments:
Post a Comment