xxxxxxxxxx
// 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
xxxxxxxxxx
#include <stdio.h>
void swap(int *ptr1, int *ptr2) {
// Swapping values using pointers
*ptr1 = *ptr1 + *ptr2;
*ptr2 = *ptr1 - *ptr2;
*ptr1 = *ptr1 - *ptr2;
}
int main() {
int a = 5, b = 10;
int *ptr1 = &a, *ptr2 = &b;
// Before swap
printf("Before Swap:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
// Swapping using pointers
swap(ptr1, ptr2);
// After swap
printf("After Swap:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
xxxxxxxxxx
#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;
}
xxxxxxxxxx
// 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
xxxxxxxxxx
// 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 \n", *p, *q);
swap(p, q); // you can use - swap(&a,&b);
printf("After swapping value of a = %d ,b = %d\n", *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;
}
xxxxxxxxxx
#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\n", num1);
printf("num2: %i\n", 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\n", num1);
printf("num2: %i\n", num2);
return 0;
}
xxxxxxxxxx
#include<stdio.h>
void swapping(int, int); //function declaration
int main()
{
int a, b;
printf("Enter values for a and b respectively: \n");
scanf("%d %d",&a,&b);
printf("The values of a and b BEFORE swapping are a = %d & b = %d \n", a, b);
swapping(a, b); //function call
return 0;
}
void swapping(int x, int y) //function definition
{
int third;
third = x;
x = y;
y = third;
printf("The values of a and b AFTER swapping are a = %d & b = %d \n", x, y);
}
xxxxxxxxxx
#include <stdio.h>
#include <stdlib.h>
int *swap(int x, int y)
{
int z = x;
int *ptr_number;
x = y;
y = z;
*(ptr_number) = x;
*(ptr_number + 1) = y;
return ptr_number;
}
int main(void)
{
int x = 45;
int y = 30;
int *ptr_number;
printf("befor swap x = %d , y =%d\n\n",x , y);
ptr_number = swap(x , y);
printf("after swap x = %d , y =%d\n\n", *(ptr_number) , *(ptr_number+1));
return 0;
}