Q:

Kotlin program to swap two numbers

belongs to collection: Kotlin Basic Programs

0

Given two numbers, we have to swap them.

Example:

    Input:
    First number: 10
    Second number: 20

    Output:
    First number: 20
    Second number: 10

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Kotlin program to convert distance Miles to KM and... >>
<< Kotlin program to find largest of three numbers...