In: Computer Science
Write a Java function to swap two integers.
//swap_number() method will swap two integers
public static void swap_number(int m,int n)
{
int c; //declare third variable
c=m; //assign first number to third variable
m=n; //assign value of second variable to firtst
variable
n=c;//assign value of third variable to second
variable
System.out.println("After swap first number is "+m +"
second number is "+n);
}
PROGRAM IMPLEMENTATION
import java.lang.*;
import java.util.Scanner;
class swap
{
//swap_number() method will swap two integers
public static void swap_number(int m,int n)
{
int c; //declare third variable
c=m; //assign first number to third variable
m=n; //assign value of second variable to firtst
variable
n=c;//assign value of third variable to second
variable
System.out.println("After swap first number is "+m +"
second number is "+n);
}
//driver program
public static void main(String[] args)
{
//declare the scanner object to read data
Scanner scr= new Scanner(System.in);
int a,b; //declare two integers
System.out.println("Enter two numbers"); //ask user
for two numbers
a=scr.nextInt(); //read first number
b=scr.nextInt();//read second number
//diplsay the numbers
System.out.println("Before swap first number is "+a +"
second number is "+b);
swap_number(a,b); //call to swap method
}
}
OUTPUT