for-loopnested-loopspascal

Pascal - Shape Drawing


So the task is to draw this shape :

******
**  **
*    *
**  **
******

The number of rows is set by the user,and it is labeled as n.In this case it is n=3. So i tried splitting it in two , and i managed to get an output looking like this.

***
**
*
**
***
***
 **
  *
 **
***

My code :

translation : brojredova is number of rows
brojzvezda is number of stars *
broj praznih is number of empty fields
--------------------------------------------
program veasdsa; 
var 
  n,brojredova,brojzvezda,brojpraznih : integer;

begin
  readln(n);

  // prva polovina 1st half

  for brojredova := 1 to n do
  begin  
    // *
    for brojzvezda := 1 to ((n-brojredova) + 1) do
    begin
      write('*');
    end;

    writeln;
  end;       

  for brojredova := 2 to n do
  begin
    for brojzvezda := 1 to brojredova do
    begin
      write('*');
    end;

    writeln;
  end;   // ovde pocinje druga polovina ( second half starts from here)

  for brojredova := 1 to n do
  begin
    //prazna
    for brojpraznih := 1 to (brojredova - 1) do
    begin
      write(' ');
    end;

    // * 
    for brojzvezda := 1 to ((n - brojredova) + 1) do
    begin
      write('*');
    end;

    writeln;
  end;

  for brojredova := 2 to n do
  begin
    //prazna
    for brojpraznih := 1 to (n - brojredova) do
    begin
      write(' ');
    end;

    // * 
    for brojzvezda := 1 to brojredova do
    begin
      write('*');
    end; 
        
    writeln;
  end;
end.

I can't figure out how to get them together.. There is probably an easier way,but i tried doing it like this.


Solution

  • Let's simplify by writing a very basic procedure which prints a character repeatedly.

    procedure print_char_times (ch : char; n : integer);
    var
      i : integer;
    begin
      for i := 1 to n do
        write (ch)
    end;
    

    Now you don't need to repeat this loop over and over. With this defined, you just need to count i from 0 to n - 1 to get the top half of the shape:

    • Print '*' n - i times.
    • Print ' ' i * 2 times.
    • Print '*' n - i times.

    It's very straightforward to translate this to code.

    program Test;
    var
      i, n : integer;
    
      procedure print_char_times (ch : char; n : integer);
      var
        i : integer;
      begin
        for i := 1 to n do
          write (ch)
      end;
    
    begin
      n := 3;
    
      for i := 0 to n - 1 do
      begin
        print_char_times('x', n - i);
        print_char_times(' ', i * 2);
        print_char_times('x', n - i);
        writeln
      end;
    
      for i := n - 2 downto 0 do
      begin
        print_char_times('x', n - i);
        print_char_times(' ', i * 2);
        print_char_times('x', n - i);
        writeln
      end
    end.