0

Simply by interchanging the numbers in printf I.e,

  1. printf("before swap:First Var.=%d\tSecond Var.=%d\n" ,i,j);
    9.printf("After Swap: First Var.d\n" ,j,i);
6
Contributors
8
Replies
68
Views
3 Years
Discussion Span
Last Post by Ancient Dragon
0

OK, but nothing was swapped. A swap of values doesn't mean simply reordering the variables in the print statement.

0

1.printf("beforeswap:FirstVar.=%d\tsecondVar.=%d\n",i,j); 9.printf("AfterSwap:FirstVar.=%d\secondvar=%d\n",j,i);

Sir,this is not reordering,but assigning values in different way,by this the variable values get swapped.

0

@charishma: What you do is swapping by printing two variables on the screen. You do not swap their values in memory.

0

Yes, I too accept sir,but in this program we just need output I.e.,swapping but I think there is no use of memory in this program output

1

If you actually have to swap them, there are ways to do it without using any more variables. My favourite is this:

i ^= j;
j ^= i; 
i ^= j; 

Edited by Moschops

2

I will show you how to swap numbers.
void main()

{


int x, y;
clrscr();
printf("Enter two positive numbers");
scanf("%d%d",&x,&y);
y=y+x;
x=y-x;
y=y-x;
printf("The swapped numbers are %d and %d",x,y);
getch();
/* Comments: Let x=3 and y=4;
    so y=x+y will give y= 3+4 y=7 x=3
    x=y-x will give x = 7-3 x=4 y=7
    Finally y=y-x will give y= 7-4 y=3 x=4
*/


}
Votes + Comments
great!
0

Yes sir,swap 2no.s with memory then I go with your method but just swap means I will go with my method because it has less no. of statements

2

I will go with my method because it has less no. of statements

That's a poor reason not to use his code. If you post the exact assignment I'm willing to wager that your instructor wants you to swap the variables in memory, not just on the console screen.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.