Kotlin program to swap two numbers

Kotlin | Swap two numbers: Here, we are going to learn how to swap two given numbers in Kotlin programming language? Submitted by IncludeHelp, on April 20, 2020

Problem statement

Given two numbers, we have to swap them.

Example:

Input:
First number: 10
Second number: 20

Output:
First number: 20
Second number: 10

Swapping two numbers in Kotlin

To swap two numbers – here we are using third variable/temporary variable (consider – first contains the first number, second contains the second number and temp is a temporary variable).

  • Assign the first number (first) to the temporary variable (temp)
  • Now, assign the second number (second) to the variable first.
  • Now, assign the temp (that contains the first number) to the second.
  • Finally, values are swapped, print them on the screen.

Program to swap two numbers in Kotlin

package com.includehelp.basic

import java.util.*

// Main Method Entry Point of Program
fun main(arg: Array<String>) {
    // InputStream to get Input
    var reader = Scanner(System.`in`)
    
    // Input two values
    println("Enter First Value : ")
    var first = reader.nextInt();
    println("Enter Second Value : ")
    var second = reader.nextInt();    
    
    println("Numbers Before Swap : \n first = $first \n second = $second ")
    
    //Code for Swap Numbers
    var temp = first
    first=second
    second=temp
    
    println("Numbers After  Swap : \n first = $first \n second = $second ")
}

Output

Run 1:
Enter First Value :
45
Enter Second Value :
12
Numbers Before Swap :
 first = 45
 second = 12
Numbers After  Swap :
 first = 12
 second = 45

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.