‹ Back to the paper
Question 2(iii)
3 marks
Computer ScienceISC 2023 Specimen Computer Science Paper 1Case basedMethods
Answer the questions on the code given below.
void Solve(int n) { int a=1,b=1; for (int i=n;i>0;i=i/10) { int d=i%10; if (d%2==0) a=a*d; else…
void Solve(int n)
{ int a=1,b=1;
for (int i=n;i>0;i=i/10)
{ int d=i%10;
if (d%2==0)
a=a*d;
else
b=b*d;
}
System.out.println(a+" "+b);
}With reference to the code given below answer the questions that follow.
(a)[2]
What will the function Solve( ) return when the value of n=3269?
(b)[1]
What is the method Solve( ) computing?
Answer
Answer (a)
Solve() is void, so it returns nothing, but it displays "12 27" (verified by running the code for real).
Dry run for n=3269: i=3269, d=9 (odd) -> b=1*9=9; i=326, d=6 (even) -> a=1*6=6; i=32, d=2 (even) -> a=6*2=12; i=3, d=3 (odd) -> b=9*3=27; i=0, loop ends.
Output: 12 27
Answer (b)
Taking the digits of n one at a time (from the units digit upward), the method computes the product of all the even digits (stored in a) and, separately, the product of all the odd digits (stored in b), and then displays both products.