understanding recursion

Hi

Am trying to understand recursion. Found 2 programmes from a book I am working through at the moment, to help me work through this.
The first I understand. First
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
void countdown (int n);
int main() {
  countdown (4);
  return 0;
}

void countdown(int n) {
  std::cout << "Count down ... " << n << std::endl;
  if (n > 0)
    countdown(n-1);
  std::cout << "Count up ... " << n << " memory address of n " << &n << std::endl;
}

So clearly, the variable "n" is unique to each call of the function.
The second however is somewhat unclear to me.
Second
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
const int Len{66};
const int Divs{6};
void subdivide (char [], int , int, int );

int main() {
  char ruler[Len];
  int i;
  for (i = 1; i < (Len-2); i++)
    ruler[i] = ' ';

  ruler[Len-1] = '\0';
  int max = Len-2;
  int min{0};

  ruler[min] = ruler[max] ='|';
  std::cout << ruler << std::endl;

  for (i = 1; i <= Divs; i++) {
    subdivide(ruler,min,max, i);
    std::cout << ruler << std::endl;
    for (int j=1; j < (Len -2); j++)
      ruler[j] = ' ';
  }
  return 0;
}

void subdivide (char ar[], int low, int high, int level) {
  if (level == 0)
    return;
  int mid = (high + low) /2;
  ar[mid] = '|';
  subdivide(ar, low, mid, level - 1);
  subdivide(ar, mid, high, level -1);
}

Question I have is, is the call to subdivide repeated for each level, So if Level reaches zero, control goes back to the for loop in main, so Level is incremented, but "min" and "max" are still the same, so when subdivide is called Level 1 is repeated, is that correct ?

So if Level is 3, Level 1 would have been performed 3 times and level 2 twice. Is my understanding correct?
Last edited on
Topic archived. No new replies allowed.