Home > Back-end >  Clarification for function that calls itself
Clarification for function that calls itself

Time:11-08

I'm just confused about this function code that kinda acts like a nested for loop but instead of a nested for loop it just calls the function

mostly just the line where it says

  // Draw pyramid of height n - 1
    draw(n - 1);


would the n not be 0 if you input 1 but it isnt ?? i just dont know the explanation of it

#include <iostream>
#include <string.h>

using namespace std;

int i;

void draw(int n);


int main() {
    
 // Get height of pyramid
    int height;
    cout << "Input Height: "; cin >> height;

    // Draw pyramid
    draw(height);
      return 0;
}



void draw(int n)
{
    // If nothing to draw
    if (n <= 0)
    {
        return;
    }

    // Draw pyramid of height n - 1
    draw(n - 1);

    // Draw one more row of width n
    for (int i = 0; i < n; i  )
    {
        printf("#");
    }
    printf("\n");
}

CodePudding user response:

This technique is called recursion. It is used a lot to divide a problem to smaller pieces. Lets say you give number 5, 1st if loop fails we move forward and call the draw(4), 2nd time the if loop fails we move forward and call draw(3) then again draw(2) and draw(1) and draw(0) now pay attention the if fails in draw(0). After that remember that the previous functions are not yet finished they are still open in stack(memory stack) so we go back to function draw(1) to line with for loop draw one #, then we go back to draw(2) cout the ##, finish that function and so on until we reach the draw(5) and finish after executing it.

I would suggest looking at some recursion problems like fibonacci to understand it better.

CodePudding user response:

I'm not sure if I understand correctly your concern. If your question is about recursive mechanism of this function the solution is really simple. Every height > 0 is going this way:

if (n <= 0)
{
    return;
}

draw(n - 1);

Now function stops because another one is called for n - 1 parameter. This continues until n <= 0. Then all previously stopped function calls from 1 to n are going there:

for (int i = 0; i < n; i  )
{
    printf("#");
}
printf("\n");

Someone already mentioned that it's called recursion. You should check this.

  • Related