Assume the availability of a function named printStars that can be passed a non-negative integer n and print a line of asterisks. Write a function named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows: first a line of 1 asterisk, followed by a line of 2 asterisks, and then a line of 3 asterisks, and so on and finally a line of n asterisks. For example, if the function received 5 it would print: * * * * * * * * * * * * * * * The function must not use a loop of any kind (for, while, do-while) to accomplish its job. The function should invoke printStars to accomplish the task of printing a single line.

LANGUAGE: C++

CHALLENGE:

Assume the availability of a function named printStars that can be passed a non-negative integer n and print a line of asterisks. Write a function named printTriangle that receives a non-negative integer n and prints a triangle of asterisks as follows: first a line of 1 asterisk, followed by a line of 2 asterisks, and then a line of 3 asterisks, and so on and finally a line of n asterisks. For example, if the function received 5 it would print: * * * * * * * * * * * * * * * The function must not use a loop of any kind (for, while, do-while) to accomplish its job. The function should invoke printStars to accomplish the task of printing a single line.

SOLUTION:

The Bad News: The content you are trying to access is only available to members.

The Good News: You too can be a member, simply Click Here.

Already a member?

Posted in ,

7 Comments

  1. Kenneth Tuten on May 9, 2014 at 10:17 pm

    fixed:

    void printTriangle(int n)
    {
    if(n <= 0) return;
    printStars(n);cout<<endl;
    printTriangle(n-1);
    }

    • Kenneth Tuten on May 9, 2014 at 10:19 pm

      fixed:

      void printTriangle(int n)
      {
      if(n <= 0) return;
      printStars(n);cout<<endl;
      printTriangle(n-1);
      }

      EDIT: Sorry, this was for a variation of the problem posted here. Your code is correct

  2. Anon on February 24, 2015 at 9:13 pm

    WRONG! You’re printing the stars in reverse order (e.x. 5 to 1). Pay attention! It wants 1 to 5 instead.

  3. Maurice on October 18, 2015 at 9:11 pm

    void printTriangle(int n){
    if(n==0) return;

    printTriangle(n-1);

    printStars(n);
    }

  4. Zack Withers on July 10, 2016 at 5:50 pm

    Real answer

    void printTriangle(int n){
    if(n==0) return;

    printTriangle(n-1);

    printStars(n);
    cout << endl;
    }

    • Gee on March 15, 2017 at 12:10 am

      this is the only one that worked!

Leave a Comment

You must be logged in to post a comment.