how to display various pattern using for loop?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • GraxGunz
    New Member
    • Jul 2011
    • 13

    how to display various pattern using for loop?

    Code:
      for (int i = 1; i <= 6; i++)
      {
        for (int j = 1; j <= i; j++)
          cout << setw(3) << j;
        cout << endl;
      }
    above code will display below pattern:
    1
    1 2
    1 2 3
    1 2 3 4 5
    1 2 3 4 5 6

    Code:
      for (int i = 6; i >= 1; i--)
      {
        for (int j = 1; j <= i; j++)
          cout << setw(3) << j;
        cout << endl;
      }
    and this code will display pattern below:
    1 2 3 4 5 6
    1 2 3 4 5
    1 2 3 4
    1 2 3
    1 2
    1

    as what i understand
    Code:
      for (int i = 6; i >= 1; i--)
      {
        cout << endl;
      }
    above code is for creating the coloum
    and
    Code:
        for (int j = 1; j <= i; j++)
          cout << setw(3) << j;
    is for print out the number from 1 to 6

    my question here is what should i change or added he code above so that my output will display the pattern below:
    __________1
    ________2_1
    ______3_2_1
    ____4_3_2_1
    __5_4_3_2_1
    6_5_4_3_2_1

    and

    1_2_3_4_5_6
    __1_2_3_4_5
    ____1_2_3_4
    ______1_2_3
    ________1_2
    __________1

    note: _ is space

    how can i print out my numbers that the alignment shift to the right? should i add space(" ") using if else loop for cout? or i might have a better solution??
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Here is where you use a manipulator.

    Write a function that takes an ostream& and pass in cout. Then use the ostrream& to display an underscore, then return the ostreanm&:

    Code:
    cout << "Hello!" << MyFunction(cout) << endl;
    where MyFunction is:

    Code:
    ostream& MyFunction(ostream& os)
    {
        os << "_";
        return os;
    }

    Comment

    Working...