Is it possible to increment setw?

Viewed 110

I need to display something that looks like:

     /
    -
    /
   /
    -
    /
   /
  /
   -

I currently have the following which does not print the slashes properly.

for (int i = 1; i <= numberOfDolls; i++) {
   for(int j = 1; j <= i; j++) 
      cout << setw(numberOfDolls) << '/' << endl;
      
      cout << "-" << endl;
    }

I was thinking of using setw() to increment the slashes. Is this possible?

2 Answers

You can use std::setw(.) for that purpose. The key is to have a parameter defining the shift. Here is a code implementing it. Simple modifications are possible if you want to slightly modify the image.

#include <iostream>
#include <iomanip>
int main() {

    int numberOfDolls = 3;
    int shift = numberOfDolls + 2;
    for (int i = 1; i <= numberOfDolls; i++) {
        for(int j = 0; j < i; j++) {
            std::cout << std::setw(shift) << '/' << std::endl;
            shift--;
        }
        shift++; 
        std::cout << std::setw(shift) << "-" << std::endl;
    }
    return 0;
}

However, using std::setw(.) seems like an overkill. In my opinion, better to simply add spaces, for example:

#include <iostream>
#include <iomanip>
#include <string>
int main() {

    int numberOfDolls = 3;
    int shift = numberOfDolls + 1;
    for (int i = 1; i <= numberOfDolls; i++) {
        for(int j = 0; j < i; j++) {
            std::cout << std::string(shift, ' ') << '/' << std::endl;
            shift--;
        }
        shift++; 
        std::cout << std::string(shift, ' ') << "-" << std::endl;
    }
    return 0;
}

Output

    /
    -
    /
   /
   -
   /
  /
 /
 -

I am not sure about your doubt but you will get desired output using following:

for (int i = 1; i <= numberOfDolls; i++) {
   for(int j = 1, n=numberOfDolls; j <= i; j++)
      cout << setw(n--) << '/' << endl;

      cout <<setw(numberOfDolls-1)<< "-" << endl;
    }
Related