swap two numbers without using third variable code example
Example 1: swap 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: swap 2 numbers without using 3rd variable
a=10;
b=20;
a=a+b;
b=a-b;
a=a-b;
Example 3: 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 4: swap two variables without temporary java
import java.*;
class noTemp {
public static void main(String a[])
{
int x = 10;
int y = 5;
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swaping:"
+ " x = " + x + ", y = " + y);
}
}
Example 5: swap 2 integers without using temporary variable
using System;
class MainClass {
public static void Main (string[] args) {
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
Console.WriteLine("After swapping: num1 = "+ num1 + ", num2 = " + num2);
Console.ReadLine();
}
}
Example 6: swap using third variable
#include <stdio.h>
int main()
{
int var1, var2, temp;
printf("Enter two integersn");
scanf("%d%d", &var1, &var2);
printf("Before SwappingnFirst variable = %dnSecond variable = %dn", var1, var2);
temp = var1;
var1 = var2;
var2 = temp;
printf("After SwappingnFirst variable = %dnSecond variable = %dn", var1, var2);
return 0;
}