I have to define the prolog pyramid(N) that prints out a pyramid of asterisks of given height as in the following example.
pyramid(4).
*
***
*****
*******
true
this is what i have done so far... I can't find the way to print out the rest of stars needed for each lines.. I also tried to define support predicates to handle subparts of the program.but failed to find one.
pyramid(0) :-
nl.
pyramid(N) :-
N > 0,
N1 is N - 1,
foreach(between(1,N1,_), write(' ')),
write('*'), nl,
pyramid(N1).
Think of how many stars each level gets in terms of
N
. Say you are at linei
, with N = 4.N-1
) spaces, a star, and another 3 spaces.i
th line gets(N - 1) - (i - 1)
spaces,1 + 2 * (i - 1)
stars, and another(N - 1) - (i - 1)
spaces.So that gives:
I think (but not sure) you can also remove the
N > 0
bit since the casepyramid(0, _)
will be checked first.Something like should do you: