Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,442 answers

573 users

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

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
*)

program CountSquares;

// Function to calculate the total number of squares in an N x N grid
function CountSquaresInNxNGrid(N: Integer): Integer;
begin
  // Formula: Total Squares = N * (N + 1) * (2N + 1) / 6
  CountSquaresInNxNGrid := (N * (N + 1) * (2 * N + 1)) div 6;
end;

var
  N, totalSquares: Integer;

begin
  N := 3;

  // Validate input
  if N <= 0 then
  begin
    writeln('Grid size must be a positive integer!');
    halt(1);
  end;

  // Calculate and display the total number of squares
  totalSquares := CountSquaresInNxNGrid(N);
  
  writeln('The total number of squares in a ', N, 'x', N, ' grid is: ', totalSquares);
end.



(*
run:

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

*)



 



answered Aug 31, 2025 by avibootz
edited Aug 31, 2025 by avibootz
...