Kotlin: Find the Sum of Natural Numbers

1. Introduction

Natural numbers are the set of positive integers, starting from 1 and progressing indefinitely. The sum of natural numbers can be used in various calculations, especially in algebra and arithmetic. In this tutorial, we will employ Kotlin to calculate the sum of the first 'n' natural numbers provided by the user.

2. Program Overview

Our Kotlin program will:

1. Prompt the user to enter a number 'n'.

2. Compute the sum of the first 'n' natural numbers.

3. Display the calculated sum to the user.

3. Code Program

import java.util.Scanner

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

    // Prompt the user to specify 'n' - the number of natural numbers to sum
    print("Enter the number of natural numbers to sum up: ")
    val n = reader.nextInt()

    // Calculate the sum of the first 'n' natural numbers
    val sum = n * (n + 1) / 2

    // Showcase the computed sum
    println("The sum of the first $n natural numbers is: $sum")
}

Output:

Enter the number of natural numbers to sum up: 5
The sum of the first 5 natural numbers is: 15

4. Step By Step Explanation

1. Scanner Setup: We begin by initializing the Scanner class to capture user input. Our instance is referred to as reader.

2. Number Collection: The program encourages the user to specify the number of natural numbers they wish to sum. This value is stored in the variable 'n'.

3. Sum Computation: Using a well-known arithmetic formula, the sum of the first 'n' natural numbers is given by: n * (n + 1) / 2. This mathematical shortcut offers an efficient alternative to looping through every number up to 'n'.

4. Displaying the Outcome: After computing the sum, the program reveals the result to the user.

Comments