I'm trying to write a function that will draw a right triangle that will ascend and then descend after the max height is reached. It is to be drawn using the asterisk symbol. I'm fairly new to recursion and that is the primary method I need to use to solve this problem. Any guidance or critique to my code would be appreciative. I can only edit the code that is marked TODO.

Desktop_3-25-2019_12-16-42_PM-239.png

    // File: main.cpp

    #include <iostream>
    #include <fstream>
    #include <iomanip>
    using namespace std;

    int recursiveCount = 0;

    void triangle(const char drawChar, const int maxHeight, const int currentHeight);

    int main() {
        char drawChar = '*';

        /* Change the fill character to be the 'drawChar' used for the triangle. */
    recursiveCount = 0;

    cout.fill(drawChar);
    triangle(drawChar, 5, 1);
    cout.fill(' ');

    return 0;
}// end main()

void triangle(const char drawChar, const int maxHeight, const int currentHeight) {
    /* DO NOT edit code */
    cout.fill(drawChar);
    recursiveCount += 1;
    /* END of do not edit */

    /* TODO (1):
     * Draw a right expanding triangle, using 'drawChar' as the character.
     * The maxHeight represents the final height of the triangle,
     * whereas the currentHeight represents the height of each side.
     */
    if (maxHeight <= 0){
        return;
    }
    triangle(drawChar, maxHeight - 1, currentHeight + 1);
    for(int i=0; i < currentHeight; i++){
        cout << drawChar << endl;
    }
    }

Recommended Answers

All 2 Replies

I've recategorized this as a discussion thread.

c++ Code

int main()
'{'
int lengthC = 0;

for (int i = 1; i < 10; i++) {
    if (i > 5) {
        lengthC += 2;
    }
    for (int j = 0; j < (i - lengthC); j++)
    {
        cout << "*";
    }
    cout << endl;
}

'}'

c# Code

static void Main(string[] args)
'{'

int lengthC = 0;

for (int i=1; i < 10; i++ ) {
if (i > 5) {
lengthC+=2;
'}'
for (int j = 0; j < ( i - lengthC ); j++ )
'{'
Console.Write("*");
'}'
Console.Write("\r\n");
'}'

'}'

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.