465 views

Consider the following program

int find (int n)
{
int 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;
}

The value returned by find (9) is ______ .

$\sum_{i=1}^{n}\sum_{j=1}^{i}\sum_{k=1}^{j}1 = \sum_{i=1}^{n}\sum_{j=1}^{i}j = \sum_{i=1}^{n}(i*(i+1)) /2 = 1+3+6+10+15+21+28+36+45 = 165$

Now, initial value of a was 1. Now a value incremented 165 times by 1. So final ans = 1+165 = 166

//https://ide.geeksforgeeks.org/bo7T4PnEfn (If you want to check)

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

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

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

Yes @Shaik Masthan sir this is also one way to do this.

Nested For loop:

I=1     I=2      I=3      I=4……………………………  I=8    I=9

J=1     J=2     J=3     J=4…………………………… J=8   J=9

K=1    K=2    K=6      K=10………………………… K=36  K=45

Sum of all these you will get: 165

So now value of a increasing linearly with variable K. Now a=165+1 =166

Ans: 166

1
373 views