mazen el zoor
mazen el zoor

Reputation: 305

Prolog print numbers from 1 to N?

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

Answers (2)

fferri
fferri

Reputation: 18950

Using between/3 and forall/2:

?- forall(between(1, 40, X), writeln(X))
1
2
3
...
39
40
true.

Upvotes: 3

joel76
joel76

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

Related Questions