write a program to swap two numbers code example
Example 1: Write a program to show swap of two numbers without using third variable.
#include<stdio.h>
int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
Example 2: how to swap values in variables in c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1 = 10;
int num2 = 9;
int tmp;
int *p_num1 = &num1;
int *p_num2 = &num2;
printf("num1: %i\n", num1);
printf("num2: %i\n", num2);
tmp = num1;
*p_num1 = num2;
*p_num2 = tmp;
printf("num1: %i\n", num1);
printf("num2: %i\n", num2);
return 0;
}