Program 1: Using Relations.
Code:
Program 2: Input/Output from/to Console:
Code:
Program 3: Writing a Calculator.
Code:
Program 4: Find the bigger number in two numbers.
Code:
Program 5: Find the biggest number in three numbers.
Code:
Program 6: Find the factorial of a number.
Code:
Program 7: Solve the Problem of Towers of Hanoi.
Code:
Program 8: Display Fibonacci series upto a specified number of elements.
Program 9: Calculate GCD of two numbers.
Code:
parent(pam, bob). parent(tom, bob). parent(tom, liz). parent(bob, ann). parent(bob, pat). parent(pat, jim). male(tom). male(bob). male(pat). male(jim). female(pam). female(liz). female(ann). father(X, Y):-male(X), parent(X, Y). mother(X, Y):-female(X), parent(X, Y). grandFather(X, Y):-male(X), parent(Z, Y), parent(X, Z). grandMother(X, Y):-female(X), parent(Z, Y), parent(X, Z). greatGrandFather(X, Y):-parent(Z, Y), parent(Q, Z), father(X, Q). greatGrandMother(X, Y):-parent(Z, Y), parent(Q, Z), mother(X, Q). stepBrother(X, Y):-father(Z, X), father(Z, Y), mother(Q, X), not(mother(Q, Y)); mother(Z, X), mother(Z, Y), father(Q, X), not(father(Q, Y)).
Program 2: Input/Output from/to Console:
Code:
greetings:- write('What is your name?'), nl, read(X), write('Hello '), write(X).
Program 3: Writing a Calculator.
Code:
calculator:- write('Operations Supported: 1. addition 2. subtraction 3. multiplication 4. division 5. mod 6. squareRoot'), nl, write('What do you want to do?'), read(O), write('Operand 1: '), read(X), (O='squareRoot'->Answer is sqrt(X), write(Answer); write('Operand 2: '),read(Y), (O='addition'->write('Addition specified'),Answer is X+Y, write(Answer); (O='subtraction'->Answer is X-Y, write(Answer); (O='multiplication'->Answer is X*Y, write(Answer); (O='division'->Answer is X/Y, write(Answer); (O='mod'->Answer is mod(X,Y), write(Answer))))))).
Program 4: Find the bigger number in two numbers.
Code:
greater(X, Y):- (X>Y->write(X), write(' is greater than '), write(Y); (Y>X->write(Y), write(' is greater than '), write(X); write(X), write(' is equal to '), write(Y))).
Program 5: Find the biggest number in three numbers.
Code:
greatestThree(X, Y, Z):- ( (X<Y;X<Z) -> ( Y<Z -> write('Z is the greatest');write('Y is the greatest')); ((X=Y,Y=Z)->write('All are equal');write('X is the greatest'))).
Program 6: Find the factorial of a number.
Code:
fact(0,1). fact(N,F):-N>0, N1 is N-1, fact(N1, F1), F is F1*N.
Program 7: Solve the Problem of Towers of Hanoi.
Code:
hanoi(1, A, B, _):- write('Move disk from tower '), write(A), write(' to '), write(B), nl. hanoi(N, A, B, C):- N>1, N1 is N-1, hanoi(N1, A, C, B), hanoi(1, A, B, C), hanoi(N1, C, B, A).
Program 8: Display Fibonacci series upto a specified number of elements.
fibonacci(A, B, Upto):- Upto>0, Z is A+B, write(A), nl, fibonacci(B, Z, Upto-1).
Program 9: Calculate GCD of two numbers.
gcd(X, Y):- X=Y, write(X); X=0, write(Y); Y=0, write(X); X>Y, Z is X-Y, gcd(Z, Y); X<Y, Z is Y-X, gcd(X, Z).