Program to Swap Two Numbers

Description

To swap two numbers take a temporary variable. 
step 1: Assign the value of firstNumber variable into the temporary variable.
step 2: Assign the value of secondNumber variable into  firstNumber variable.
step 3: Assign the value of tempNumber variable into  secondNumber variable.

C/C++

/* C Program to Swap Two Numbers */
//Save it as SwapTwoNumbers.c

#include<stdio.h>
int main(){

    int firstNumber, secondNumber, tempNumber;

    printf("Enter first number : ");
    scanf("%d",&firstNumber);

    printf("Enter second number : ");
    scanf("%d",&secondNumber);

    printf("Number before swapping %d and %d",firstNumber,secondNumber);

    //Stotring firstNumber variable into a temporary variable
    tempNumber = firstNumber;
    
    //Stotring secondNumber variable into a firstNumber variable
    firstNumber = secondNumber;
    
    //Stotring tempNumber variable into a secondNumber variable
    secondNumber = tempNumber;

    printf("\nNumber after swapping %d and %d",firstNumber,secondNumber);

    return 0;
}
Input:
Enter first number : 45
Enter second number : 23

Output:
Number before swapping 45 and 23
Number after swapping 23 and 45

Java

/* Java Program to Swap Two Numbers */
//Save it as SwapTwoNumbers.java

import java.io.*;
import java.util.Scanner;

public class SwapTwoNumbers {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        int firstNumber, secondNumber, tempNumber;

        System.out.println("Enter first number : ");
        firstNumber = scanner.nextInt();

        System.out.println("Enter second number : ");
        secondNumber = scanner.nextInt();

        System.out.println("Number before swapping "+firstNumber+" and " +secondNumber);
        
        //Stotring firstNumber variable into a temporary variable
        tempNumber = firstNumber;
        
        //Stotring secondNumber variable into a firstNumber variable
        firstNumber = secondNumber;
        
        //Stotring tempNumber variable into a secondNumber variable
        secondNumber = tempNumber;

        System.out.println("Number after swapping "+firstNumber+" and " +secondNumber);
    }
}
Input:
Enter first number : 
45
Enter second number : 
23

Output:
Number before swapping 45 and 23
Number after swapping 23 and 45

Related Programs

1) Program to swap two strings
2) Program to find sum of digits of a number
3) Program to reverse a number
4) Program to Display Fibonacci Series using Recursion
5) Program to convert Binary to Hexa Decimal
6) Program to find factors of a Number
7) Program to find LCM(Least Common Multiple)
8) Program to calculate power of a number using recursion
9) Program to calculate volume and surface area of cube
10) Program To Check Armstrong Number
Share Me

Leave a Reply