in Programming in C edited by
368 views
2 votes
2 votes

Consider the below function:

int s (int n)
{
if (n<=1) return 1 ;
n = (n-1) * (n-1) -2 - n * n + 3*n ;
s(n);
printf(“%d”, n );
}

What is the output if initial call is $s(6)$ ?

  1. $55555$
  2. $11111$
  3. $54321$
  4. $12345$
in Programming in C edited by
by
368 views

1 comment

n=(n-1) *(n-1) -2 -n*n+3*n

simplifying this

 n=(n-1)^2 -n^2 +3n-2

n= (n^2 -2n +1) -n^2 +3n -2

n= n-1

hence s(n-1) will be called every time
0
0

1 Answer

3 votes
3 votes
Best answer
Correct option is (D).

s(6) =  (6-1)^2 -2 - 6^2 + 3*6  = 5 and before printf, s(5) is called.

s(5) =  (5-1)^2 -2 - 5^2 + 3*5  = 4 and before printf, s(4) is called.

s(4) =  (4-1)^2 -2 - 4^2 + 3*4  = 3 and before printf, s(3) is called.

s(3) =  (3-1)^2 -2 - 3^2 + 3*3  = 2 and before printf, s(2) is called.

s(2) =  (2-1)^2 -2 - 2^2 + 3*2  = 1 and before printf, s(1) is called.

s(1) will simply return and won't print anything.

Therefore, printf will be executed in reverse order, i.e. s(2)->s(3)->s(4)->s(5)->s(6)

Hence, output = 12345.
selected by

1 comment

@aiswarya, ^ operator is bitwise XOR and not power operator. I goes you have answered considering it as power operator. Please correct me in case I am wrong. Thanks.
1
1
Answer:

Related questions