C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program to swap two numbersThis program is to swap/exchange two numbers by using a variable. For example: Numbers to swap: 11 and 12 Let x= 11, y= 12 Swapping Logic: t=x= 11 x =y =12 y =t =11 After swapping: x= 12, y = 11 Algorithm
Java Programimport java.util.*; class Swap_With { public static void main(String[] args) { int x, y, t;// x and y are to swap Scanner sc = new Scanner(System.in); System.out.println("Enter the value of X and Y"); x = sc.nextInt(); y = sc.nextInt(); System.out.println("before swapping numbers: "+x +" "+ y); /*swapping */ t = x; x = y; y = t; System.out.println("After swapping: "+x +" " + y); System.out.println( ); } } Output: Enter the value of X and Y 2 3 before swapping numbers: 2 3 After swapping: 3 2 C Program#include <stdio.h> int main() { int x, y, t;// x and y are the swapping variables and t is another variable printf("Enter the value of X and Y\n"); scanf("%d%d", &x, &y); printf("before swapping numbers: %d %d\n",x,y); /*swapping*/ t = x; x = y; y = t; printf("After swapping: %d %d",x,y); return 0; } Output: Enter the value of X and Y 29 39 before swapping numbers: 29 39 After swapping: 39 29 Python Programx = int(input("Enter the value of x?")) y = int(input("Enter the value of y?")) print("before swapping numbers: %d %d\n" %(x,y)) #swapping# temp = x x = y y = temp print("After swapping: %d %d\n"%(x,y)) Output: Enter the value of X? 87 Enter the value of Y? 43 before swapping numbers: 87 43 After swapping: 43 87 PHP Program<?php echo "Enter the value of x"; $x = readline(); echo "Enter the value of y"; $y = readline(); echo "before swapping numbers: "; echo $x; echo " "; echo $y; echo "\n"; /*swapping*/ $temp = $x; $x = $y; $y = $temp; echo "After swapping "; echo $x; echo " "; echo $y; ?> Output: Enter the value of x 33 Enter the value of Y 22 before swapping numbers: 33 22 After swapping 22 33 C# Programusing System; public class Swap { public static void Main() { Console.WriteLine("Enter the value of x and y"); int x=Convert.ToInt32(Console.ReadLine()); int y = Convert.ToInt32(Console.ReadLine()); int temp; Console.WriteLine("before swapping numbers: "+x +" "+ y); /*swapping*/ temp = x; x = y; y = temp; Console.WriteLine("After swapping: "+x +" " + y); }} Output: Enter the value of x and y 65 54 before swapping numbers: 65 54 After swapping: 54 65
Next Topic#
|