Reputation: 305
Assume the user gives an input N to the function, how would I print these numbers from 1 to N (recursively or other wise).
example
print_numbers(40).
->1
->2
->…
->40
Upvotes: 0
Views: 2772
Reputation: 5645
You want to print numbers from 1 to N so print_numbers(N) can be translated in print_numbers(1, N).
Now what is print_numbers from X to Y ?
print_numbers from X to Y is print(X) and print_numbers from X+1 to N!
In Prolog, you will get :
print_numbers(N) :-
print_numbers(1, N).
% general case X must be lower than Y
print_numbers(X, Y) :-
X =< Y,
writeln(X),
X1 is X + 1,
print_numbers(X1, Y).
Upvotes: 4