Skip to main content

Recursion in C and C++

Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C++, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process". This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes be completed without the recursive call.




A simple example of recursion would be:
void recurse()
{
  recurse(); //Function calls itself
}

int main()
{
  recurse(); //Sets off the recursion
}
This program will not continue forever, however. The computer keeps function calls on a stack and once too many are called without ending, the program will crash. Why not write a program to see how many times the function is called before the program terminates?
#include <iostream>

using namespace std;

void recurse ( int count ) // Each call gets its own count
{
  cout<< count <<"\n";
  // It is not necessary to increment count since each function's
  //  variables are separate (so each count will be initialized one greater)
  recurse ( count + 1 );
}

int main()
{
  recurse ( 1 ); //First function call, so it starts at one      
}
This simple program will show the number of times the recurse function has been called by initializing each individual function call's count variable one greater than it was previous by passing in count + 1. Keep in mind, it is not a function restarting itself, it is hundreds of functions that are each unfinished with the last one calling a new recurse function.

It can be thought of like the Russian dolls that always have a smaller doll inside. Each doll calls another doll, and you can think of the size being a counter variable that is being decremented by one.

Think of a really tiny doll, the size of a few atoms. You can't get any smaller than that, so there are no more dolls. Normally, a recursive function will have a variable that performs a similar action; one that controls when the function will finally exit. The condition where the function will not call itself is termed the base case of the function. Basically, it is an if-statement that checks some variable for a condition (such as a number being less than zero, or greater than some other number) and if that condition is true, it will not allow the function to call itself again. (Or, it could check if a certain condition is true and only then allow the function to call itself).

A quick example:
void doll ( int size )
{
  if ( size == 0 )   // No doll can be smaller than 1 atom (10^0==1) so doesn't call itself
    return;          // Return does not have to return something, it can be used
                     //  to exit a function
  doll ( size - 1 ); // Decrements the size variable so the next doll will be smaller.
}
int main()
{
  doll ( 10 ); //Starts off with a large doll (it's a logarithmic scale)
}
This program ends when size equals one. This is a good base case, but if it is not properly set up, it is possible to have an base case that is always true (or always false).

Once a function has called itself, it will be ready to go to the next line after the call. It can still perform operations. One function you could write could print out the numbers 123456789987654321. How can you use recursion to write a function to do this? Simply have it keep incrementing a variable passed in, and then output the variable...twice, once before the function recurses, and once after...
void printnum ( int begin )
{
  cout<< begin;
  if ( begin < 9 )         // The base case is when begin is greater than 9
  {                           //  for it will not recurse after the if-statement
      printnum ( begin + 1 );
  }
  cout<< begin;         // Outputs the second begin, after the program has
                              //  gone through and output
}
This function works because it will go through and print the numbers begin to 9, and then as each printnum function terminates it will continue printing the value of begin in each function from 9 to begin.



Posted By:-Cplusplusprogramming

Popular posts from this blog

C++ Program to find the sum, difference, product and quotient of two integers

#include <iostream.h> #include <conio.h> void main() {   clrscr();   int x = 10;   int y = 2;   int sum, difference, product, quotient;   sum = x + y;   difference = x - y;   product = x * y;   quotient = x / y;   cout << "The sum of " << x << " & " << y << " is " << sum << "." << endl;   cout << "The difference of " << x << " & " << "y <<  is " << difference << "." << endl;   cout << "The product of " << x << " & " << y << " is " << product << "." << endl;   cout << "The quotient of " << x << " & " << y << " is " << quotient << "." << endl;   getch(); }

Program of virtual piano

//////////////Tested And Created By C++/////////////////////////////// #include<stdio.h> #include<dos.h> #include<conio.h> #include<stdlib.h> #define SHOW 1 #define HIDE 2 union REGS input,output; class piano {  public:int BIGKEY,MIDKEY,back,border;     piano()//init constructor     {         BIGKEY=15;         MIDKEY=1;         back=7;         border=15;     } }color; void drawpiano(int x,int y); int check_xy(int x,int y); void BOX(int c,int r,int c1,int r1,int col); int initmouse(); void setupscreen(); void pointer(int on); void restrictmouse(int x1,int y1,int x2,int y2); void check_keys(int x,int y); void getmouse(int *button,int *x,int *y); float freq[7] = {130.81, 146.83, 164.81, 174.61,196, 220, 246.94 } ; int n=0,a=4,backcolor=2,exitcode=1; void showbar(int t) {  if(t>65) t=65;  if(t<1) t=1;  textcolor(15);  for(int q=0;q<=t;t++)  {     gotoxy(3+q,4);     cprintf("Û");  } } void main() {  int

Putimage function in c

putimage function outputs a bit image onto the screen. Declaration:- void putimage(int left, int top, void *ptr, int op); putimage puts the bit image previously saved with getimage back onto the screen, with the upper left corner of the image placed at (left, top). ptr points to the area in memory where the source image is stored. The op argument specifies a operator that controls how the color for each destination pixel on screen is computed, based on pixel already on screen and the corresponding source pixel in memory. c smiling face animation This animation using c draws a smiling face which appears at random position on screen. See output below the code, it will help you in understanding the code easily. C programming code #include<graphics.h> #include<conio.h> #include<stdlib.h>   main() { int gd = DETECT, gm, area, temp1, temp2, left = 25, top = 75; void *p;   initgraph(&gd,&gm,"C:\\TC\\BGI");   setcolor(YELLOW);