C Program to Swap Two Numbers Using Third Variable

C program to swap two numbers using third variable can be implemented by using another variable apart from the variables which store the two given numbers. Swapping of two numbers means the exchanging of values between them.

  Here the C program for swapping by using the third variable has been shown along with the algorithm, pseudocode and time complexity of the program.





1. Algorithm to swap two Numbers using Third Variable


1. Take two integers say $x,~y$ as input.

2. Set $t= x$

3. Set $x= y$

4. Set $y= t$

5. Return $x, y$




2. Pseudocode to swap two Numbers using Third Variable


Input : Two integer numbers $x,~y$

Output : $x,~y$ with exchanged values

1. Procedure swap($x, y$):

2. $t \leftarrow x $

3. $x \leftarrow y$

4. $y \leftarrow t$

5. Return $x,~y$

6. End Procedure





3. Time complexity to Swap Two Numbers using Third Variable


Time Complexity: O(1)





4. C Program & output of to Swap Two Numbers using Third Variable

Code has been copied
/**************************************************
        	alphabetacoder.com
 C program to swap two numbers using third variable
***************************************************/

#include <stdio.h>

int main() {
    int num1, num2, temp;
    // take input of the numbers
    printf("Enter two numbers = ");
    scanf("%d%d", & num1, & num2);
    printf("Before swapping: number1 = %d and number2 = %d\n", num1, num2);

    //do swapping operation  using temp
    temp = num1;
    num1 = num2;
    num2 = temp;

    printf("After swapping: number1 = %d and number2 = %d", num1, num2);
    return 0;
}

Output


Enter two numbers = 5 10

Before swapping: number1 = 13 and number2 = 20

After swapping: number1 = 20 and number2 = 13