PLAY WITH CODING

Home Basic Program If & Else Loops Conversion Pattern logo

Basic C Program

Program to swap two number without using 3rd variable

Input - Output

Input
Enter first number : 12
Enter second number : 5

Output
num1= 5 num2= 12

Algorithm

Step 1: START

Step 2: input two number num1 and num2 as input.

Step 3: Assign the sum of first and second variable into first variable.

Step 4: Assign the subtraction from first variable to second variable into second variable

Step 5: Assign the subtraction from first variable to second variable into first variable

Step 6: Print the swap values

Step 7: END

CODE


/* Swap two number without using 3rd variable */

#include  <stdio.h>
int main()
{
      int num1,num2;
      printf("Enter the first number : ");
      scanf("%d",&num1);
      printf("Enter the second number : ");
      scanf("%d",&num2);
      printf("value of num1 and num2 before swaping\n");
      printf("value of num1 = %d\n",num1);
      printf("value of num2 = %d\n",num2);
      num1=num1-num2;
      num2=num1+num2;
      num1=num2-num1;
      printf("value of num1 and num2 after swaping\n");
      printf("value of num1 = %d\n",num1);
      printf("value of num2 = %d\n",num2);
    return 0;
}


/* Swap two number without using 3rd variable */

#include  <iostream>
using namespace std;
int main()
{
      int num1,num2;
      cout<<"Enter the first number : ";
      cin>>num1;
      cout<<"Enter the second number : ";
      cin>>num2;
      cout<<"value of num1 and num2 before swaping"<<"\n";
      cout<<"value of num1 = "<<num1<<"\n";
      cout<<"value of num2 = "<<num2<<"\n";
      num1=num1-num2;
      num2=num1+num2;
      num1=num2-num1;
      cout<<"value of num1 and num2 after swaping"<<"\n";
      cout<<"value of num1 = "<<num1<<"\n";
      cout<<"value of num2 = "<<num2<<"\n";
    return 0;
}

OutPut

Enter the first number : 12
Enter the second number: 5

value of num1 and num2 before swaping
value of num1 = 12
value of num2 = 5
value of num1 and num2 after swaping
value of num1 = 5
value of num2 = 12