In this program, you will learn about concepts behind c program to swap two numbers with and without using a temporary variable and using the pointer.
For better understanding of program you must have proper knowledge of these c programming topics :
#include <stdio.h>
int main ()
{
int num1, num2, temp;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
//Swapping process
temp = num1;
num1 = num2;
num2 = temp;
printf("\nAfter swapping,"
"\nFirst number: %d"
"\nSecond number: %d", num1, num2);
return 0;
}
Output
[adsense1]
#include <stdio.h>
int main()
{
int num1, num2;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
//Swapping process
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
printf("\nAfter swapping,"
"\nFirst number: %d"
"\nSecond number: %d", num1, num2);
return 0;
}
Output
#include <stdio.h>
int main()
{
int num1, num2, *x, *y, temp;
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
//Swapping process
x = &num1;
y = &num2;
temp = *y;
*y = *x;
*x = temp;
printf("\nAfter swapping,"
"\nFirst number: %d"
"\nSecond number: %d", num1, num2);
return 0;
}
Output