Home > Software design >  Print recursive * pattern
Print recursive * pattern

Time:04-08

I have trouble printing the * pattern.

They should have 2 functions: printStars() and printLine(). printStars(int n), is used to print a line of n stars; the second one, printLines(int m), is to print m pairs of lines.

I have completed print half top but I could not reverse the pattern of the second half. You can't add more functions. There are only 2 functions printStars() and printLines() and must be recursive

The requirement:

* * * *
* * *
* *
* 
*
* *
* * *
* * * *

Here is what I have done:

* * * *
* * *
* *
* 

Code:

void printStars(int n){
    if (n < 1) return;
    cout << "*";
    printStars(n-1);
}

void printLines(int m){
    if (m < 1) return;
    printStars(m);
    cout << "\n";
    printLines(m-1);
}

int main(int argc, const char * argv[]) {
    int n;
    cout << "n = ";
    cin >> n;
    printLines(n);
}

Hint from the question: Think in the way that the whole picture is generated in the following pattern:

Hint

CodePudding user response:

here is the small change you need:

void printLines(int m){
    if (m < 1) return;
    printStars(m);
    cout << "\n";
    printLines(m-1);

    printStars(m); // just add these two lines to print line again after all internal ones are printed
    cout << "\n";
}
  • Related