swap values using pointers code example

Example 1: swap function c++ using pointer

#include <stdio.h>
void SwapValue(int &a, int &b) {
   int t = a;
   a = b;
   b = t;
}
int main() {
   int a, b;
   printf("Enter value of a : ");
   scanf("%d", &a);
   printf("\nEnter value of b : ");
   scanf("%d", &b);
   SwapValue(a, b);
   printf("\nAfter swapping, the values are: a = %d, b = %d", a, b);
   return 0;
}

Example 2: swap two numbers using pointers

#include<stdio.h>

#include<conio.h>

void swap(int *a,int *b);

void main()

{

int a = 20;

int b = 30;

printf("Before swapped: a = %d and b = %d\n",a,b);

swap(&a,&b);

printf("Swapped result: a = %d and b = %d\n",a,b);

getch();

}

void swap(int *a, int *b)

{

int temp;

temp = *a;

*a = *b;

*b = temp;

}

Tags:

Cpp Example