RobotSpirits
RobotSpirits

Reputation: 35

How to create an upward triangle with repeat function

I am trying to create an upward triangle function that utilizes a function that I have already completed that takes a character and prints it however many times you want to.

I want to be clear up front, this is for a homework assignment. I am running into some walls, and just need a little guidance.

Upward triangle Example:

*
**
***
****

I know how to create an upward triangle function without another function:

void utri( int tricount )
{
    int uptri, x;
    char star;
    star = '*';
    for ( uptri = 1; uptri <= tricount; uptri++ )
    {
        for ( x = 0; x < uptri; x++ )
        {
                printf ("%c", star);
        }
        printf("\n");
    }
}

but I am having trouble coming up with a logical way to do so. I am trying to create an upward triangle that will utilize my repeat function below.

This is the repeat function I want to utilize to create my upward triangle function:

void rept( int alot, char sym )
{
    int z;

    for ( z = 0; z < alot; z++ )
        printf("%c", sym);

    printf("\n");
}

When testing the output, this is the call I want to use:

utri(4);

Upvotes: 0

Views: 301

Answers (2)

ejderuby
ejderuby

Reputation: 735

All you have to do is replace the inner for loop with the new function you must use, and pass the correct variables to the function by putting them in the function call accordingly, such as: rept(uptri, star);.

uptri is passed to rept() and is the variable named int alot (the number of times the loop will run) in that scope, and star is the character char that will print in rept() and is the variable named char sym in rept's scope. If you're new to computer programming, "scope" just refers to what part of the program that variable can be seen. So, rept can't see the variables uptri and star until they are passed to it by their value using the function call rept(uptri, star);. Once that happens, rept uses those variables and assigns their values to the variables in its own scope: alot and sym.

Code

void utri( int tricount )
{
    int uptri, x;
    char star;
    star = '*';
    for ( uptri = 1; uptri <= tricount; uptri++ )
    {
        rept(uptri, star);
    }
}

Upvotes: 1

priojeet priyom
priojeet priyom

Reputation: 908

Congratulations. Your solution works perfectly in seperation. You just have to merge them together to make things work. So your rept function prints character sym alot times and you need to print star 1 time for line 1, 2 times for line 2 and so on.. What if we call rept passing line number as alot and star as sym?

**See the Code below after thinking a bit about the question.

void utri( int tricount )
{
        int uptri, x;
        char star;
        star = '*';
        for ( uptri = 1; uptri <= tricount; uptri++ )
        {
                rept(uptri, star);
        }
}

Upvotes: 0

Related Questions