1. Introduction
The sum of the first N natural numbers can be calculated using a simple arithmetic formula. However, in this guide, we will demonstrate two methods: one using the arithmetic progression formula and the other using a loop. This will offer a comparative perspective on the efficiency and clarity of both methods.
2. Program Overview
We'll begin by defining a number N (let's say 100 for this example). We will then apply the arithmetic formula to find the sum and subsequently use a loop to verify our result.
3. Code Program
// Define the number N
let N = 100
// Method 1: Using the formula for arithmetic progression
let sumUsingFormula = N * (N + 1) / 2
// Method 2: Using a loop
var sumUsingLoop = 0
for i in 1...N {
sumUsingLoop += i
}
// Print the results
print("Sum of first \(N) natural numbers using formula: \(sumUsingFormula)")
print("Sum of first \(N) natural numbers using loop: \(sumUsingLoop)")
Output:
Sum of first 100 natural numbers using formula: 5050 Sum of first 100 natural numbers using loop: 5050
4. Step By Step Explanation
1. let N = 100: Here, we specify N, the number up to which we want to calculate the sum.
2. let sumUsingFormula = N * (N + 1) / 2: This formula derives from the arithmetic progression of natural numbers. The formula calculates the sum of the first N natural numbers directly without iterating through each number.
3. In the loop method, we initialize a variable sumUsingLoop to zero. The for loop then iterates from 1 to N, adding each number to the sum in each iteration.
4. Lastly, we print the results from both methods to demonstrate that they indeed produce the same result.