C Language: SwapTwo Numbers

#1: Program to Swap Numbers Using Temporary Variable:

#include <stdio.h>
int main()
{
int a,b,tem;

printf(“Enter first number: “);
scanf(“%d”, &a);
printf(“Enter second number: “);
scanf(“%d”,&b);

printf(“\n Before swapping,a= %d\n”,a);
printf(“Before swapping, b= %d”,b);

// Value of a is assigned to temp
temp = a;
// Value of b is assigned to a
a = b;
// Value of temp is assigned to b
b = temp;

printf(“\nAfter swapping, firstNumber = %d\n”, a);
printf(“After swapping, secondNumber = %d”, b);

return 0;
}




Output:
Enter first number: 6
Enter second number: 9

Before swapping, a =6
Before swapping, b =9

After swapping, a=9
After swapping, b=6

————————————————————————–

#2: Program to Swap Number Without Using Temporary Variables

#include <stdio.h>
int main()
{
int a,b;

printf(“Enter first number: “);
scanf(“%d”, &a);

printf(“Enter second number: “);
scanf(“%d”,&b);

printf(“\n Before swapping,a= %d\n”,a);
printf(“Before swapping, b= %d”,b);

// Swapping process
a= a-b;
b=a+b;
a=a-b;

printf(“\nAfter swapping, firstNumber = %df\n”,a);
printf(“After swapping, secondNumber = %d”,b);

return 0;
}




Translate »