Is there a better and shorter way of my for loop?

Viewed 117

I'm a newbie here and this my first question. I learn basic c++ on Visual Studio 2019. I study functions and loops.

I have a homework that wants print:

I solved it with my code of 30 lines. But I just wonder is a there a shorter and better way of this?

using namespace std;
int main() 
{   
        for (int j = 0; j < 5; j++)
        {
            if (j == 1)
                break;
            cout << "*";
            cout << endl;
            if (j == 2)
                break;
            cout << "**";
            cout << endl;
            if (j == 3)
                break;
            cout << "***";
            cout << endl;
            if (j == 4)
                break;
            cout << "****";
            cout << endl;
            if (j == 5)
                break;
            cout << "*****";
            cout << endl;
        }
    return 0;
}

4 Answers

You have made several mistakes in your code.

  • break statements should actually be continue statements. break terminates the entire loop altogether (ie. absolutely nothing will be printed in the code you provide).
  • i == 5 can never be true, as the loop terminates before thet happens (see the condition i < 5).

To answer your question, you can use a nested loop.

for (int i = 0; i < 5; i++) {
    for (int j = 0; j <= i; j++) {
        std::cout << '*';
    }
    std::cout << std::endl;
}

Or, if you don't need to be flexible, do it manually.

std::cout << "*\n**\n***\n****\n*****" << std::endl;
        

Why a loop? Here’s the same logic in seven lines of code:

int main() {
    std::cout << "*\n";
    std::cout << "**\n";
    std::cout << "***\n";
    std::cout << "****\n";
    std::cout << "*****\n";
}

To be honest, this is probably as short as it gets (apart from cramming all the output into a single statement).

But the issue with your loop isn’t primarily its length, it’s that your loop isn’t variable: it fails to work as soon as you change the number of iterations, and that defeats the purpose. All the logic is hard-coded, which makes the loop useless.

But if you want to use loops, then make the logic of printing stars configurable:

void print_stars(int n) {
    for (int i = 0; i < n; ++i) {
        std::cout << "*";
    }
    std::cout << "\n";
}

int main() {
    for (int i = 0; i < 5; ++i) {
        print_stars(i + 1);
    }
}
#include<iostream>
using namespace std;


int main(){
    for(int i = 1;i <= 5;i++){
        for(int j = 1;j <= i;j++){
            cout<<"*";
        }
        cout<<"\n";
    }
}
void printTrignleL(size_t n)
{
    for (size_t i = 0; i < n; ++i) {
        std::cout << std::string(i + 1, '*') << '\n';
    }
}
Related