In mathematics, a **pyramid number**, or **square pyramidal number**, is a figurate number that represents the number of stacked spheres in a pyramid with a square base. Square pyramidal numbers also solve the problem of counting the number of squares in an *n* × *n* grid.

A Square pyramidal number represents sum of squares of first natural numbers. First few Square pyramidal numbers are 1, 5, 14, 30, 55, 91, 140, 204, 285, 385, 506, …

In this example i’ll show you How to calculate Sum of squares of first n natural numbers in C#.

**C# Code:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
static void Main(string[] args) { int sum = 0; Console.Write("N : "); int n = Convert.ToInt32(Console.ReadLine()); for(int i = 1; i <= n; i++) { sum = 0; for(int j=1;j<=i;j++) { sum += j * j; Console.Write(j+"^2"); if (j != i) { Console.Write(" + "); } else { Console.Write(" = "); } } Console.Write(sum); Console.WriteLine(); } Console.ReadKey(); } |