Addition using Recursion


As a simple rule of recursion, any function can be computed using a recursive routine if :
1. The function can be expressed in its own form.
2. There exists a termination step, the point at which f(x) is known for a particular ‘x’.

Therefore to write a recursive program for addition of 2 numbers, we have to express addition in a recursive form using the above 2 rules :
1. add(m,n) = add(m,n-1)+1 (recursive defination of addition).
2. if n=0, return m (termination step).
Using these 2 rules, the recursive program of addition can be coded very easily as shown :

#include "stdio.h"
#include "conio.h"
int y;
add(int m,int n)
	{ if(n==0)
	   return m;
	  y=add(m,n-1)+1;
	  return y;
	}
main()
	{ int a,b,r;
	  clrscr();
	  printf("enter the two numbers : ");
	  scanf("%d%d",&a,&b);
	  r=add(a,b);
	  printf("%d",r);
	  getch();
	  return 0;
	}


Related Posts

Share

Filed Under: CCodes

Tags:

About the Author: Software Engineer - Advanced Search & Recommendation at Rovi

RSSComments (3)

Leave a Reply | Trackback URL

  1. vidya says:

    please can anyone tell me how to type a program in java for below format of matrix
    |1 2| |1 2| |2 4| |6 | |6|
    | | + | | = | |= | | = | | = |11| = |2|
    |3 4| |3 4| |6 8| |14| |5|

  2. rhen says:

    I am a beginner in programming language and I really need help.
    And I like this website because it gives simple sample programs and source codes that can simplify things rather than make a program complicated.
    It uses only stdio.h….great..!
    I hope that there are lectures or tutorials for beginners like me
    and there are simple sample codes.

    • Saurabh says:

      Hi rhen,
      Thanks for your appreciation. I had started this website when I was a student (now I work as Android Games Developer), just for the love for programming.
      As for helping you, I’ll be glad to do that. I dont have any lectures pre prepared, but if you want I can take your online sessions on skype for helping you out.
      Needless to say, this will all be free of cost.
      For further details you can contact me at geeks@programminggeeks.com or saurabh.v1@gmail.com

Leave a Reply

*

AWSOM Powered