Hello Devs,

In this tutorial, we are going to learn C program for swapping of two numbers

Here is a well-commented example you can understand and analyze.

 

# include <stdio.h>

int main(){
    int a,b,temp;
   
    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);
    printf("Before swapping: a = %d, b=%d",a,b);

    temp = a;
    a = b;
    b = temp;
    printf("\nAfter swapping: a = %d, b=%d",a,b);

    return 0;
}

C program for Swapping using function

#include<stdio.h>

void swap(int *,int *);
int main(){

    int a,b;
   
    printf("Enter any two integers: ");
    scanf("%d%d",&a,&b);

    printf("Before swapping: a = %d, b=%d",a,b);

    swap(&a,&b);

    printf("\nAfter swapping: a = %d, b=%d",a,b);
    return 0;
}

void swap(int *a,int *b){
    int *temp;
    temp = a;
    *a=*b;
    *b=*temp;
}


I hope this example helps you.