How to find the number of squares in an N*N grid with VB.NET

1 Answer

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

' 1x1 squares = 9 Squares
' 2x2 squares = 4 Squares
' 3x3 squares = 1 Squares

Imports System

Class CountSquares
    Private Shared Function CountSquaresInNxNGrid(ByVal N As Integer) As Integer
		' Formula: Total Squares = N * (N + 1) * (2N + 1) / 6
        Return (N * (N + 1) * (2 * N + 1)) / 6
    End Function

    Public Shared Sub Main()
        Dim N As Integer = 3

		' Validate input
        If N <= 0 Then
            Console.WriteLine("Grid size must be a positive integer!")
            Return
        End If

        Dim totalSquares As Integer = CountSquaresInNxNGrid(N)
		
        Console.WriteLine($"The total number of squares in a {N}x{N} grid is: {totalSquares}")
    End Sub
End Class



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

 



answered Aug 31, 2025 by avibootz
...