375 views
8 8 votes

What is the output of the following code?

#include <stdio.h>

void update(int n, int *p) {
    if (n <= 0)
        return;

    *p = *p + n;

    update(n - 2, p);

    *p = *p + n;
}

int main() {
    int x = 1;

    update(5, &x);

    printf("%d", x);

    return 0;
}

3 Answers

1 1 vote

Here, pointer $\texttt{p}$ points to $\texttt{x}$.

So, every change made using $\texttt{*p}$ directly changes the original variable $\texttt{x}$.

Initially, $\texttt{x = 1}$.

The call is $\texttt{update(5, \&x)}$.

In $\texttt{update(5)}$:

$\texttt{*p = *p + 5}$

So, $\texttt{x = 1 + 5 = 6}$

Then it calls $\texttt{update(3, p)}$.

In $\texttt{update(3)}$:

$\texttt{*p = *p + 3}$

So, $\texttt{x = 6 + 3 = 9}$

Then it calls $\texttt{update(1, p)}$.

In $\texttt{update(1)}$:

$\texttt{*p = *p + 1}$

So, $\texttt{x = 9 + 1 = 10}$

Then it calls $\texttt{update(-1, p)}$.

Since $\texttt{n <= 0}$, it returns immediately.

Now returning starts.

Back in $\texttt{update(1)}$:

$\texttt{*p = *p + 1}$

So, $\texttt{x = 10 + 1 = 11}$

Back in $\texttt{update(3)}$:

$\texttt{*p = *p + 3}$

So, $\texttt{x = 11 + 3 = 14}$

Back in $\texttt{update(5)}$:

$\texttt{*p = *p + 5}$

So, $\texttt{x = 14 + 5 = 19}$
 

$\therefore$ Output : $\boxed{19}$

edited by
Answer:
Position:
Show:

Related questions

6 6 votes
2 2 answers
318
318 views
GO Classes asked Jun 17
318 views
What is the output of the following code?#include <stdio.h int fun(int n) { int x = n; if (n <= 0) return 0; x = x + 2; return x + fun(n - 2); } int main() { printf("%d",...
6 6 votes
2 2 answers
248
248 views
GO Classes asked Jun 17
248 views
What is the output of the following code?#include <stdio.h int fun(int n) { if (n <= 0) return 1; if (n == 1) return 2; return fun(n - 1) + 2 * fun(n - 2); } int main() {...
6 6 votes
2 2 answers
333
333 views
GO Classes asked Jun 17
333 views
How many times is $\texttt{fun()}$ called when the following code is executed? (Count the first call also).#include <stdio.h int fun(int n) { if (n <= 1) return 1; return...
6 6 votes
3 3 answers
325
325 views
GO Classes asked Jun 17
325 views
What is the output of the following code?#include <stdio.h int fun(int n) { if (n <= 1) return n + 1; if (n % 2 == 0) return fun(n - 1) + fun(n - 2); return fun(n - 2) + ...