How to find the number of squares in an N*N grid with C++

2 Answers

0 votes
/*
Total squares in a 3 * 3 grid are 14

1x1 squares = 9 Squares
2x2 squares = 4 Squares
3x3 squares = 1 Squares
*/

#include <iostream>

// Function to calculate the total number of squares in an N x N grid
int countSquaresInNxNGrid(int N) {
    if (N <= 0) {
        throw std::invalid_argument("Grid size must be a positive integer.");
    }

    int totalSquares = 0;

    // Sum of squares of side lengths from 1 to N
    for (int k = 1; k <= N; k++) {
        totalSquares += k * k;
    }

    return totalSquares;
}

int main() {
    int N = 3;

    try {
        int totalSquares = countSquaresInNxNGrid(N);
        std::cout << "The total number of squares in a " << N << "x" << N << 
                     " grid is: " << totalSquares << std::endl;
    } catch (const std::exception &e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
}



/*
run:
    
The total number of squares in a 3x3 grid is: 14
    
*/

 



answered Aug 31, 2025 by avibootz
edited Aug 31, 2025 by avibootz
0 votes
#include <iostream>

// Function to calculate the total number of squares in an N x N grid
int countSquaresInNxNGrid(int N) {
    // Formula: Total Squares = N * (N + 1) * (2N + 1) / 6
    return (N * (N + 1) * (2 * N + 1)) / 6;
}

int main() {
    int N = 3;

    // Validate input
    if (N <= 0) {
        std::cout << "Grid size must be a positive integer!" << std::endl;
        return 1;
    }

    // Calculate and display the total number of squares
    int totalSquares = countSquaresInNxNGrid(N);
    
    std::cout << "The total number of squares in a " << N << "x" << N << 
                 " grid is: " << totalSquares << std::endl;
}



/*
run:
    
The total number of squares in a 3x3 grid is: 14
    
*/

 



answered Aug 31, 2025 by avibootz
...