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:
- Initial value.
- 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.
- 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.