// swap variables in C
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}
swap(&a, &b); // address of a and b
//Author: Subodh
//! Swap two number using XOR operation
cout << "Before, n1 = " << num1 << ", n2 = " << num2 << endl;
num1 = num1 ^ num2, num2 = num1 ^ num2, num1 = num1 ^ num2;
cout << "After, n1 = " << num1 << ", n2 = " << num2 << endl;
// swap the value of varible using pointer
#include <stdio.h>
void swap(int *, int *);
int main()
{
int a = 11;
int b = 5;
int *p, *q;
p = &a; // p holds the address of a
q = &b; // q holds the address of b
printf("Before swapping value of a = %d , b = %d
", *p, *q);
swap(p, q); // you can use - swap(&a,&b);
printf("After swapping value of a = %d ,b = %d
", *p, *q);
return 0;
}
// function that swaps the value of the integer variable
void swap(int *p, int *q)
{
int t;
t = *p;
*p = *q;
*q = t;
}
#include <stdio.h>
int main()
{
int x = 20, y = 30, temp;
temp = x;
x = y;
y = temp;
printf("X = %d and Y = %d", x, y);
return 0;
}
// swap variables in C
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}
swap(&a, &b); // address of a and b
#include <stdio.h>
#include <stdlib.h>
int main()
{
//initialize variables
int num1 = 10;
int num2 = 9;
int tmp;
//create the variables needed to store the address of the variables
//that we want to swap values
int *p_num1 = &num1;
int *p_num2 = &num2;
//print what the values are before the swap
printf("num1: %i
", num1);
printf("num2: %i
", num2);
//store one of the variables in tmp so we can access it later
//gives the value we stored in another variable the new value
//give the other variable the value of tmp
tmp = num1;
*p_num1 = num2;
*p_num2 = tmp;
//print the values after swap has occured
printf("num1: %i
", num1);
printf("num2: %i
", num2);
return 0;
}