[artofprogramming] Re: swap

  • From: Krupa Sivakumaran <krupa32@xxxxxxxxx>
  • To: artofprogramming@xxxxxxxxxxxxx
  • Date: Mon, 23 Sep 2019 10:38:29 +0530

Cool. Hope everyone understands the three lines.
If not, pls ask in the group (there may be others too).

Now, to the third level.
Will this code always work? The answer is no.
The question is... when will this code fail to swap?

On 9/22/19, Fiddle the Second <khyati.gupta267@xxxxxxxxx> wrote:

#include<iostream.h>
#include<conio.h>
void main()
    {
          clrscr();
          int a = 5, b = 8;
          cout<<"A = "<<a<<"\nB = "<<b;
          a = a + b;
          b = a - b;
          a = a - b;
          cout<<"\nSwapped values: ";
          cout<<"\nA = "<<a<<"\nB = "<<b;
          getch();
}


On Sun, Sep 22, 2019, 10:12 PM Krupa Sivakumaran <krupa32@xxxxxxxxx> wrote:

Thanks Khyati and Prishita.
Both are correct. I would recommend to use 'temp' as the name, as it
reflects the nature
of its use - a temporary place.

Now, for the second level.
How do you do this WITHOUT using a third variable?

On 9/22/19, Prishita Raj <raj.prishita@xxxxxxxxx> wrote:
a=5
b=8

c=a
a=b
b=c

Print a
Print b

On Sun, Sep 22, 2019, 1:16 PM Krupa Sivakumaran <krupa32@xxxxxxxxx>
wrote:

Yes. Whoever knows the solution can post it.
Thats what the group is for.
Make some noise.

On 9/20/19, Krupa Sivakumaran <krupa32@xxxxxxxxx> wrote:
Here is the first programming question to the group.

Given two numbers a and b with values 5 and 8, write a program to
swap
the values of
a and b, and print them. That is, a should be 8 and b should be 5
after the swap.








Other related posts: