Consider the following algorithm. ``` x <-- 1 for i is in {1, 2, 3} do for j is in {1, 2, 3, 4} do x <-- x + x for k is in {1, 2, 3, 4, 5} do x<-- x + 1 x <-- x + 5 ``` Count the number of + operations done by this algorithm.
any ideas ?
you may wrap your code between ``` and ``` for highlighting the syntax
No very well familiar with this subject
for each value of i, you do the j loop. the j loop does 4 executions. the i loop does all of that 3 times. so 3*4= 12 times for both. you do 1 add inside the i, j loops, so 12 adds for that part.
the indenting matters (a lot). According to the indenting, the k loop is independent of the i,j loops. So you do that one separately. How many adds for the k loop? finally, the last statement is not in any loop. You do it once (so it does 1 last add)
15 for k loop
you would get 15 for k loop only if the k loop was "inside" the i loop. But according to the indentation, the k loop is not inside the i loop. if the k loop statement was indented 2 spaces, it would be inside the i loop. if it was indented a total of 4 spaces, the k would be inside both the i and j loops.
so what loop is it in
so i guess it is in the k and i loop
the k loop is at the same level as the i loop the logic is: do the i loop (which involves also doing the j loop) when that is done, do the k loop when that is done, do the last statement
Can anyone explain this problem to me
x <-- 1 for i is in {1, 2, 3} do for j is in {1, 2, 3, 4} do x <-- x + x end j for k is in {1, 2, 3, 4, 5} do x<-- x + 1 x <-- x + 5 end k end i I added "end statements" to show where the control of each loop ends the i loop is executed 3 times. that means everything "inside" it is executed 3 times the j loop is executed 4 times. that means the statement x<-- x+x is performed 4 times, and then the j loop ends. But because we are inside the i loop, we will do the j loop 3 times, and the x<-- x+x will be executed 3*4= 12 times. (so 12 adds) after the j look ends, the k loop is started. It goes 5 times. That means the 2 statements "inside" the k loop are executed 5 times. Because we are inside the i loop, the statements inside the k loop will be done 3*5=15 times total. There are 2 statements , and 2 adds, so 30 adds will be performed. total adds will be 30+12= 42
the flow will go: for i=1 do j loop (which means for j=1 , up to j=4, do x<-- x+x) (we do 4 adds) then do the k loop (we do x<-- x + 1, x <-- x + 5 (2 adds), and we do them 5 times (for each value of k from k=1 to k=5). we do 10 adds we get to the end of the i loop, having done 14 adds we now do the i loop, with i=2. we end up doing another 14 adds finally, we do the i loop with i=3, and another 14 adds after i=3, the i loop is complete and we are done total adds: 14+14+14= 42 adds
Join our real-time social learning platform and learn together with your friends!