c++for-loopnested-loops

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.


Solution

  • 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;
            }
        }
    }