How to multiply a string?

I have an exercise that requires me to make a a right angled triangle using + signs but the row of the triangle is determined by the user. and for each line, the + sign will have one more. Example :
+
++
+++

Hm, well, I’d do it like:

Function "+"( Left : Character; Right : Natural ) return String is
  ( String'(1..Right => Left) );
--OR
Function "+"( Left : String; Right : Natural ) return String is
Begin
  Return Result : String(1..Left'Length*Right) do
    For Index in 1..Right loop
        declare
           Offset : Constant Natural := Natural'Pred( Index ) * Left'Length;
           Chunk  :  String renames Result(Offset..Natural'Pred(Offset+Left'Length) );
        begin
           Chunk:= Right;
        end;
    End loop;
  End return;
End "+";

…but I think there’s a "*" function in Ada.Strings.Fixed; use that.

Thanks ! but is there a simpler solution by using while loop ?

why use “while” when you know the length / number of iterations ? This is what “*” must be doing under the hood, there’s no point rewriting it.

You can use Ada.Strings.Fixed.
Spot this:

--  String constructor functions

   function "*" (Left  : in Natural;
                 Right : in Character) return String;

   function "*" (Left  : in Natural;
                 Right : in String) return String;

Concretely, you can write
10 * '+'
And you’ll get
"++++++++++"

1 Like

In this program, I have to ask the user to put the number of lines.

So?

Declare
   Function Prompt return Natural is
   Begin
      loop
         Ada.Text_IO.Put( "How many? " );
         declare
            Response : String renames Ada.Text_IO.Get_Line;
         begin
            Return Natural'Val( Response );
         exception
            when Constraint_Error => Null;
         end;
      end loop;
   End;

   Iterations : Natural renames Prompt;
Begin
   For X in 1..Iterations loop
      Null; -- Stuff
   end loop;
End;
procedure Output_Triangle (Num_Lines : in Positive) is
begin
   for N in 1 .. Num_Lines loop
      Ada.Text_IO.Put_Line (Item => (1 .. N => '+') );
   end loop;
end Output_Triangle;
1 Like

alright thanks a bunch !