Code to be explained

How does the number of + signs increases for each line by using this program ? I’m still quite lost

with Ada.Text_IO; – For input and output
with Ada.Integer_Text_IO; – For handling integer inputs

procedure Plus_Triangle is
– Declare variables
Lines : Integer; – The number of lines
I : Integer; – Line counter
J : Integer; – ‘+’ counter for each line

begin
– Prompt the user for the number of lines
Ada.Text_IO.Put("Enter the number of lines: ");
Ada.Integer_Text_IO.Get(Lines); – Get the number of lines from user input

– Initialize the outer loop counter
I := 1;

– Outer while loop for each line
while I <= Lines loop
– Initialize the inner loop counter for the ‘+’ symbols
J := 1;

  -- Inner while loop to print the '+' symbols for the current line
  while J <= I loop
     Ada.Text_IO.Put("+");
     J := J + 1;
  end loop;

  -- Move to the next line
  Ada.Text_IO.New_Line;

  -- Increment the line counter
  I := I + 1;

end loop;

end Plus_Triangle;

Can anybody give me a clarification regarding the inner loop ?

I’m not great at teaching, so have a look here.

You should edit your post and add triple back ticks to make the code readable.

Hi, It’s increasing because the upper bound, “I”, is increased after each line.

Well, you have several things going on:

  1. Obtain some user-input;
  2. Using a while-loop, (the comment indicates a for iteration though;
  3. Using a second while-loop, which comment indicates is possibly a for iteration.

Given these considerations, I have to ask: are these examples from a book or tutorial? If so, are they from some other, non-Ada language?

Because, as I read it, your procedure is equivalent to:

with
Ada.Text_IO,
Ada.Integer_Text_IO;

Procedure Plus_Triangle is
   Lines : Integer; – The number of lines
Begin
   Ada.Text_IO.Put("Enter the number of lines: ");
   Ada.Integer_Text_IO.Get(Lines);
   OUTER:
   For I in 1..Lines loop
      INNER:
      For J in 1..I loop
         Ada.Text_IO.Put( "+" );
      End loop INNER;
      Ada.Text_IO.New_Line;
   End loop OUTER;
End Plus_Triangle;

So, observably the inner loop goes from 1 to whatever value I is, where I is ranging from 1 to the user-input Lines.

Yes, and the output part of this can be simplified even further to

for I in 1 .. Lines loop
   Ada.Text_IO.Put_Line (Item => (1 .. I => '+') );
end loop;

which is even clearer. This was shown to the OP in this post, so perhaps there is some unstated reason for taking the more complex, unclear approach.

1 Like