How to resolve the algorithm Pascal's triangle step by step in the Ada programming language
How to resolve the algorithm Pascal's triangle step by step in the Ada programming language
Table of Contents
Problem Statement
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be: So the triangle now looks like this: Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for n ≤ 0 does not need to be uniform, but should be noted.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Pascal's triangle step by step in the Ada programming language
Source code in the ada programming language
package Pascal is
type Row is array (Natural range <>) of Natural;
function Length(R: Row) return Positive;
function First_Row(Max_Length: Positive) return Row;
function Next_Row(R: Row) return Row;
end Pascal;
package body Pascal is
function First_Row(Max_Length: Positive) return Row is
R: Row(0 .. Max_Length) := (0 | 1 => 1, others => 0);
begin
return R;
end First_Row;
function Next_Row(R: Row) return Row is
S: Row(R'Range);
begin
S(0) := Length(R)+1;
S(Length(S)) := 1;
for J in reverse 2 .. Length(R) loop
S(J) := R(J)+R(J-1);
end loop;
S(1) := 1;
return S;
end Next_Row;
function Length(R: Row) return Positive is
begin
return R(0);
end Length;
end Pascal;
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line, Pascal; use Pascal;
procedure Triangle is
Number_Of_Rows: Positive := Integer'Value(Ada.Command_Line.Argument(1));
Row: Pascal.Row := First_Row(Number_Of_Rows);
begin
loop
-- print one row
for J in 1 .. Length(Row) loop
Ada.Integer_Text_IO.Put(Row(J), 5);
end loop;
Ada.Text_IO.New_Line;
exit when Length(Row) >= Number_Of_Rows;
Row := Next_Row(Row);
end loop;
end Triangle;
You may also check:How to resolve the algorithm Write entire file step by step in the BASIC programming language
You may also check:How to resolve the algorithm Scope/Function names and labels step by step in the 6502 Assembly programming language
You may also check:How to resolve the algorithm Inverted syntax step by step in the Fortran programming language
You may also check:How to resolve the algorithm Twin primes step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Phrase reversals step by step in the AWK programming language