How to make the star pyramid in odd number of stars?

#include<iostream>
using namespace std;

int main() {
    
    int i, j;
    
    for(i = 1; i <= 5; i++) {
        
        for(j =  1; j <= i; j++) { 
            
            cout<< "*";
        }
        
        cout<< endl;
    }
    
    return 0;
}

That is my code above. Odd number as in 1 then 3 stars then 5 stars, etc. All my attempts failed. At first, starts scrolled nonstop. Then only a column of 1 row of stars showed up. It should be so simple, but it's not working out!

Stuff like i%2 == 0 isn't working.

Thank you.

EDIT: Supposed to look like this:

*
***
*****
******

etc


Solution 1:

It can be simple if you break it in small pieces.

The best strategy for beginner is boottom-up, that is first get the smallest piece, that does the simplest thing, that you cannot break into smaller pieces. Then go "up" one level at a time until you reach the "big view" of your algorithm that combines all the pieces:

  • first "piece": print n stars on a single line: the simplest way is to use std::string constructor that constructs a string by repeating a character and print that:
    std::cout << std::strin(n, '*') << '\n'

  • second piece: get the correct number of stars for each line: you start from 1 and increase by 2; simple:
    for (int star_count = 1; star_count <= 7; star_count += 2)

And putting them together:

for (int star_count = 1; star_count <= 7; star_count += 2)
    std::cout << std::string(star_count, '*') << '\n';

One thing I want to emphasize is that I use meaningful name for my variable. There are very few cases where something like i, n are acceptable and that is only in cases where those variables are consecrated for that use, i.e. using i as an index in an array. It is tremendously helpful and you should get asap into the habit of properly naming all of your variables.

For instance if instead of going on number of starts I would have gone with a relation between my line number and the number of stars I would have written like this:

for (int line_index = 1; line_index <= 4; ++line_index)
    std::cout << std::string(line_index * 2 - 1, '*') << '\n';