retagged by
10,445 views
23 votes
23 votes

Consider the C program below. What does it print?

# include <stdio.h>
# define swapl (a, b) tmp = a; a = b; b = tmp
void swap2 ( int a, int b)
{
        int tmp;
        tmp = a; a = b; b = tmp;
 }
void swap3 (int*a, int*b)
{
        int tmp;
        tmp = *a; *a = *b; *b = tmp;
}
int main ()
{
        int num1 = 5, num2 = 4, tmp;
        if (num1 < num2) {swap1 (num1, num2);}
        if (num1 < num2) {swap2 (num1 + 1, num2);}
        if (num1 > = num2) {swap3 (&num1, &num2);}
        printf ("%d, %d", num1, num2);
}
  1. $5, 5$
  2. $5, 4$
  3. $4, 5$
  4. $4, 4$
retagged by

4 Answers

Best answer
33 votes
33 votes

Answer is C.

Only:

if (num1 > = num2) {swap3 (&num1, &num2);}

Statement works, which in turn swaps num1 and num2.

edited by
6 votes
6 votes

In main program num1=5, num2=4

first condition true. num1=4, num2=5

Now, second condition become true but no affect on values still num1=4, num2=5

third condition fail.

Ans: 4,5

1 votes
1 votes
the swap1( ) function does not create new variables for a and b and temp. so it changes the same a and b. so they become 4 and 5.

swap2( ) function cant change the value of a and b because it is called by value and create different a and b.

the third condition does not get satisfied. so swap3( ) is not called and values remain as 4 and 5 for a and 5 respectively.
Answer:

Related questions