+ 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
10 Respuestas
+ 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)
+ 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
+ 2
tag the relevant programming language
0
Rain ...
right, I should be more explicit...👍
0
You have take temporary variable which will store age at once then number at once.
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
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!
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;
}
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