‹ Back to the paper
The following functions are a part of some class: void Try(char ch[],int x) {…
The following functions are a part of some class:
void Try(char ch[],int x)
{ System.out.println(ch); char temp;
if ( x<ch.length/2)
{ temp=ch[x];
ch[x]= ch[ch.length-x-1];
ch[ch.length-x-1] = temp;
Try(ch,x+1);
} }
void Try1(String n)
{ char c[]=new char[n.length()];
for(int i=0;i<c.length;i++)
c[i] = n.charAt(i);
Try(c,0);
}(a)[2.0]
What will the output of Try( ) when the value of ch[]={‘P’, ‘L’,‘A’, ‘Y’} and x=1?
(b)[1.0]
What will the output of Try1( ) when the value of n=”SKY”?
Answer
Answer (a)
AIOutput:
PLAY
PALY
(Verified by running the code.) Try(ch,1) first prints the array as given: PLAY. Since $x(1) < ch.length/2 (=2)$, it swaps ch[1] and ch[4-1-1]=ch[2], i.e. swaps 'L' and 'A', giving PALY, then calls Try(ch,2). This call prints the array again: PALY. Now $x(2)$ is not $< 2$, so the if-block is skipped and the recursion stops.
Answer (b)
AIOutput:
SKY
YKS
Try1("SKY") copies the string into a char array and calls Try(c,0), which first prints SKY. Since $0 < 3/2 (=1)$, it swaps c[0] and c[3-0-1]=c[2], i.e. 'S' and 'Y', giving YKS, then calls Try(c,1), which prints YKS. Now $x(1)$ is not $<1$, so the recursion stops.
From ISC 2024 Specimen Computer Science Paper 1, question 2(iii).