in Programming in C retagged by
10,546 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$
in Programming in C retagged by
10.5k views

4 Answers

33 votes
33 votes
Best answer

Answer is C.

Only:

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

Statement works, which in turn swaps num1 and num2.

edited by

4 Comments

The following code might help someone understand the swapping using macro expansion

https://onlinegdb.com/si4b0N8Ec
0
0

Hi, could you kindly give a detailed explanation ? I could not understand the solution. Not even from the comments am I clear.

5>4. So 1st condition is true !. Macro swaps so the 2nd cond is also true ! swap2 only changes adress so no change. 3rd cond is true and finally this gives us (5,5)…..

I understand my answer is wrong.
Could you kindly correct my mistakes?

0
0
Bhai,I am not getting this swapping by macro

How it is been performed???
0
0
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

4 Comments

You are wrong bro, only swap3 will be satisfied not swap1 or swap2 if statement. You can run this code on gcc c compiler with/without swap3 if statement..
0
0
Can you please explain why 1st condition is not true ?
0
0

Is 5<4???? @KunuSwavik

0
0
1 vote
1 vote
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.

1 comment

Swap 1 is executing before the birth of a,b ... Then how it changes the *same a and b* ?
1
1
0 votes
0 votes

Here is my approach:

 

 

Answer:

Related questions