C program to swap two numbers using call by value

C program to swap two numbers using call by value

This C program is to swap two numbers using call by value.The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.In C programming, C by default uses call by value to pass arguments.

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).

Now we enter the swap function

temp = n1  i.e. temp = 7

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 not passed by value they will not change inside the main.

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

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!