-1

here is an output of a pattern program. I'm finding it hard to find the logic for the below ouput. please write the code in C++ ...

output:

1
2 9
3 8 10
4 7 11 14
5 6 12 13 15
  • *please write the code* is something you never want to put in a question here. Instead take your best shot at it and ask questions about your attempts should your attempts fail. – user4581301 Apr 17 '19 at 03:43

1 Answers1

0
#include <iostream>

using namespace std;

int main()
{
    int n;
    cin>>n;
    int arr[n+1][n+1];
    int st, ed, inc;
    int num = 1;
    for(int j = 1; j <= n; j++) {
        if(j%2==1) {
            st = j, ed = n+1, inc = 1;
        } else {
            st = n, ed = j-1, inc = -1;
        }
        for(int i = st; i != ed; i += inc) {
            arr[i][j] = num;
            num++;
        }
    }

    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= i; j++) {
            cout<<arr[i][j]<<" ";
        }
        cout<<endl;
    }

    return 0;
}

Input: 5

Output:
1
2 9
3 8 10
4 7 11 14
5 6 12 13 15

Faruk Hossain
  • 1,205
  • 5
  • 12
  • This is a code-only answer. It can probably be salvaged by explaining what you are doing and why, replacing the uninformative identifiers with descriptive names, and replacing the [Variable Length Array](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) with valid code. – user4581301 Apr 17 '19 at 04:46
  • If you notice carefully then you can find clue from the output. In 1st column, number increases from 1st row to bottom, in second column number increases from bottom most row to 2nd row, in 3rd column number increases from 3rd row to bottom most and so on. So you just need to find the start and end row for columns. This logic is just here by checking whether current column is even or odd. if(j%2==1) { st = j, ed = n+1, inc = 1; } else { st = n, ed = j-1, inc = -1; } – Faruk Hossain Apr 17 '19 at 04:56
  • Thanks a lot...... I have found a method to print that output without using the arrays...Here it is – Vaibhav Kandari Apr 21 '19 at 03:36
  • Please post here the answer @VaibhavKandari – Krishna Kumar Singh Apr 18 '20 at 14:14