Trójkąty z gwiazdek rekurencyjnie.

0

Możecie mnie naprowadzić jakoś ja rekurencyjnie zrobić z gwiazdek poniższy wzór?
Przykład dla n=5:

*****
****
***
**
*
 
program zs;

{$APPTYPE CONSOLE}

uses
  SysUtils;
function gwiazdki(n:integer):integer;
  var
  i:integer;
  begin
    if (n<>1) then result:=gwiazdki(n-1);
    write('*');
  end;
var
  n:integer;
begin
  writeln('Podaj N:');
  readln(n);
  gwiazdki(n);
  readln;
end.
1
procedure gwiazdki(n:integer);
var i:integer;
begin
    if n>0 then
    begin
      for i=1 to n Write('*');
      WriteLn;
      gwiazdki(n-1);
    end;
end;
0

Zapomniałem dodać jeszcze, że w programie nie można użyć pętli

0

Więc potrzebujesz dodać jeszcze jeden parametr.

2
procedure StarsLine(ALength: Integer);
begin
  if ALength > 0 then
  begin
    WriteLn(StringOfChar('*', ALength));
    StarsLine(ALength - 1);
  end;
end;

@morodis - nie ma pętli; A jeśli jej poszukać, to StringOfChar także jej nie posiada, dopiero użyty w niej FillChar gdzieś tam na najniższym poziomie ją posiada;

Przykład bez pętli i funkcji je maskujących:

procedure StarsLine(ALength, AStarIdx: Integer);
begin
  if ALength = 0 then Exit();

  if AStarIdx > ALength then
  begin
    WriteLn();
    StarsLine(ALength - 1, 1);
  end
  else
  begin
    Write('*');
    StarsLine(ALength, AStarIdx + 1);
  end;
end;

Gdyby posłużyć się funkcją IfThen z modułu StrUtils, kod skróci się do poniższej postaci:

uses
  StrUtils;

  procedure StarsLine(ALength, AStarIdx: Integer);
  begin
    if ALength = 0 then Exit();

    Write(IfThen(AStarIdx > ALength, #10, '*'));

    if AStarIdx > ALength then
      StarsLine(ALength - 1, 1)
    else
      StarsLine(ALength, AStarIdx + 1);
  end;

Można też użyć stałej tablicy znaków, indeksowanej typem Boolean, jednak to redundantne; Szkoda, że w Delphi czy Free Pascalu nie wymyślili jeszcze operatora trójargumentowego...

Dorzućmy jeszcze jeden parametr i IfThen z modułu Math, a wyjdzie jeszcze krócej:

uses
  StrUtils, Math;

  procedure StarsLine(ALength, AStarIdx: Integer; AEoL: Boolean);
  begin
    if ALength = 0 then Exit();

    Write(IfThen(AEoL, #10, '*'));
    StarsLine(IfThen(AEoL, ALength - 1, ALength), IfThen(AEoL, 1, AStarIdx + 1), AStarIdx = ALength);
  end;

Nie no żartuję - wyszedł potwór.

1 użytkowników online, w tym zalogowanych: 0, gości: 1