7                              9
int num1;                      int num2;




            The problem:
Swap the numbers contained within the two
            integer variables
7                                9
  int num1;                        int num2;




          That’s easy right?
Can’t we just swap the values; 7 get’s replaced
            with 9 and vise versa?
7                               9
 int num1;                       int num2;




          Unfortunately…
       It doesn’t quite work like that.
We can only perform one operation at a time.
7
  int num1;                        int num2;


                         9
                    So…
 We can move the value from num1 to num2.
But by doing so we lose the original value from
             num2 in the process.
7                              9
  int num1;                      int num2;




       So how do we save it?
We need to create somewhere to place the data
                 from num2.
7                                9
  int num1;                        int num2;




                   int temp;

     int temp; saves the day.
We can create a third variable, temp to act as a
 holding area to place the data from num2.
7
   int num1;                      int num2;


                     9
                   int temp;

      int temp; saves the day.
By placing the value held within num2 into temp
               we can preserve it.
7
int num1;                     int num2;


                  9
               int temp;

                 So…
Now we can move the value from num1 into
                num2
9                            7
int num1;                    int num2;




               int temp;

            And finally…
Move the contents from temp into num1
It might look like…

Swap java

  • 1.
    7 9 int num1; int num2; The problem: Swap the numbers contained within the two integer variables
  • 2.
    7 9 int num1; int num2; That’s easy right? Can’t we just swap the values; 7 get’s replaced with 9 and vise versa?
  • 3.
    7 9 int num1; int num2; Unfortunately… It doesn’t quite work like that. We can only perform one operation at a time.
  • 4.
    7 intnum1; int num2; 9 So… We can move the value from num1 to num2. But by doing so we lose the original value from num2 in the process.
  • 5.
    7 9 int num1; int num2; So how do we save it? We need to create somewhere to place the data from num2.
  • 6.
    7 9 int num1; int num2; int temp; int temp; saves the day. We can create a third variable, temp to act as a holding area to place the data from num2.
  • 7.
    7 int num1; int num2; 9 int temp; int temp; saves the day. By placing the value held within num2 into temp we can preserve it.
  • 8.
    7 int num1; int num2; 9 int temp; So… Now we can move the value from num1 into num2
  • 9.
    9 7 int num1; int num2; int temp; And finally… Move the contents from temp into num1
  • 10.