Swap values of two variable function call by reference program

Coding in C

#include<stdio.h>
void swap(int*,int*);
int main()
{
int a,b;
printf(“Enter a b: “);
scanf(“%d%d”,&a,&b);
printf(“Before swapping values in main a = %d b = %d\n”,a,b);
swap(&a,&b);
printf(“After swapping values in main a = %d b = %d\n”,a,b);
}
void swap (int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
printf(“After swapping values in function a = %d b = %d\n”,a,b);
}

Coding in C++

#include<iostream>
using namespace std;
void swap(int*,int*);
int main()
{
int a,b;
cout<<“Enter a b: “; cin>>a>>b;
cout<<“Before swapping values in main a = “<<a<<” b = “<<b<<endl;
swap(&a,&b);
cout<<“After swapping values in main a = “<<a<<” b = “<<b<<endl;
}
void swap (int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
cout<<“After swapping values in function a = “<<a<<” b = “<<b<<endl;
}

Output

Callbyref program output in C CPP

Published by

admin

I am a computer teacher, programmer and web developer