FOR FREE YEAR SOLVED

Swapping Two Values

Back to Programming

Description

The program is written to swap two values. A third variable is used here to swap the two numbers. First one number is stored in a temporary variable. Then the 2nd number is copied to the 1st number and the previously stored first number is stored in the 2nd variable and hence the values are exchanged.

If the two variables are a and b whose values are to be exchanges and the values are:

a=5, b=6

Then, after exchanging the values will be:

 a=6, b=5

Algorithm

INPUT: Two Numbers

OUTPUT: The values after exchanging

PROCESS:

Step 1: [Taking the inputs]

               Read a, b [two numbers]

Step 2: [Swapping the two values]

               Set tmp<-a

               Set a<-b

               Set b<-tmp

               Print "After swapping the values are a and b"

Step 3: Stop.

Code

TIME COMPLEXITY:

The time complexity of this program is O(1) as it requires a constant time to execute the program.

SPACE COMPLEXITY:

The space complexity is O(1) as it requires a constant number of memory spaces to execute the program for any given input.