Swap Function in C using Pointers

Hi Friends

This is the popular swap() function in C showing the working of Pointers as Function Arguments.


/* Program demonstrating Swap Function */

#include<stdio.h>

#include<conio.h>

 

//Swap Function in C

//pass by value

void swap(int num1, int num2)

{

     int num3;

     num3=num1;

     num1=num2;

     num2=num3; 

    

     printf(“\n Inside Swap Function \n”);

     printf(“\n num1 = %d”, num1);

     printf(“\n num2 = %d”, num2);

     printf(“\n”);

}

 

//pass by reference

void swapref(int *num1, int *num2)

{

     int num3;

     num3=*num1;

     *num1=*num2;

     *num2=num3;  

}

int main()

{

     int a, b, c;

     a=2;

     b=3;

    

     printf(“\n ~~~Swapping two Numbers in C~~~ \n”);

    

     printf(“\n Before Swapping \n”);

     

     printf(“\n a = %d”, a);

     printf(“\n b = %d”, b);

     printf(“\n”);

    

     swap(a,b);

     printf(“\n After Swapping in main (pass by value)\n”);

     printf(“\n a = %d”, a);

     printf(“\n b = %d”, b);

     printf(“\n”);

    

     printf(“\n After Swapping (pass by reference) \n”);

     swapref(&a,&b);

     

     printf(“\n a = %d”, a);

     printf(“\n b = %d”, b);

   

     getch();

     return 0;  

}

Snapshot of the o/p




2 thoughts on “Swap Function in C using Pointers

  1. Pingback: Clumsy Pointers in C – Ennovates

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s