The Wayback Machine - https://web.archive.org/web/20240721023928/https://www.geeksforgeeks.org/c-program-swap-two-numbers/
Open In App

C Program to Swap two Numbers

Last Updated : 12 Jul, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Swapping two numbers means exchanging their values. In this article, we will learn how to swap two numbers in the C programming language.

swap two numbers in c

Swap Two Numbers Using a Temporary Variable

Below is the C program to swap two numbers using a temporary variable.

C
// C program to swap two variables
#include <stdio.h>

// Driver code
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);

    // Using a temporary variable to swap the values
    // Store the value of x in a temporary variable
    int temp = x;
    // Assign the value of y to x
    x = y;
    // Assign the value stored in the temporary variable to
    // y
    y = temp;

    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}

Output
Enter Value of x 
Enter Value of y 
After Swapping: x = 0, y = 0

Explanation

We swap two numbers by storing the value of one number in a temporary variable, assigning the value of the second number to the first number, and then assigning the value stored in the temporary variable to the second number.

Swap Two Numbers Without Using a Temporary Variable

Below is the C/C++ program to swap two numbers without using a temporary variable.

C
// C program to swap two numbers
// without using a third variable
#include <stdio.h>

// Driver code
int main()
{
    int a, b;
    printf("Enter the two numbers : \n");
    scanf("%d %d", &a, &b);
    printf("Before swapping A is : %d and B is %d \n", a,
           b);

    // Swapping without using a third variable
    // Sum of both numbers is stored in 'a'
    a = a + b;
    // Difference of sum and original 'b' is
    // stored in 'b'
    b = a - b;
    // Difference of sum and new 'b' is stored in
    // 'a'
    a = a - b;

    printf("After swapping A is : %d and B is : %d \n", a,
           b);
    return 0;
}

Output
Enter the two numbers : 
Before swapping A is : 0 and B is 0 
After swapping A is : 0 and B is : 0 

Complexity Analysis

  • Time Complexity: O(1)
  • Auxiliary Space: O(1)

Explanation

The idea is to use arithmetic operators. We will take the sum of the two numbers and store it in one variable, and store the difference of both numbers in the other variable. Finally, we will store the difference of both numbers in the first variable. Since the values will be updated after the first two operations, we will be able to swap the numbers.

We can write a function also to swap twp variables if we need to repeatedly use swap

The idea is to use pointers in C. We use pointers because variables are passed by value in C and to change value of a variable inside another function, we need to pass address of the variable so that the value can changed by going to the address.

C

// C program for QuickSort
#include <stdio.h>

// function to swap tp integers
void swap(int *p1, int *p2) {
    int temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

// Driver code
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);

    // Note that we are passing addresses
    // of two variables
    swap(&x, &y);
    
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}


Refer to the complete article on How to swap without using a temporary variable? for more details!



Similar Reads

Python Program to swap two numbers without using third variable
Given two variables n1 and n2. The task is to swap the values of both the variables without using third variable.Examples: X : 10 Y : 20 After swapping X and Y, we get : X : 20 Y : 10 A : 'Hello' B : 'World' After swapping A and B, we get : A : 'World' B : 'Hello' Method 1 :- Using simple built-in method left , right = right , left This method work
4 min read
Javascript program to swap two numbers without using temporary variable
To swap two numbers without using a temporary variable, we have multiple approaches. In this article, we are going to learn how to swap two numbers without using a temporary variable. Below are the approaches used to swap two numbers without using a temporary variable: Table of Content Using Arithmetic OperatorsUsing Bitwise XORA mixture of bitwise
6 min read
How to swap two numbers without using a temporary variable?
Given two variables, x, and y, swap two variables without using a third variable.  Method 1 (Using Addition and subtraction)  The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.  [GFGTABS] C++ // C++ Program to swap two numbers without // using temporary variable #inc
15+ min read
Swap three numbers in cycle
Given three numbers, swap them in cyclic form. First number should get the value of third, second should get the value of first and third should get value of second. Examples: Input : a = 2, b = 4, c = 7 Output : a = 7, b = 2, c = 4 Input : a = 10, b = 20, c = 30 Output : a = 30, b = 10, c = 20 Prerequisite: Pointers, Call by Reference, The idea is
5 min read
Swap Two Variables in One Line
We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write "x, y = y, x".2) C/C++: Below is one generally provided classical solution: //
4 min read
Swap two nibbles in a byte
A nibble is a four-bit aggregation or half an octet. There are two nibbles in a byte. Given a byte, swap the two nibbles in it. For example, 100 is represented as 01100100 in a byte (or 8 bits). The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal. Recommended PracticeSwap two nibbles in a byteTr
8 min read
C program to swap adjacent characters of a String
Given a string str, the task is to swap adjacent characters of this string in C. Examples: Input: str = "geeks" Output: NA Not possible as the string length is odd Input: str = "geek" Output: egke Approach: Check if the length of the string is even or odd.If the length is odd, swapping cannot be done.If the length is even, take each character of th
2 min read
Python3 Program for Swap characters in a String
Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your task is to find the final String after B swaps. Exam
5 min read
Lexicographically largest string possible in one swap
Given string str of length N, the task is to obtain the lexicographically largest string by at most one swap. Note: The swapping characters might not be adjacent. Examples: Input: str = "string" Output: tsring Explanation: Lexicographically largest string obtained by swapping string -&gt; tsring. Input: str = "zyxw" Output: zyxw Explanation: The gi
7 min read
Bit manipulation | Swap Endianness of a number
Prerequisite: https://www.geeksforgeeks.org/little-and-big-Endian-mystery/ Little Endian and Big Endian are ways or storing data in machines. Some machines might use Little Endian byte ordering while others might use big Endian. This creates an inconsistency when you are transferring data from a Big Endian machine to a Little Endian machine. Usuall
15 min read
Practice Tags :
three90RightbarBannerImg