Swift Program to Calculate Cube Sum of First n Natural Numbers


This tutorial will discuss how to write swift program to calculate cube sum of first n natural numbers.

Natural numbers are those number which include all the positive number starting from 0 to infinite for example, 1, 2, 3, 4, ……n. Now we find the cube sum of first n natural numbers: 1+23+33+43 = 1 + 8 + 27 + 64 = 100.

Below is a demonstration of the same −

Input

Suppose our given input is −

Num = 5

Output

The desired output would be −

Cube Sum of first 5 numbers are 225.

Algorithm

Following is the algorithm −

Step 1 - Declare a variable to store number.

Step 2 - Declare another variable to store the cube sum of natural numbers

Step 3 - Run for loop and find the cube sum of the natural numbers −

for i in 1...num
{
   sum += i * i * i
}

Step 4 - Display output

Example

The following program shows how to calculate cube sum of first n natural numbers.

import Foundation
import Glibc

// Number
var num = 4
var sum = 0

// Finding the cube sum of first 4 natural numbers
for i in 1...num
{
   sum += i * i * i
}
print("The cube sum of first 4 natural numbers is", sum)

Output

The cube sum of first 4 natural numbers is 100

Here in the above code we find the cube sum of first 4 natural numbers using the following code −

for i in 1...num
{
   sum += i * i * i
}

So the working of the above code is −

num = 4

sum = 0

1st iteration: sum = sum + 1 * 1 * 1 = 0+1 = 1

2nd iteration: sum = 1 + 2 * 2 * 2 = 1+8 = 9

3rd iteration: sum = 9 + 3 * 3 * 3 = 9+27 = 36

4th iteration: sum = 36 + 4 * 4 * 4 = 36+64 = 100.

Hence the cube sum of first 4 natural numbers is 100.

Updated on: 30-Nov-2022

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements