How to Swap Two Numbers in Swift Program?

This tutorial will discuss how to write a swift program to swap two numbers. Swapping of two variables means mutually exchanging the values of two variables.

Swapping using temporary variable

Given two variables Number1 and Number2 now we swap their values with each other using a temporary variable Numtemp. It is the most easiest way to swap two numbers.

Algorithm

The algorithm is explained below −

• Step 1 − Declare three integer variables: Number1, Number2 and Numtemp(temporary variable.)

• Step 2 − Assign values to Number1 and Number2

• Step 3 − Assign Number1 to Numbertemp

• Step 4 − Assign Number2 to Number1

• Step 5 − Assign Numbertemp to Number2

• Step 6 − Display the value of Number1 and Number2 variables

Example

The following Swift program will show how to swap two numbers using temporary variable.

import Foundation
import Glibc

var Numtemp = 0
var Number1 = 23
var Number2 = 45

print("Number 1 before swapping:", Number1)
print("Number 2 before swapping:", Number2)

Numtemp = Number1
Number1 = Number2
Number2 = Numtemp

print("\nNumber 1 after swapping:", Number1)
print("Number 2 after swapping:", Number2)

Output

Number 1 before swapping: 23
Number 2 before swapping: 45

Number 1 after swapping: 45
Number 2 after swapping: 23

In the above code, we have two numbers that are Number1 = 23 and Number2 = 45 now we swap them using temporary variable named as Numtemp. The following code will show the swapping −

Numtemp = Number1

Number1 = Number2

Number2 = Numtemp

So the values after swapping are Number1 = 45 and Number2 = 23.

Example

The following Swift program will show how to swap two numbers using temporary variable.

import Foundation
import Glibc

print("Entered Numbers are-")
print("Number 1- ", Number1)
print("Number 2- ", Number2)

var Numtemp = 0

Numtemp = Number1
Number1 = Number2
Number2 = Numtemp

print("Numbers after swapping-")
print("Number 1-", Number1)
print("Number 2-", Number2)

10
20

Output

Entered Numbers are
Number 1- 10
Number 2- 20
Numbers after swapping
Number 1- 20
Number 2- 10

In the above code, we take two numbers from the user using readLine() function and convert them into integer using Int() function and the entered numbers are number1 = 10 and number2 = 20. Now we swap them using the third variable named as Numtemp. The following code will show the swapping −

Numtemp = Number1

Number1 = Number2

Number2 = Numtemp

So the values of the Number1 and Number2 after swapping are Number1 = 20 and Number2 = 10.