- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

# Program to find number of squares in a chessboard in C++

In this problem, we are given the size of a chessboard. Our task is to create a program to find number of squares in a chessboard in C++.

**Problem Description** − To find the number of squares in a chessboard. We will have to calculate all the combinations of the square that are inside the chessboard i.e. we will consider squares of side 1x1, 2x2, 3x3 … nxn.

**Let’s take an example to understand the problem,**

**Input:** n = 4.

**Output**: 30

Squares of size 1x1 -> 16 Squares of size 2x2 -> 9 Squares of size 3x3 -> 4 Squares of size 4x4 -> 1 Total number of squares = 16+9+4+1 = 30

**Solution Approach:**

A simple approach is by using the sum formula for nxn grid. Let’s deduct the general formula for the sum, sum(1) = 1 sum(2) = 1 + 4 = 5 sum(3) = 1 + 4 + 9 = 14 sum(4) = 1 + 4 + 9 + 16 = 30 The sum is can be generalised as sum = 12 + 22 + 32 + 42 + … n2 sum = ( (n*(n+1)*((2*n) + 1))/6 )

## Example

#include <iostream> using namespace std; int calcSquaresCount(int n){ int squareCount = ( (n * (n+1) * (2*n + 1))/6 ); return squareCount; } int main() { int n = 6; cout<<"The total number of squares of size "<<n<<"X"<<n<<" is "<<calcSquaresCount(n); }

## Output:

The total number of squares of size 6X6 is 91

- Related Questions & Answers
- Program to Find Out the Number of Squares in a Grid in Python
- Count squares with odd side length in Chessboard in C++
- Program to count number of perfect squares are added up to form a number in C++
- Count number of squares in a rectangle in C++
- Program to determine color of a chessboard square using Python
- Is a number sum of two perfect squares in JavaScript
- Transform to Chessboard in C++
- Minimum number of squares whose sum equals to given number n
- Java Program to Find Factorial of a number
- Program to find super digit of a number in Python
- Program to find number of nodes in a range in Python
- Python program to filter perfect squares in a given series
- C# Program to find number of occurrence of a character in a String
- To find sum of even factors of a number in C++ Program?
- Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10

Advertisements