How swap values without third variable?Ask Questions

 Posted on 07/09/2018 7:59:44 AM

I want to swap value of variable A and variable B. without taking third variable C.

I can do like

int a=10,b=5,c=0;

c=a;

a=b;

b=c;

But i don't want to use variable C. 

Share On: facebook gplus twitter
profile
Asked by Shailesh Chaudhary on 07/09/2018 7:59:44 AM Score: 501 points
Add Comment:
Submit

Comments

2 Answers

1 Corrected Answers
Aproved Answers
0
Profile
Answered by Hardik Ranpura on Sep 7 2018 10:57AM Score: 34 points

There are two ways to swap value of variables without using third variable.

In this example I am using + and - operation to do swapping of value of two variable.

int a = 8;

int b = 4;

a = a * b; // a = 8 * 4 = 32

b = a / b; // b = 32 / 4 = 8

a = a / b; // a = 32 / 8 = 4

// you value gets swap

Comments

there are two ways to do this. using +,- and using *,/
07/09/2018   10:58:33   Hardik Ranpura
Add Comment:
0
Profile
Answered by Hardik Ranpura on Sep 7 2018 10:55AM Score: 34 points

int a=10;

int b=20;

 

a = a + b; //a = 10 + 20 = 30

b = a - b; // b = 30 - 20 = 10

a = a - b; // a = 30 -10 = 20

//value gets swap

Comments

there are two ways to do this. using +,- and using *,/
07/09/2018   10:58:39   Hardik Ranpura
Add Comment:

Post Your Answer

  •  
  •  

Existing Members

Sign in to your account
Email Address
Password
...or Join us
Download, Vote, Comment, Publish.
Full Name
Email Address
I have read and agree to the Terms of Service and Privacy Policy
Please subscribe me to the StoodQ newsletters
Guideline to answer a question:

Useful tips to submit your answer
Please read below guidelines before you submit your answer for question.

  • Read and understand question for which you are submitting your answer.
  • Try to avoid grammatical and spell mistake while answering.
  • Do not post any irrelevant information in your answer.
  • Explain your answer with example or any reference link to help who posted question.
  • If you find irrelevant question, please report it to support. Click here to contact support.
  • You agree to the privacy policy and terms of use to submit any contents.

Note: StoodQ is online developers community which helps developer for their difficulty, lets help them with your value contribution.