+ 2

how to swap the values of two different variables

i have a variable age which has the value 5 and another variable number which has the value 10. i want the variable age to have the value of the variable number while the variable number has the value ofage

10th Feb 2024, 8:03 PM
DUFE JUANITA
DUFE JUANITA - avatar
10 Respostas
+ 8
from your profile, you are studying Python. Python have a convenient swapping method. age = 5 number = 10 #before swap print(age, number) #to swap, do this: age, number = number, age #after swap print(age, number)
10th Feb 2024, 9:36 PM
Bob_Li
Bob_Li - avatar
+ 3
General method for each programming language is as N B slready mentioned with additional variable and in Python looks like: avar = 1 bvar = 2 # swap tem = avar avar = bvar bvar = tem
11th Feb 2024, 10:06 AM
JaScript
JaScript - avatar
+ 2
tag the relevant programming language
10th Feb 2024, 8:17 PM
Lisa
Lisa - avatar
0
Rain ... right, I should be more explicit...👍
10th Feb 2024, 11:37 PM
Bob_Li
Bob_Li - avatar
0
You have take temporary variable which will store age at once then number at once.
11th Feb 2024, 3:01 PM
Vishakha
Vishakha - avatar
0
Depends on the language and logic if you are using python you can just a, b = b , a or you can just create another variable c = a a = b b = c or do this c = b - a a = b - a + a b = b - c
11th Feb 2024, 11:21 PM
Jomari Tenorio
Jomari Tenorio - avatar
0
I have dealt with this before, the simpler option is to take advantage of the python syntax, like so: Var1, Var2 = Var2, Var1 This code takes advantage of the python syntax, happy coding!
12th Feb 2024, 7:53 AM
evalyadam
evalyadam - avatar
0
#include<stdio.h> void (int a, int b); Void(int a,int b) { Int c; a=b; b=c; } Int main() { Int x,y; x=5; y=10; Swap(x,y); printf("after swap:"); return 0; }
12th Feb 2024, 2:55 PM
Sudeep Reddy
Sudeep Reddy - avatar
0
#include <stdio.h> int main() { int x, y, *a, *b, temp; printf("Enter the value of x and y\n"); scanf("%d%d", &x, &y); printf("Before Swapping\nx = %d\ny = %d\n", x, y); a = &x; b = &y; // After Swapping:// temp = *b; *b = *a; *a = temp; printf("After Swapping\nx = %d\ny = %d\n", x, y); return 0; } Example : Let x and y be: 45 34 Before Swapping: x=45 y=34 After Swapping: x=34 y=45
12th Feb 2024, 5:43 PM
Arun R
Arun R - avatar