ADVERTISEMENT
ADVERTISEMENT

Home » Kotlin » Kotlin programs » Kotlin basic programs

Kotlin program to calculate the sum of natural numbers

Kotlin | Sum of natural numbers: Here, we are going to learn how to calculate the sum of natural numbers in Kotlin programming language?
Submitted by IncludeHelp, on April 24, 2020

Given a number number, and we have to calculate the sum of all natural numbers from 1 to number.

Example:

    Input:
    number = 15

    Output:
    120

Program to calculate the sum of natural numbers in Kotlin

package com.includehelp.basic

import java.util.*


//Main Function entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val scanner = Scanner(System.`in`)

    //input integer number
    print("Enter Number  : ")
    val number: Int = scanner.nextInt()

    var sum=0

    //Iterate through loop to calculate sum
    for(i in 1..number){
        sum+=i
    }

    //Print Sum
    println("Sum of All Natural Numbers up to $number are : $sum")
}

Output

Run 1:
Enter Number  : 15
Sum of All Natural Numbers up to 15 are : 120
---
Run 2:
Enter Number  : 99
Sum of All Natural Numbers up to 99 are : 4950
---
Run 3:
Enter Number  : 456
Sum of All Natural Numbers up to 456 are : 104196
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.