Kotlin: Calculate the Power of a Number

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

1. Introduction

Raising a number to a power, or exponentiation, is a fundamental mathematical operation. It is often utilized in scientific, engineering, and statistical computations. In this tutorial, we'll utilize Kotlin's computational prowess to elevate a number to a given power.

2. Program Overview

Our Kotlin program will:

1. Receive a base number and an exponent from the user.

2. Calculate the result of the base number raised to the exponent.

3. Show the resultant value to the user.

3. Code Program

import java.util.Scanner

fun main() {
    // Implement Scanner for user input
    val reader = Scanner(System.in)

    // Gather the base number and exponent from the user
    print("Enter the base number: ")
    val base = reader.nextDouble()
    print("Enter the exponent: ")
    val exponent = reader.nextInt()

    // Compute the power using the Math.pow function
    val result = Math.pow(base, exponent.toDouble())

    // Exhibit the result
    println("$base raised to the power of $exponent is: $result")
}

Output:

Enter the base number: 2
Enter the exponent: 3
2.0 raised to the power of 3 is: 8.0

4. Step By Step Explanation

1. Scanner Initiation: We instigate by initializing the Scanner class, a handy tool to obtain user input. Our instance is named reader.

2. Base and Exponent Retrieval: The program prompts the user to enter a base number and an exponent. It's noteworthy that the base can be a decimal, whereas the exponent used here is an integer (to keep it simple).

3. Power Calculation: Kotlin's standard library provides a convenient function, Math.pow, to execute exponentiation. The base number and exponent are fed to this function, which subsequently returns the calculated power.

4. Result Exhibition: The program then furnishes the user with the outcome, elucidating the base number raised to the given exponent and the resultant value.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare