CS Electrical And Electronics
@cselectricalandelectronics

Swap two variables with third variable and without third variable?

All QuestionsCategory: C LanguageSwap two variables with third variable and without third variable?
Anonymous asked 1 year ago
1 Answers
Anonymous answered 1 year ago

To swap the values of two variables, you can use a temporary variable to hold the value of one of the variables while you assign the other variable to the temporary variable. Here is an example of how to swap the values of two variables.
 
// Variables to swap
int x = 5;
int y = 10;
// Use a temporary variable to hold the value of x
int temp = x;
// Assign the value of y to x
x = y;
// Assign the value of the temporary variable (which holds the original value of x) to y
y = temp;
 
Alternatively, you can use arithmetic operations to swap the values of the two variables without using a temporary variable. Here is an example of how to do this in Java:
 

// Variables to swap
int x = 5;
int y = 10;
// Use addition and subtraction to swap the values of x and y
x = x + y; // x is now 15
y = x – y; // y is now 5 (the original value of x)
x = x – y; // x is now 10 (the original value of y)
 

Both of these methods have a time complexity of O(1), since they only require a constant number of operations to swap the values of the two variables.

Â