Write a C, C++ program to swap two numbers using pointers. So swapping two numbers using pointers means we are using call by reference method.
Swap two numbers without using third variable .
Swap two numbers using third variable .
2. To pass an argument using call by reference we use the address operator(&).
3. Using call by reference no additional memory is used as we are using pointers.
C, C++ Interview Questions .
Output :
Enter two numbers : 6 7
Swap two numbers without using third variable .
Swap two numbers using third variable .
Call by Reference
1. In call by reference method actual parameter is modified. Because a pointer to the data is copied. So Changes to the data pointed by the pointer are reflected in the data of the calling function.
3. Using call by reference no additional memory is used as we are using pointers.
C, C++ Interview Questions .
Swap Two Numbers using Pointers in C
#include<stdio.h> void swapValue(int *a,int *b); int main(){ int a = 100; int b= 200; printf("First number is %d",a); printf("Second Number is %d",b); swapValue(&a,&b); printf("After swap function \n"); printf("%d\n%d",a,b); } void swapValue(int *x,int *y){ int temp; temp = *x; *x=*y; *y=temp; }
Swap Two Numbers using Pointers in C++
#include <iostream> using namespace std; void swapvalue (int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int main() { int a, b; cout << "Enter two numbers: \n"; cin >> a >> b; /* Passing address .*/ swapvalue(&a, &b); cout << "After swapping first and second number is "<<a <<" "<<b; return 0; }
Output :
Enter two numbers : 6 7
After swapping first and second number is 7 6
No comments:
Post a Comment