Recent

Author Topic: For loops  (Read 1227 times)

Don_Zagor

  • New Member
  • *
  • Posts: 25
For loops
« on: December 15, 2018, 11:37:34 am »
Hey guys, I have a stupid question.
Does this:
Code: Pascal  [Select][+][-]
  1.                                    for i:=1 to 4 do
  2.                                          for j:=1 to 13 do
  3.                                                cards[x,y]:=suit[x] + rank[y];
  4.  
begin with i:=1 and then goes for j:=1 to 13, and when that is done it then goes to i:=2 and j:=1 to 13...?

navodar

  • Guest
Re: For loops
« Reply #1 on: December 15, 2018, 11:45:36 am »
Yes.

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: For loops
« Reply #2 on: December 15, 2018, 12:25:59 pm »
You probably intended the for loop variables i and j to affect which cards[] array value is set.
However, you use non-loop variables (x and y) in your arrays, so you iterate over the same cards[x,y] value 52 times.
Rather than ask on this forum, it is far better to simply experiment yourself to learn how loop iteration works in practice.
Something like
Code: Pascal  [Select][+][-]
  1. program project1;
  2.  
  3. {$Mode objfpc}{$H+}
  4.  
  5. type
  6.   TSuitRange = 1..4;
  7.   TSuitArray = array[TSuitRange] of Integer;
  8.  
  9.   TRankRange = 1..13;
  10.   TRankArray = array[TRankRange] of Integer;
  11.  
  12.   TCards = array[TSuitRange, TRankRange] of Integer;
  13.  
  14. var
  15.   suit: TSuitArray;
  16.   rank: TRankArray;
  17.   cards: TCards;
  18.   s, r: Integer;
  19. begin
  20.   for s in TSuitArray do
  21.     suit[s] := s;
  22.   for r in TRankArray do
  23.     rank[r] := r;
  24.   for s in TSuitArray do
  25.     for r in TRankArray do
  26.       cards[s, r] := suit[s] + rank[r];
  27.   for s in TSuitArray do
  28.     for r in TRankArray do
  29.       WriteLn('cards[',s,',',r,']=',cards[s,r]);
  30.   ReadLn;
  31. end.
« Last Edit: December 15, 2018, 12:27:56 pm by howardpc »

creaothceann

  • Full Member
  • ***
  • Posts: 117
Re: For loops
« Reply #3 on: December 15, 2018, 01:39:47 pm »
Open the Watches window (Ctrl+Alt+W), add the variables as expressions, and step through the program (F7).

 

TinyPortal © 2005-2018