Q&A: Recursion

What is iterative problem solving?

Solving problems using loops.

What is recursive problem solving?

Solving problems by breaking them into smaller, but idential, steps and calling the function over and over with different parameters.

What is a recursive case?

The state(s) where the function will call itself.

What is a terminating case?

The state(s) where the recursive function returns a value.

Give the code for your iterative and recursive implementations of the following functions:

1. Count up

void CountUp_Iterative( int start, int end )
{
  for ( int i = start; i <= end; i++ )
  {
    cout << i << endl;
  }
}

void CountUp_Recursive( int start, int end )
{
  // Terminating case
  if ( start > end ) { return; }

  // Recursive case
  cout << start << endl;
  CountUp_Recursive( start+1, end );
}

2. Sum up

int SumUp_Iterative( int start, int end )
{
  int sum = 0;
  for ( int i = start; i <= end; i++ )
  {
    sum += i;
  }
  return sum;
}

int SumUp_Recursive( int start, int end )
{
  // Terminating case
  if ( start > end ) { return 0; }

  // Recursive case
  return start + SumUp_Recursive( start+1, end );
}

Author: Rachel Wil Sha Singh

Created: 2023-10-30 Mon 12:30

Validate