Showing posts with label Recursion. Show all posts
Showing posts with label Recursion. Show all posts

Generation of Fibonacci Series - Recursion & Iteration -LISP

Program:
;;FIBONACCI SERIES
(defun fib(n)
    (setf a 0 b 1)
    (format t "~&<<<Generation of Fibonacci series with ~D terms>>>~&1.Iterative method~&2.Recursive method~&Enter your choice:" n)
    (setf x (read))
    (cond
        ((= n 1) (print a))
        ((= n 2) (print a)(print b))
        ((> n 2) (if (= x 1)
                (fib1 n))
        (if (= x 2)
             (do ((i 0 (+ i 1))) ((= i n))
                (print (fib2 i)))))
    )
)
(defun fib1(n)
                ;Iterative method
    (print a)(print b)
    (do((i 2 (+ i 1))) ((= i n))
        (setf c (+ a b))
        (print c)
        (setf a b b c))
)
(defun fib2(n)
    (cond
        ((= n 0) 0)
        ((= n 1) 1)
        ((> n 1)(+ (fib2 (- n 1)) (fib2 (- n 2))))
                ;Recursive method
    )
)

Output:
Break 2 [3]> (load 'f.lsp)
;;  Loading file f.lsp ...
;;  Loaded file f.lsp
T
Break 2 [3]> (fib 5)
<<<Generation of Fibonacci series with 5 terms>>>
1.Iterative method
2.Recursive method
Enter your choice:1

0
1
1
2
3
NIL
Break 2 [3]> (fib 5)
<<<Generation of Fibonacci series with 5 terms>>>
1.Iterative method
2.Recursive method
Enter your choice:2

0
1
1
2
3
NIL
Break 2 [3]>

Factorial of a number - C++

Program :
#include<iostream>
using namespace std;
int fr(int n);
   
int main()
{
 int n,fact=1,c,f,k=1;
 cout<<"Enter the number:";
 cin>>n;
 while(k==1)
 {
   cout<< "MENU\n\n1.USING ITERATION\n\n2.USING RECURSION\n\n3.EXIT\n\nENTER YOUR CHOICE:";
   cin>>c;
   switch(c)
    {
 
        case 1: if(n==0)
                cout<<"Factorial of 0 is 1";
               else
                 {
                 for(int i=1;i<=n;++i)
                    fact=fact*i;
                 cout<<"\nfactorial= "<<fact<<"\n\n";
                 }
                 break;
         case 2: f=fr(n);
                 cout<<"\nfactorial="<<f<<"\n\n";
                 break;
         case 3:k=0;
                break;
                
        default:cout<<"\nInvalid choice";
                break;
      }
   }
 return 0;
  
 }
 int fr(int n)
 {
   if(n==0)
    return 1;
   else
    return (n*fr(n-1));
  }

Output:
students@cselab-desktop:~$ g++ fact.cpp
students@cselab-desktop:~$ ./a.out
Enter the number:5
MENU

1.USING ITERATION

2.USING RECURSION

3.EXIT

ENTER YOUR CHOICE:1

factorial= 120

MENU

1.USING ITERATION

2.USING RECURSION

3.EXIT

ENTER YOUR CHOICE:2

factorial=120

MENU

1.USING ITERATION

2.USING RECURSION

3.EXIT

ENTER YOUR CHOICE:3
students@cselab-desktop:~$
Related Posts Plugin for WordPress, Blogger...