PRASHNIKAप्रश्निका
Back to the paper

The following function is a part of some class which computes and returns the value of a number ‘p’…

Computer Science20243 marksFill in
The following function is a part of some class which computes and returns the value of a number ‘p’ raised to the power ‘q’ ($p^q$). There are some places in the code marked by ?1? , ?2? , ?3? which must be replaced by an expression / a statement so that the function works correctly.
double power ( double p , int q )
{   double r = ?1? ;
    int c = ( q<0 ) ? -q : q ;
    if ( q == 0)
        return  1 ;
    else
    {   for (int i = 1; i <= c ;?2?, i++);
        return (q>0)? r : ?3?;
    }
}
(a)[1.0]
What is the expression or statement at ?1?
(b)[1.0]
What is the expression or statement at ?2?
(c)[1.0]
What is the expression or statement at ?3?

Answer

Answer (a)

AI
?1? is `1` (i.e. `double r = 1;`), so that r is initialised to the multiplicative identity before it is repeatedly multiplied by p to build up $p^c$.

Answer (b)

AI
?2? is `r = r * p` (the loop reads `for (int i = 1; i <= c; r = r * p, i++);`), so that r is multiplied by p once for each of the c iterations, accumulating $r = p^c$. (Verified: for p=2, q=3, this correctly gives r=8.0.)

Answer (c)

AI
?3? is `1 / r`, so that when q is negative the function returns the reciprocal of $p^{|q|}$, i.e. $p^{q} = 1/p^{|q|}$. (Verified: for p=2, q=-2, r becomes 4.0 and the function correctly returns 0.25.)
Implementation of algorithms to solve problems

From ISC 2024 Specimen Computer Science Paper 1, question 2(iv).