in Programming in C edited by
714 views
6 votes
6 votes
int find(int n) {

    int i, j, k, a = 1;

    for (i = 1; i <= n; i++)

        for (j = 1; j <= i; j++)

            for (k = 1; k <= j; k++)

                a = a + 1;

    return a;
}

What will be the value of find$(10)$?

in Programming in C edited by
714 views

4 Answers

15 votes
15 votes

Answer: 221

Iterative approach for this question is very slow and error prone. Instead we’ll try to formularize it.

for (i = 1; i <= n; i++)
  for (j = 1; j <= i; j++)
    for (k = 1; k <= j; k++)
      a = a + 1;

Here we can infer that for each iteration of k, a is incremented once

And for each iteration of ‘j’, ‘a’ is incremented by whatever iteration the ‘k’ loop runs for. So we can derive a summation formula for it.

$result=\sum_ {i=1}^n\sum_ {j=1}^i \sum_ {k=1}^j1$

$result=\sum_ {i=1}^n\sum_ {j=1}^i j$

The innermost summation now is the sum of ‘i’ natural numbers defined by ‘j’

$result=\sum_ {i=1}^n \frac {i*(i+1)} {2} = \frac {1} {2} \sum_ {i=1}^n{(i^2+i)} = \frac {1} {2} \sum_ {i=1}^n{i^2} + \frac {1} {2} \sum_ {i=1}^n{i}$

$result=\frac {1}{2}\frac {n(n+1)(2n+1)}{6} + \frac{1}{2} \frac{n(n+1)}{2}$

Putting n = 10

$result=\frac {1}{2}\frac {10(11)(21)}{6} + \frac{1}{2} \frac{10(11)}{2}$

$result=\frac {1}{2}\frac {10(11)(21)}{6} + \frac{1}{2} \frac{10(11)}{2} = \frac {1}{2}(440) = 220$

Initial value of ‘a’ was 1 hence a = 221.

 

Points to remeber:

  1. Initial value.
  2. Limits of loop: since here it was <=, not just <. If it were just < then the upper limit for summation would have reduced by 1 and needed to be solved accordingly.
  3. Block of “for loop”:  if no curly braces are given to explicitly define the body of loop then the following/next line would be considered as body of the loop. But here the following line is a (k) loop itself so that (k) loop plus (k) it's body will be considered as the body of outer (j) loop.

 

1 comment

beautiful answer bro.
2
2
6 votes
6 votes

Answer: 221

Initially $a=1$,

When $i=1$, we will add $1$ to $a$

When $i=2$, we will add $1+2$ to $a$

similarly, $i=3$ we will add $1+2+3$ to $a$ 

$...$

when $i=10$, we will add $1+2+3+...+10$ to $a$

Now adding them all we will get

$a = 1 + 1 + 1 + 2 + 1 + 2 + 3 + … + 9 + 10$,

if we look carefully we will notice that $1$ is added 10 times, $2$ is added 9 times, $3$ is added 8 times, … , $10$ is added 1 time.

Therefore $a = 1 + (1*10) + (2*9) + (3*8) + … + (9*2) + (10*1) = 221$ 

by
3 votes
3 votes

when i=1 updation will be done 1 time,

when i=2 updation will be done 1+2 time

when i=3 updation will be done 1+2+3 time

when i=n updation will be done 1+2+3+… n time

so total time updation =(1)+(1+2)+(1+2+3)+(1+2+3+4)+(1+2+3+4+..n)

and the sum of this series is (n)(n+1)(n+2)/6

in our case n=10 so total 220 time updation will be done ,initially a=1 is given so the answer will be 220+1 which is 221.

1 vote
1 vote

This is how I worked out the problem.

Answer:

Related questions