Swift Program – Find Sum of First N Natural Numbers

Find Sum of First N Natural Numbers

To find sum of first n Natural Numbers, we can use for loop with range 1...n and accumulate the sum during each iteration. Or, we can use the formula to find the sum of first n Natural Numbers.

Using For Loop

In the following program, we will take a value of 10 for n, and find the sum of first n Natural Numbers using for loop.

main.swift

import Foundation

var n = 10
var sum = 0

for i in 1...n {
    sum += i
}

print("The sum of first \(n) natural numbers is \(sum)")

Program Output

The sum of first 10 natural numbers is 55

Using Formula

The formula to find the sum of first n Natural Number is n(n+1)/2. In the following program, we will use this formula to find the sum.

main.swift

import Foundation

var n = 10
var sum = n*(n+1)/2

print("The sum of first \(n) natural numbers is \(sum)")

Program Output

The sum of first 10 natural numbers is 55

Summary

Summarising this tutorial, we learned how to find the sum of first n Natural Numbers using for loop or formula.