Actually the sample code in 1 is very clear. It loops from 'a' to 'z', and putchar
prints xxx
, which should result from a
to z
. By the way, the number 1 code in proper form is this:
char c='a';
while(c++<='z') // c is incremented
putchar(xxx); // lets say xxx is declared as char earlier
In 1, c
is added by one already after it is being checked and just before it is printed (since post increment is done after everything in the line is done). So let's say c = 'a'
. Is c
less than or equal to z
? Since it is, putchar()
will be done, but before that, c
is incremented, (c++
) so the old value a
will be b
. So in order to print 'a'
(the old value), you will print c - 1
('b' - 1
), which is 'a'
.
So xxx = c - 1
.
In question number 2, (a)
is definitely not the answer.
Tracing recur()
:
// if recur(11)
recur(int num) {
// num = 11, 11 / 2 is not 0
if ((num / 2) != 0)
// since num / 2 is not 0 because 11 / 2 = 5.5,
// num will be (num / 2) since (num / 2) is passed as the new parameter
// return(recur(5.5) * 10) + 5.5 % 2);
// then repeat until num / 2 = 0
// then compute the returns, (return_value * 10 + num % 2)
return (recur(num / 2) * 10 + num % 2);
else
return 1;
}
This is how the values are changed:
num: 11.00
num / 2: 5.50
num: 5.00
num / 2: 2.50
num: 2.00
num / 2: 1.00
num: 1.00
num / 2: 0.50
return: 10
return: 101
return: 1011
final return: 1011