C# Examples
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C# Program - Calculate sum of Cubes of Natural numbers



In Mathematics, the natural numbers are all positive numbers which is used for counting like 1, 2, 3, 4, and so on. The smallest natural number is 1.

Objective: Write a C# program which returns sum of cubes of natural numbers starting from 1 to given natural number n, (13 + 23 + 33 + ... + n3).

Method 1: Using while loop

The example below shows how to use while loop to calculate sum of cubes of first n natural numbers.

using System;

class MyProgram {
  static void Main(string[] args) {
    int n = 10;
    int i = 1;
    int sum = 0;

    ///calculating sum of cubes from 1 to n
    while(i <= n) {
      sum += i*i*i;
      i++;
    }

    Console.WriteLine("Sum is: " + sum);
  }
}

The above code will give the following output:

Sum is: 3025

Method 2: Using for loop

The same can be achieved using for loop. Consider the example below:

using System;

class MyProgram {
  static void Main(string[] args) {
    int n = 10;
    int sum = 0;

    //calculating sum of cubes from 1 to n
    for(int i = 1; i <= n; i++)
      sum += i*i*i;

    Console.WriteLine("Sum is: " + sum);
  }
}

The above code will give the following output:

Sum is: 3025

Method 3: Using Recursion

Similarly, recursion can be used to calculate the sum.

using System;

class MyProgram {
  //recursive method
  static int Sum(int n) { 
    if(n == 1)
      return 1;
    else
      return (n*n*n + Sum(n-1));
  } 

  static void Main(string[] args) {
    Console.WriteLine("Sum of Cubes of first 10 natural numbers: " + Sum(10));
    Console.WriteLine("Sum of Cubes of first 20 natural numbers: " + Sum(20));
  }
}

The above code will give the following output:

Sum of Cubes of first 10 natural numbers: 3025
Sum of Cubes of first 20 natural numbers: 44100

Method 4: Using Mathematical Formula

The sum of cubes of first n natural numbers can be mathematically expressed as:

Sum of Cubes of Natural numbers
using System;

class MyProgram {
  static void Main(string[] args) {
    int n = 10;

    //calculating sum of cubes from 1 to n
    int sum = n*(n+1)/2;
    sum *= sum;

    Console.WriteLine("Sum is: " + sum);
  }
}

The above code will give the following output:

Sum is: 3025



5