13_8_4_3_2_1's blog

By 13_8_4_3_2_1, 9 years ago, In English

(I'm too much infant in case of coding. I'm just writing a blog just out of curiosity)

We know the process of swapping two variables.

Let's 1st talk about a very easy process.

(Swapping with the help of two new variables)

Suppose we have two variables(say A & B). A & B have their values. Now we will take one new variables.(With no values)(Say temp) Then we can do the following: C=A; B=D; C & D are two new variables; Now do the following and print the value of A & B: A=D; B=C; You will see A=3; B=2; Bang!! We have successfully swapped. Let me explain. Let, A & B are two buckets(You can compare variables with buckets, right?) Say, in A we have milk and in B there is honey. We just want honey in A bucket, and milk in bucket B. That's the theory of swapping,right? Okk, now we have brought two new empty buckets C &D(Actually now empty,it has garbage. Let's wash :p) Then what have we done?? We have just put A bucket's milk in C bucket & B bucket's milk in D bucket. Now A& B buckets are empty. Now let's put D bucket's honey in A bucket & C bucket's milk in B bucket Now we have milk in B bucket and honey in A bucket.

(Swapping with the help of only one new variable)

Suppose we have two variables.(say A & B). A & B have their values. Now we will take one new variable.(With no values)(Say temp) Then we can do the following: temp=A; A=B; B=temp;

1st we have assigned the values of A in temp variable, then we have put value of B in A variable. And after that we have assigned value of temp(actually A) in B.

Then after printing the values of A & C, we will see: A=3; B=2; Bang!!! We've successfully swapped two variables.

Let me explain. Let, A & B are two buckets(You can compare variables with buckets, right?) Say, in A we have milk and in B there is honey. We just want honey in A bucket, and milk in bucket B. That's the theory of swapping,right? Okk, now we have brought one empty bucket temp.(Actually now empty,it has garbage. Let's wash :p) Then what have we done?? We have just put A bucket's milk in temp bucket. Now A bucket is empty. Let's put B bucket's honey in A bucket. Now B bucket is empty. Let's just put temp bucket's milk in B bucket. Now we have milk in B bucket and honey in A bucket. Agaain we have successfully swapped. =D

Okk now let's try now try this one.

(Swapping with the help of no extra variables) Suppose we have two variables(say A & B). A & B have their values.

Now let's try this: A=A+B; B=A-B; A=A-B;

I think you have understood. If not , just make comment. ;)

Full text and comments »

  • Vote: I like it
  • +10
  • Vote: I do not like it