C program to swap two numbers

1. C program to swap two numbers without using third variable

This C program swaps the values of two variables without using a third variable.

Program: Swap the numbers in C

#include<stdio.h>
int main()
{
    int a,b;
    printf("Enter two numbers: ");
    scanf("%d %d",&a,&b);
    printf("\nThe values before swapping -> \ta= %d and b= %d",a,b);
    a=a+b;      // a+=b is same as a=a+b
    b=a-b;
    a=a-b;
    printf("\nThe values after swapping -> \ta= %d and b= %d\n",a,b);
    return 0;
}

Sample Output: Swap the values and print them

Enter two numbers: 219 538

The values before swapping ->   a= 219 and b= 538
The values after swapping ->    a= 538 and b= 219

2. C program to swap two numbers using third variable

This C program swaps the values of variables using a third variable.

Program: Swap two numbers

#include<stdio.h>
int main()
{
    int a,b,temp;
    printf("Enter two numbers: ");
    scanf("%d %d",&a,&b);
    printf("\nValues of a and b before swapping ->\t a=%d and b=%d",a,b);
    temp=a;     //store value of a inside the temp variable
    a=b;        //No explanation needed
    b=temp;     //Allocate the stored value of a(original) to b
    printf("\nValues of a and b after swapping ->\t a=%d and b=%d\n",a,b);
    return 0;
}

Sample Output: Swap numbers and print values

Enter two numbers: 34 67

Values of a and b before swapping ->     a=34 and b=67
Values of a and b after swapping ->      a=67 and b=34

3. C program to swap two numbers using pointers and functions

This C program takes two numbers as input from the user and then swaps them using a user-defined function.


Program: C program to swap two numbers using function

#include<stdio.h>
//function prototype
void swap(int *n1, int *n2);
int main()
{
    int num1, num2;
    printf("Enter two numbers(a & b): ");
    scanf("%d %d", &num1, &num2);
    printf("Before swapping:\nNumber1= %d\nNumber2= %d\n\n", num1, num2);
    swap(&num1, &num2);
    printf("After swapping:\nNumber1= %d\nNumber2= %d\n", num1, num2);
    return 0;
}
//function definition
void swap(int * n1, int * n2)
{
    int temp;
    temp = *n1;
    *n1 = *n2;
    *n2 = temp;
}


Output: print numbers after swapping

Enter two numbers(a & b): 35 92
Before swapping:
Number1= 35
Number2= 92

After swapping:
Number1= 92
Number2= 35

Share your code and queries in the comments.

Share code with your programmer friends.

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →

Leave a Reply

Your email address will not be published. Required fields are marked *