Write a program to interchange number using function(by call by value method) :-


//Interchange number using call by value

#include<stdio.h>
#include<conio.h>
void interchange(int x,int y);
void main()

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

interchange(a,b);
printf("\n Value of A and B after interchange:\n a=%d\n b=%d",a,b);

getch();
}

void interchange(int x,int y)
{

printf("Value of X and Y before interchange:\n x=%d\n y=%d",x,y);

int temp;
temp=x;
x=y;
y=temp;

printf("\n Value of x and y after interchange:\n x=%d\n y=%d",x,y);
}

Output:


Enter any two numbers:50
100
Value of X and Y before interchange:
x=50
y=100
Value of x and y after interchange:
x=100
y=50
Value of A and B after interchange:
a=50
b=100

			
Previous Next







C program to swap two numbers using call by value :-


	//C program to swap two numbers using call by value

		#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:


	Enter the two numbers to be swapped
	200
	824

	The values of n1 and n2 in the main function before calling the swap function are n1=200 n2=824
	The values of n1 and n2 in the swap function after swapping are n1=824 n2=200
	The values of n1 and n2 in the main function after calling the swap function are n1=200 n2=824

			

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.

Previous Next