Swapping Two Nos in C

Swapping Concept in C-Program

In this blog we are going to read about swapping of two numbers in c program. Normally we can do swapping of the two variables by using the third variable.This example contains two different techniques to swap numbers in C programming.The first program uses temporary variable to swap numbers, whereas the second program doesn’t use temporary variables.

Example-1 Swapping of two numbers

#include<stdio.h>
int main()
{
    int a=10,b=20,c;
    printf("\nBefore Swapping");
    printf("\nA Value:%d",a);
    printf("\nB Value:%d",b);
    c=a;
    a=b;
    b=c;
    printf("\nAfter Swapping");
    printf("\nA Value:%d",a);
    printf("\nB Value:%d",b);
    return 0;
}

Output

Example- 2 Swapping of two numbers without using third variable

#include<stdio.h>
int main()
{
    int a=10,b=20,c;
    printf("\nBefore Swapping\n");
    printf("\nA Value:%d\n",a);
    printf("\nB Value:%d\n",b);
    printf("\n\n");
    a=a+b;
    b=a-b;
    a=a-b;
    printf("\nAfter Swapping\n");
    printf("\nA Value:%d\n",a);
    printf("\nB Value:%d\n",b);
    printf("\n\n");
    return 0;
}

Output

swapping

About the author

Tutor Joes Stanley

Hi, I'm Stanley an aspiring blogger with an obsession for all things tech in Tamil .This blog is dedicate to helping learn about technology

View all posts

Leave a Reply

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