Swap Two Numbers in Deluge | With and Without Using a Third Variable | Beginner Friendly Tutorial

Swap Two Numbers in Deluge | With and Without Using a Third Variable | Beginner Friendly Tutorial

Deluge Script to Swap two Variables


Now, suppose you have two values, a and b, and you want to exchange values of these two variables what each one holds.

Examples of Swapping

Input : a = 5, b = 10;
Output : a = 10, b = 5


Different Methods to Swap of Two Numbers in Deluge


1. Using Third Variables or Temporary Variable

Below are the simple steps we follow: 

  1. Copy the value of 'a' into temp:temp=a
  2. Move the value of 'b' into 'a': a = b
  3. Put the saved 'temp' value back into 'b': b = temp

 // Using a third variable

temp = a;

a = b;

b = temp;

2. Without any extra Variable

Below are the simple steps we follow: 

  1. First add both variables Numbers 'a & b' and store the sum in 'a'
  2. Next,set 'b' to the value of -a that now holds a+b & subtract the old 'a'
  3. Finally,fix 'a' by subtracting the new 'b' from the current sum.

  // Without using a third variable

a = a + b;

b = a - b;

a = a - b;


Post a Comment