PLAY WITH CODING

Home Basic Program If & Else Loops Conversion Pattern logo

Basic C Program

Program to Swap two number 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: declare a third variable as temp.

Step 4: Assign the value of first variable into temp variable.

Step 5: Assign the value of second variable into first variable

Step 6: Assign the value of temp variable into second variable

Step 7: Print the swap values

Step 8: END

CODE


/* Swap two number using 3rd variable */

#include  <stdio.h>
int main()
{
      int num1,num2,temp;
      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);
      temp=num1;
      num1=num2;
      num2=temp;
      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 using 3rd variable */

#include  <iostream>
using namespace std;
int main()
{
      int num1,num2,temp;
      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";
      temp=num1;
      num1=num2;
      num2=temp;
      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