
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Cube Sum of First N Natural Numbers in Swift
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.