Pages

Saturday, January 3, 2015

Write a Prolog program to find Factorial of a number


Hey friends let’s write a simple program to find factorial of a number using prolog. When we were in our ordinary level classes if someone asked us to find the factorial of a numbers simply we did …  J



But when we were doing our C Programming practicals they asked us to find the factorial of a number using RECURSION…..Then what we did was…




But you may wonder why I am talking about the recursion in C for finding the factorial in Prolog. Answer is quite simple “Because we are going to follow the same way to calculate the factorial value in prolog too. “In here only the approach is little bit different because we are going to use Facts, Rules, Goals and Queries for the fulfillment. But if you are a complete beginner and confused with these words please refer this simple tutorial (http://www.puiching.edu.hk/~wtchung/trace/Prolog/pro02.htm)

Okay hurry up and open your SWI Prolog…Before coding let’s move on to our ordinary level classes. While we are cording I may ask a question like “what is your answer for 0!”Then you have to say “0! = 1”.






Okay, now we are going to run the query. Let’s see what will happen…





Rather giving you the expected result 24 it will give you the below result.



To get the expected result we need to add a termination for this prolog program. We can add a termination by adding fact(0,1).







Now you have almost finished. Let’s meet with a path finding program soon ,Bye

No comments:

Post a Comment