- To print sum of 1 to N
User Input: 10
Output:
Sum of 1 to 10 : 55
import java.util.Scanner
fun main(args: Array<String>) {
print("Enter last number :")
val userInput = Scanner(System.`in`)
var n:Int = userInput.nextInt()
print("Sum of 1 to $n : "+ (n*(n+1))/2)
}
Enter last number : 10 Sum of 1 to 10 : 55Program
We are using the formula of sum of natural numbers (1 to N)
(N*(N+1))/2 // N is the last number
Concept