c++iomanipsetw

Why is my program continuing on the setw value which I have set for the previous cout statements? And this is happening in a pattern too?


This is my code:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
    int n1 = 1, n2 = 2;
    cout << setw(5) << n1 << endl;
    cout << setw(6) << n1 << " " << n2 << endl;
    cout << setw(7) << n1 << "   " << n2 << endl;
    cout << setw(8) << n1 << "     " << n2 << endl;
    cout << setw(9) << n1 << "       " << n2 << endl;
    cout << setw(8) << n1 << "     " << n2 << endl;
    cout << setw(7) << n1 << "   " << n2 << endl;
    cout << setw(6) << n1 << " " << n2 << endl;
    cout << setw(5) << n1 << endl;

    return 0;
}

This is my output:

My output

However, my intended output is:

Intended output

what's wrong in my code?


Solution

  • You just put the numbers in wrong order, try this:

    int main() {
        int n1 = 1, n2 = 2;
        cout << setw(9) << n1 << endl;
        cout << setw(8) << n1 << " " << n2 << endl;
        cout << setw(7) << n1 << "   " << n2 << endl;
        cout << setw(6) << n1 << "     " << n2 << endl;
        cout << setw(5) << n1 << "       " << n2 << endl;
        cout << setw(6) << n1 << "     " << n2 << endl;
        cout << setw(7) << n1 << "   " << n2 << endl;
        cout << setw(8) << n1 << " " << n2 << endl;
        cout << setw(9) << n1 << endl;
    
        return 0;
    }