How to write Program to swap two variables using function call by value?

1 answer

Answer

1031709

2026-07-30 15:20

+ Follow

//This program swaps the values in the variable using function containing reference arguments

#include<iOStream.h>

void swap(int &iNum1, int &iNum2);

void main()

{

int iVar1, iVar2;

cout<<"Enter two numbers "<<endl;

cin>>iVar1;

cin>>iVar2;

swap(iVar1, iVar2);

cout<<"In main "<<iVar1<<" "<<iVar2<<endl;

}

void swap(int &iNum1, int &iNum2)

{

int iTemp;

iTemp = iNum1;

iNum1 = iNum2;

iNum2 = iTemp;

cout<<"In swap "<<iNum1<<" "<<iNum2<<endl;

}

Reference arguments are indicated by an ampersand (&) preceding the argument:

int &iNUm1;

the ampersand (&) indicates that iNum1 is an alias for iVar1 which is passed as an argument.

The function declaration must have an ampersand following the data type of the argument:

void swap(int &iNum1, int &iNum2)

The ampersand sign is not used during the function call:

swap(iVar1, iVar2);

The sample output is

Enter two numbers

12

24

In swap 24 12

In main 24 12

------------------------------------------------------------------

By Satish from here

/ * Program to Swap Two Numbers by Using Call By Reference Method * /

#include

main()

{

int i, j;

clrscr();

printf("Please Enter the First Number in A : ");

scanf("%d",&i);

printf("\nPlease Enter the Second Number in B : ");

scanf("%d",&j);

swapr(&i,&j); /* call by reference*/

printf("A is now in B : %d",i);

printf("B is now in A : %d",j);

}

/* call by reference function*/

swapr(int *x, int *y)

{

int t;

t=*x;

*x=*y;

*y=t;

}

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.