0

I have a little difficulty in programming in C ++ to make patterned output using 2D arrays, I make the output like a matrix like this: input 4 (for column 4 & row 4)

I I I I
0 0 I 0
0 I 0 0
I I I I

I've tried this my programmed. For the top and bottom rows I've managed to change the value to 1

   #include <iostream>
using namespace std;

int main(){
    int elemen[100][100], n, i, j, k;
    
    cout <<"input element = ";
    cin >>n;
    
    for(i = 0;i < n;i++){
        for(j = 0;j < n;j++){
            elemen[0][j] = 1;
            elemen[n-1][j] = 1;
            elemen[n-i][n-j] = 1;           
            cout <<elemen[i][j]<<" ";
        }   
        cout<<endl;
    }
    
}

but the output that occurs in the above program is like this:

I I I I
0 0 0 0
0 0 I I
I I I I

whereas logically it is correct, and I've tried it on non-input arrays.whereas logically it is correct, and I've tried it on non-input arrays. because if we input the array element = 5, then the loop will automatically reduce the value of 5 one by one. Is there anyone who can help, sorry if you do not understand, because I am currently still learning to hone my logic

0

2 Answers 2

1

Unless you are actually using elemen for anything else than printing this pattern, I suggest dropping it and print the pattern directly.

Example:

#include <cstddef>  // size_t
#include <iostream>
#include <string>

int main() {
    std::size_t n = 4;
    
    std::cout << std::string(n, 'I') << '\n';

    for(std::size_t i=1; i < n - 1; ++i) {
        std::cout
            << std::string(n - i - 1, '0') 
            << 'I'
            << std::string(i, '0')
            << '\n'
        ; 
    }

    std::cout << std::string(n, 'I') << '\n';
}

Output:

IIII
00I0
0I00
IIII
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

 for(i = 0;i < n;i++){
      for(j = 0;j < n;j++){
            if (i == 0 || i == n-1 || i == n-j-1)
                elemen[i][j] = 1;
            else
                elemen[i][j] = 0;
            ...
       }
       ...
  }
  • i = 0 gives you the top row
  • i = n-1 gives you the bottom row
  • i = n-j-1 gives you reverse diagonal

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.