Consider the following function int mystery3 int nint s 0 f
Solution
i) The loop will runs based on the n value which we have given to the function mystery3(int n).it is nothing but n !(factorial).
let us say the value of n=3; nothing but 3 != 3*2*1 =6
ii) then the first loop which having variable \" i \" will run 3 times.
and the second loop which having variable \" j \" will runs based on \" i \" value.
i.e., while running first time of first loop(i value = 1 ) , second loop(which having j) will run for 1 time.
while running second time of first loop(i value = 2 ) , second loop(which having j) will run for 2 times.
while running third time of first loop(i value = 3 ) , second loop(which having j) will run for 3 times.
so the answer will be s = 6 ;
explaination:
s + = ci which means s=s+ci;
so while terminating the second loop for the first time (i = 1) \" ci \" value will be \' 1 \'.====> s = s + ci (ci= 1 ) . now the s value will be \' 1 \' because initially s is assigned with \' 0 \'.
while terminating the second loop for the second time (i = 2) \" ci \" value will be \' 2 \'.====> s = s + ci (ci= 2 ) . now the s value will be \' 3 \'. because for the value of s is \' 1 \' due to above explaination.
while terminating the second loop for the third time (i = 3) \" ci \" value will be \' 3 \'.====> s = s + ci ( ci=3 ) . now the s value will be \' 6 \'. because for the value of s is \' 3 \' due to above explaination.
iii ) yes there is a better way of the given function ( mystery3 ).
i.e., int mystery3 (int n)
{
s=0;
for ( int i = 1 ; i<=n; i ++ )
s + = i ;
return s ;
}
the reason behind to say better than given function is:
Here in this 1 loop is avoided and it is giving big plus point that the loop will runs n times only(execution will be fast), but not as like given function ( n ! ) and also the we used the less variables compare to the given function.
