gloriousCatnip
gloriousCatnip

Reputation: 431

Making a program in c++ that will produce a triangle with stars, but the result is always 2 numbers off

I am currently making a program that outputs a little triangle made off of stars (or asterisks) in c++, and I am facing some problems.

It seems as though whenever I write something to the function, the compiler interprets it as that number, minus two - something I find very strange.

int makePyramid(int len=1) {
    // A pyramid (or triangle) can not consist of less than 1 length.
    if(len < 1) {
        cout << "does not make sense" << endl;
    }
    else {
        // Go through the length
        for(int i = 1; i < len; ++i) {
            // Make one star for each number in the last loop
            for(int j = 1; j < i; ++j) {
                cout << "*";
            }
            // Makes a new line after the second loop is through
            cout << endl;
        }
    }
}

Here is the function in question. As you can see, it should work - the first loop goes through the whole number and then goes to the next loop which prints one asterisks depending on the value of the number, and then it outputs a new line so it can get started on the next set of asterisks.

Keep in mind that I am pretty new to C++, and I am using minGW in cmd (Windows 10) to compile the code.

Upvotes: 0

Views: 1472

Answers (2)

Eldar Dordzhiev
Eldar Dordzhiev

Reputation: 5135

1) The loop for (int i = 1; i < len; i++) iterates len - 1 times. i have values in the range of [1; len - 1].

2) The loop for (int j = 1; j < i; ++j) iterates j - 1 times. j have values in the range of [1; i - 1].

That's why these function prints less asteriks. C style loops are tricky and are more powerful in comparison to, for example, Pascal loops. In order to fix that you need by initializing i and j with 0 or by replacing < with <=:

int makePyramid(int len=1) {
    // A pyramid (or triangle) can not consist of less than 1 length.
    if(len < 1) {
        cout << "does not make sense" << endl;
    }
    else {
        // Go through the length
        for(int i = 0; i < len; ++i) {
            // Make one star for each number in the last loop
            for(int j = 0; j <= i; ++j) {
                cout << "*";
            }
            // Makes a new line after the second loop is through
            cout << endl;
        }
    }
}

Upvotes: 2

Slava
Slava

Reputation: 44258

First loop you should either start from 0 or change condition to <=

for( int i = 0; i < len; ++i )

or this

for( int i = 1; i <= len; ++i )

Though first one is more usual for C++ as commonly used to iterate over array indexes (from 0 to N-1). In your case it is irrelevant.

In the second loop you have to change condition to <= and start from the same number as i, so either:

 for( int i = 0; i < len; ++i )
     for( int j = 0; j <= i; ++j )

or

 for( int i = 1; i <= len; ++i )
     for( int j = 1; j <= i; ++j )

Upvotes: 1

Related Questions