Search code examples
delphimultidimensional-array2dnested-loops

How do I stop my nested loop? It loops over and over again. I only want 18 results not 81


image

var
  arrGame: array [1 .. 9, 1 .. 9] of char;
  arrPlanets: array [1 .. 9, 1 .. 9] of char;

implementation

{$R *.dfm}
{$R+}

procedure TfrmQ3.btnQ3_1StartGameClick(Sender: TObject);    
var
  i, j: integer;
  cGame: char; 
begin 
  btnQ2Play.Enabled := true;
  redQ3GameBoard.Clear; 
  redQ3incorrect.Clear; 
  for i := 1 to 9 do
  begin 
    for j := 1 to 9 do 
      arrGame[i,j] := '-'; 
  end; 

  for i := 1 to 9 do 
  begin
    for j := 1 to 5 do
    begin
      redQ3GameBoard.Lines.Add(arrGame[i,j]+ ' ' + arrGame[i,
        j] + ' ' + arrGame[i,j] + ' ' + arrGame[i,j] + ' ' + arrGame[i,
        j] + ' ' + arrGame[i,j] + ' ' + arrGame[i,j] + ' ' + arrGame[i,
        j] + ' ' + arrGame[i,j]);
    end; 
  end; 
end;

end.

On the top left is what my code is produces. The results I am trying to get are on the bottom left.

Photo of computer screen with IDE as described above


Solution

  • You basically have this code:

    for i = 1 to 9 do
      for j = 1 to 9 do
        List.Lines.Add(...)
    

    The statement

    List.Lines.Add(...)
    

    will run 9 × 9 = 81 times. Since this statement adds a line, you will get 81 lines. (Also, with nine identical values on each line! For example, when i = 4 and j = 6, you will print the value arrGame[4, 6] nine times on that row. Can you see how that is the case?)

    This is the flaw in your logic. You only want 9 lines, but each line should contain 9 components. Hence, you need to redesign the code.

    Since this seems like homework, I will not give you the solution in detail. Instead, I'll give you the following command-line program to study:

    program Project1;
    
    {$APPTYPE CONSOLE}
    
    {$R *.res}
    
    uses
      System.SysUtils;
    
    var
      Grid: array of array of Char;
    
    const
      N = 9;
    
    var
      i, j: Integer;
      s: string;
    
    function GetRandomLetter: Char;
    begin
      Result := Chr(Ord('A') + Random(Ord('Z') - Ord('A') + 1));
    end;
    
    begin
    
      try
        try
    
          Randomize;
          SetLength(Grid, N, N);
    
          // Build grid
          for i := 0 to N - 1 do
            for j := 0 to N - 1 do
              Grid[i, j] := GetRandomLetter;
    
          // Draw grid
          for i := 0 to N - 1 do
          begin
            s := Grid[i, 0];
            for j := 1 to N - 1 do
              s := s + #32 + Grid[i, j];
            Writeln(s);
          end;
    
    
        except
          on E: Exception do
            Writeln(E.ClassName, ': ', E.Message);
        end;
      finally
        Writeln('Press Return to exit.');
        Readln;
      end;
    
    end.
    

    Screenshot of program output: a 9-by-9 grid of capital letters.