For Loop Confusion!

Hello, Im working through some for loops trying to get the concept in my head but unfortunately I just cant seem to understand them enough to print a shape like a triangle, diamond or design. From what I understand is that for loops are used to repeat tasks over and over again. First you create a initial variable, second you set the condition and last you increment the variable. The problem I face is when i see a shape and im asked to write a program to design it based on user input I freeze up and don't quite know how to tackle it. Please help me!

Look at the parts of the shape that are repeated, and that follow a pattern. Let's start with a simple diagonal line of asterisks:
*
 *
  *
   *
    *
     *
      *
       *
The number of lines is the outer loop, and the number of spaces is the inner loop. Can you write the code to show you understand?

Next, try the same shape in reverse:
       *
      *
     *
    *
   *
  *
 *
*
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>

using namespace std;

int main(int argc, const char * argv[])
{
    int rows;
    char character;
    cout << "How many rows would you like: ";
    // asks the user for input
    cin >> rows;
    //
    cout << "What kind of character would you like to print: ";
    // grabs a character to be printed
    cin >> character;
    for (int i = 0; i < rows; i++)
    {
        for (int k = 0; k <= i; k++)
        {
            if (k == i)
            {
                // so position is at 0=0 1=1 2=2 3=3 aka diagonal line
                cout << character;
            }
            else
            {
                // at any other position where i != k a space is printed
                cout << " ";
            }
        }
        // after the first row completes and character is printed once it moves to the next line
        cout << endl;
    }
    return 0;
}

Example code of the first example, can you see how to make a simple change to do it in reverse?
Last edited on
@zacklucky: actually I wouldn't have the asterisk printing code inside the inner for loop, just the outer for loop.
Topic archived. No new replies allowed.