-1

I tried to make this problem but not getting solution . I want to print the pattern using c++ - This is pattern -

I tried this code but it is printing in reverse order .

  using namespace std;

  int main() {
    int n;
    cin>>n;
    
    int i = 1;
    
    while(i<=n){
        int j =1;
        while(j<=n){
            cout<<j;
            j=j+1;
        }
        cout<<endl;
        i=i+1;
    }

    return 0;
}

Output - 123 123 123

Can you please tell how to print that ?

  • Please review [ask]. In particular (but not only), compare your question's title to the "good" and "bad" examples there. (Your title is vague to the point of almost uninformative.) – JaMiT Sep 24 '22 at 15:53

2 Answers2

0

your problem is easy, in the inner loop where you are saying

int j = 1;
while(j<=n){
     cout<<j;
     j=j+1;
}

here you are ascending from 1 till n, that's what made your problem, instead, you can write :

   int j = n;
   while (j >= 1) {
        cout << j << " ";
        j = j - 1;
    }

where here in this code, you are descending from n till 1.

and this is the full code edited with this only small modification:

using namespace std;
#include<iostream>

int main() {
    int n;
    cin >> n;

    int i = 1;

    while (i <= n) {
        int j = n;
        while (j >= 1) {
            cout << j << " ";
            j = j - 1;
        }
        cout << endl;
        i = i + 1;
    }

    return 0;
}

and this is the output:

4
4 3 2 1
4 3 2 1
4 3 2 1
4 3 2 1

and also it's not a good practice to write using namespace std;, refer to this question on stack overflow about why using namespace std; is a bad practice

abdo Salm
  • 1,678
  • 4
  • 12
  • 22
0

Well your code is incrementing. So no matter what you'll do it'll always go up by one. I also recommend using for loop for this pattern.

int main()
{
    int n;
    cin>>n;

    for (int i = n; i > 0; i--)
    {
        for(int j = n; j > 0; j--)
            cout << j << " ";
        cout << endl;
    }

    return 0;
}
Monogeon
  • 346
  • 1
  • 9