C program to swap two numbers using call by reference

C program to swap two numbers using call by reference

This C program is to swap two numbers using call by reference.The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.

Logic

We are using a function called swap().This function basically swaps two numbers, how we normally take a temporary variable in C to swap 2 nos.

Dry Run of the Program

Take 2 nos as input.Let us take n1=7 and n2=10.

The values before calling the swap function will be n1=7 and n2=10.

swap(&n1,&n2) i.e swap(&7 , &10).  i.e we are passing the address of variable n1 and n2 to swap() function

Now we enter the swap function

temp = *n1  i.e. temp = 7 i.e. ‘*’ means you are pointing to the address of the corresponding variable

*n1 = *n2 i.e *n1=10

*n2 = *temp i.e. *n2 = 7

So the values printed inside the swap function would be n1 = 10 and n2 = 7

But as the values are passed by reference they will be also reflected inside the main.

Hence after calling the swap function, you can see that the values n1 and n2 inside the main are changed .

Program

#include<stdio.h>

void swap(int *,int *);        

void main( )
{
    int n1,n2;
    printf("Enter the two numbers to be swapped\n");
    scanf("%d%d",&n1,&n2);
    printf("\nThe values of n1 and n2 in the main function before calling the swap function are n1=%d n2=%d",n1,n2);
    swap(&n1,&n2);                                          
    printf("\nThe values of n1 and n2 in the main function after calling the swap function are n1=%d n2=%d",n1,n2);
}

void swap(int *n1,int *n2)                           
{ 
    int temp;
    temp=*n1;
    *n1=*n2;
    *n2=temp;
    printf("\nThe values of n1 and n2 in the swap function after swapping are n1=%d n2=%d",*n1,*n2);
}

Output

Share Me!