How do I learn properly to print different patterns like diamonds and triangles?

I'm not asking anyone to write the code for me but what I wanna ask is how do I learn this effectively I wanna develop my logic and polish my programming skills I am eager to learn this no matter how hard it is but I need a good place to start

I'm only having difficulty in printing patterns for now.
This involves multiple nested loops.
You will find the problem a lot easier if you use a function like the following:
1
2
3
4
5
6
7
void print_line (int spaces, int stars)
{   for (int i=0; i<spaces; i++)
        std::cout << ' ';
    for (int (i=0;i<stars; i++)
        std::cout << '*';
    std::cout << std::endl;
}

Once you have that function in place, you generally need only an outer loop that calls printline() with the appropriate arguments for each line to be printed.

The above function assumes a solid shape. If you want a hollow shape, you will need to adapt it accordingly.
That's exactly what I was looking for but if anymore additional guidance can be given i will be more than happy to take it
For example if you want to print this:

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

You can analyze the shape for patterns. In this case:
1) There are always 5 characters.
2) The amount of stars is always the same as the row number
3) Amount of spaces = total characters (5) - amount of stars on this row ( row number)

Using that, you can put together the following pseudo code
1
2
3
4
5
6
7
for all lines
    while spaces < max lines - line
        print a space
    while stars < line
        print a star
    print a newline
end
Last edited on
Or by recursion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
using namespace std;

string triangle( int n )
{
    if ( n ==  0 ) return "";
    return triangle( n - 1 ) + string( n, '*' ) + '\n';
}

int main()
{ 
   cout << triangle( 6 );
}
*
**
***
****
*****
******


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
using namespace std;

string diamond( int blanks, int n )
{
    string row = string( n, '*' ) + '\n';
    if ( !blanks ) return row;
    row = string( blanks, ' ' ) + row;
    return row + diamond( blanks - 1, n + 2 ) + row;
}


int main()
{ 
   cout << diamond( 5, 1 );
}
     *
    ***
   *****
  *******
 *********
***********
 *********
  *******
   *****
    ***
     *


With a bit of effort you can also make the recursive versions hollow.
Last edited on
Amazing Thank You
Topic archived. No new replies allowed.