# Find number of squares inside a given square grid in C++

In this tutorial, we will check out how to find the number of squares inside a given square grid in C++ with the corresponding code.

If the square grid contains a side of N*N, then we are going to find the total number of squares present in it.

## calculate the number of squares inside a square grid in C++

If we observe the number of squares that exist in smaller square grids then we can draw a pattern that will guide us to construct a simple formula to find the number of squares in a square grid of any length.

- The total number of squares in a square grid of side 1 =1.
- Total number of squares in a square grid of side 2 =5. ⇒ 4 small squares, and 1 2×2 square.
- The total number of squares in a square grid of side 3 =14. ⇒ 9 small squares, 4 2×2 squares and 1 3×3 square.
- The total number of squares in a square grid of side 4 =30. ⇒ 16 small squares, 9 3×3 squares, 4 2×2 squares and 1 4×4 square.

**By observing above sentences we can draw a pattern** - 1×1 :-1^2 = 1.
- 2×2 :- 2^2 + 1^2 = 5.
- 3×3 :- 3^2 + 2^2 + 1^2 = 14.
- 4×4 :- 4^2 + 3^2 + 2^2 + 1^2 = 30.
- Likewise, for nxn is n^2 + (n-1)^2 + (n-2)^2…………….(n-n+1)^2.

`Then N(s)n = n^2 + (n-1)^2 + (n-2)^2................(n-n+1)^2 = n(n + 1)(2n + 1)/6`

**1.By using the formula N(s)n = n^2 + (n-1)^2 + (n-2)^2…………….(n-n+1)^2:**

#include <bits/stdc++.h> using namespace std; int main() { int n,squares=0; cout<<"enter the length of a square:"; cin>>n; while(n>0) { squares += pow(n, 2); n--; } cout<<"no of squares in a square grid:"<<squares; return 0; }

**Output: **

enter the length of a square:5 no of squares in a square grid:55

2.**By using the formula N(s)n =n(n + 1)(2n + 1)/6:**

#include <iostream> using namespace std; int squares(int n) { return n * (n + 1) * (2 * n + 1) / 6; } int main() { int m; cout<<"enter length of a square:"; cin>>m; cout <<"no of squares in a square grid:"<< squares(m); return 0; }

**Output: **

enter length of a square:10 no of squares in a square grid:385

Similarly, you can find the number of squares inside a given square grid of any length by using these programs.

Thus, I hope this tutorial will help you.

## Leave a Reply