Header Ads Widget

Ticker

6/recent/ticker-posts

functions program in c :- 7

 Program 7: Swap the two numbers using call by reference. Swap function with argument list but no return type.


#include< stdio.h>

#include< conio.h>

void swap(int * x, int *y)

{

int t;

t = *x;

*x = *y;

*y = t;

}

void main()

{

int a, b;

printf(“\n Enter the first number a=”);

scanf(“%d”, &a);

printf(“\n Enter the second number b=”);

scanf(“%d ”,&b);

swap(&a , &b); //actual swapping is done in call by reference

printf(“\n After swapping value of a = %d”, a);

printf(“\n After swapping value of b = %d ”, b);

getch();

}


Output:

Enter the first number a= 10

Enter the second number b= 20

After swapping value of a = 20

After swapping value of b = 10


Explanation:

In call by reference, address of variable a and b is passed to the function swap. When we swap values in swap function is reflected in old values a and b. So after swapping a becomes 20 and b becomes 10 in main function.

Post a Comment

0 Comments