in Programming in C
761 views
3 votes
3 votes

Need some clarification regarding this answer Do comment please:
 

in Programming in C
761 views

4 Comments

@saxena0612

The question is not asking the number of times d = d + 1 is executed.Question says to find the number of additions preformed by code.So you need to consider all additions ( ++i,++j,++k,i+j+k,d=d+1).

Total Number of execution of  ++i , ++j and ++k add to 8000. Expression 

if( ( (i+j+k) %2 ) ==0 ) is also executed 8000 times but it has two additions.So another 16000 addition due to this. d = d +1 will contribute 4000 additions as you mentioned.So total of 28000 addition.

But the given answer is 28420 .I don't know where that 420 additions are coming from.Either I am missing something/doing something wrong or that j=1 in j for loop should have been j =0.

Note- there is a parenthesis miss match in the if statement.

0
0
i incrementing 20 times, j 400 times and k 8000 times.
0
0

yes.Got it now

Total Number of execution of  ++i , ++j and ++k add to 8000

should be 8420 

0
0

1 Answer

8 votes
8 votes
Best answer

There are $6$ instances of addition

  • $i++$
  • $j++$
  • $k++$
  • $i+j(\text{let it be s})$
  • $s+k$
  • $d+1$

We have to count how many times each of them is calculated.

d=d+1

First of all we will calculate number of additions of $d+1$, it will on the other hand signify the overall time complexity of the code.

it will be $\frac{n \times n \times n }{2}=O(n^3) \Rightarrow \frac{20 \times 20 \times 20 }{2} =4000$


i+j+k

Number of addition =$2 \times n \times n \times n=16000$


i++

$20 \text{times}$


j++

$20 \times 20=400\text{times}$


k++

$20 \times 20 \times 20=8000\text{times}$


Total number of additions$=4000+16000+20+400+8000=28420$

selected by

5 Comments

Thanks !
1
1
The loop increment for first loop variable i should happen 21 times as last will result in failure condition?Same for j and k?
0
0
$\text{No Rahul :you are missing a point that i,j,k will bot be increamented  when }i=1,j=1,k=1 $
0
0
Got it.thank you!!Nice observation
0
0
You are welcome rahul :)
0
0

Related questions