214 views
7 7 votes

What is the output of the following code?

#include <stdio.h>

void change(int *p, int *q) {
    *p = *p + 4;
    *q = *p + *q;
    p = q;
    *p = *p - 3;
}

int main() {
    int a = 6, b = 10;

    change(&a, &b);

    printf("%d %d", a, b);

    return 0;
}
  1. $\texttt{10\ 17}$
     
  2. $\texttt{10\ 20}$
     
  3. $\texttt{6\ 17}$
     
  4. $\texttt{13\ 17}$

1 Answer

0 0 votes

Initially, $\texttt{a = 6}$ and $\texttt{b = 10}$.

The function call is $\texttt{change(\&a, \&b)}$.

Inside the function, pointer $\texttt{p}$ points to $\texttt{a}$ and pointer $\texttt{q}$ points to $\texttt{b}$.

The statement $\texttt{*p = *p + 4}$ changes $\texttt{a}$.

So, $\texttt{a = 6 + 4 = 10}$.

The statement $\texttt{*q = *p + *q}$ changes $\texttt{b}$.

Here, $\texttt{*p = 10}$ and $\texttt{*q = 10}$.

So, $\texttt{b = 10 + 10 = 20}$.

Now, $\texttt{p = q}$ means local pointer $\texttt{p}$ starts pointing to $\texttt{b}$.

The statement $\texttt{*p = *p - 3}$ changes $\texttt{b}$.

So, $\texttt{b = 20 - 3 = 17}$.

Final values are $\texttt{a = 10}$ and $\texttt{b = 17}$.

Therefore, the output is $\texttt{10\ 17}$.

Answer: A.

Answer:
Position:
Show:

Related questions

7 7 votes
1 1 answer
221
221 views
GO Classes asked Jun 6
221 views
What is the output of the following code?#include <stdio.h int main() { int a = 8, b = 12; int *p = &a; int *q = &b; *p = *p + *q; q = p; *q = *q - 5; printf("%d %d", a, ...
7 7 votes
1 1 answer
206
206 views
GO Classes asked Jun 6
206 views
What is the output of the following code?#include <stdio.h void fun() { static int x = 3; int y = 2; x = x + y; y = y + x; printf("%d ", x); } int main() { fun(); fun(); ...
8 8 votes
1 1 answer
203
203 views
GO Classes asked Jun 6
203 views
What is the output of the following code?#include <stdio.h int main() { int i, j, count = 0; for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { if (i * j 6) break; co...
7 7 votes
1 1 answer
187
187 views
GO Classes asked Jun 6
187 views
What is the output of the following code?#include <stdio.h int calc(int n) { if (n == 1) return 2; return n + calc(n - 1); } int main() { printf("%d", calc(4)); return 0;...