C Program to Swap two Numbers

Given two numbers, write a C program to swap the given numbers.

Input : x = 10, y = 20;
Output : x = 20, y = 10


The idea is simple

  1. Assign x to a temp variable : temp = x
  2. Assign y to x : x = y
  3. Assign temp to y : y = temp
filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to swap two variables
#include <stdio.h>
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
  
    int temp = x;
    x = y;
    y = temp;
  
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}

chevron_right


Output:

Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 

How to write a function to swap?
Since we want the local variables of main to modified by swap function, we must them using pointers in C.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to swap two variables using a 
// user defined swap()
#include <stdio.h>
  
// This function swaps values pointed by xp and yp
void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(&x, &y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}

chevron_right


Output:

Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 

How to do in C++?
In C++, we can use references also.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to swap two variables using a 
// user defined swap()
#include <stdio.h>
  
// This function swaps values referred by 
// x and y,
void swap(int &x, int &y)
{
    int temp = x;
    x = y;
    y = temp;
}
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(x, y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}

chevron_right


Output:

Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 

Is there a library function?
We can use C++ library swap function also.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to swap two variables using a 
// user defined swap()
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    int x, y;
    printf("Enter Value of x ");
    scanf("%d", &x);
    printf("\nEnter Value of y ");
    scanf("%d", &y);
    swap(x, y);
    printf("\nAfter Swapping: x = %d, y = %d", x, y);
    return 0;
}

chevron_right


Output:

Enter Value of x 12

Enter Value of y 14

After Swapping: x = 14, y = 12 


How to swap without using a temporary variable?



My Personal Notes arrow_drop_up