In the highschool I’ve had a very good programming teacher. I remember her ‘famous’ quote – ‘keep your mind awake!’ (she liked so much this quote, that she was telling it several times on each curse). At that time I didn’t understand how true it was. Today I’ve had some free time and I remembered that I haven’t work for several months with recursion, so why not to make a small exercise? First component I’ve saw on the project I’m working it was a TMainMenu component. Simply, get with a recursion function, all items captions from a menu.
On a form, drop a TMainMenu component, and set several menu items. Also, drop a TMemo component on the form. Exercise is very simple: list on the TMemo all the menu’s items names. First time by using loops (choose from ‘for’, ‘while’ or ‘repeat’ – explication for each one of them can be found here) and second time by using recursion! In 5-10 minutes you should finish this exercise. Below is how I’ve resolved it. If you have find a better way, shout
procedure GetItemsCaption; var wi:Integer; wj:Integer; begin for wi:=MainMenu1.Items.Count-1 downto 0 do if MainMenu1.Items[wi] is TMenuItem then begin Memo1.Lines.Add( TMenuItem(MainMenu1.Items[wi]).Caption); For wj:=TMenuItem(MainMenu1.Items[wi]).Count-1 downto 0 do Memo1.Lines.Add( TMenuItem(MainMenu1.Items[wi]).Items[wj].Caption); end; end; {recursion function bring it on!!!!} procedure GetRecursiveItemsCaption; var wj:Integer; function GetMenuItems(aMenuItem:TMenuItem):TStringList; var wi:integer; begin Memo1.Lines.Add(aMenuItem.Caption); wi:=aMenuItem.Count-1; while wi>=0 do begin GetMenuItems(aMenuItem.Items[wi]); dec(wi); end; end;//GetMenuItems ends here //body of a function/procedure from your form begin //first on the 'loop' style procedure GetItemsCaption; Memo1.Lines.Add('recursion'); //'recursive' style For wj:=MainMenu1.Items.Count-1 downto 0 do GetMenuItems(MainMenu1.Items[wj]); end;
Is better sometimes to make this kind of exercises to remember some basic stuff.