In this program, You will learn how to swap two numbers without using third variable in R.
R Program Example: How to swap two numbers without using third variable in R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | { x <- as.integer(readline(prompt = "Enter x value :")) y <- as.integer(readline(prompt = "Enter y value :")) x = x + y y = x - y x = x - y print(paste("After swap x is :", x)) print(paste("After swap y is :", y)) } |
Output:
1 2 3 4 5 6 | Enter x value :34 Enter y value :30 [1] "After swap x is : 30" [1] "After swap y is : 34" |
The code first reads in values for x
and y
from the user and stores them as integers. It then swaps the values of x
and y
using a simple algorithm.
First, it adds x
and y
and stores the result in x
. Then it subtracts y
from the new value of x
and stores the result in y
. Finally, it subtracts the new value of y
from the original value of x
and stores the result in x
.
After the values have been swapped, the code prints the new values of x
and y
to the console.