How to fill the four sides of a square with 1s and the inside with 0s in C++

2 Answers

0 votes
#include <iostream>

int main() {
    int square_size = 7; 

    /*
        We print an n×n square.
        - If the cell is on the border (top, bottom, left, right),
          we print 1.
        - Otherwise, we print 0.
    */

    for (int i = 0; i < square_size; i++) {          // Loop through rows
        for (int j = 0; j < square_size; j++) {      // Loop through columns
            // Check if the cell is on any of the four sides
            if (i == 0 || i == square_size - 1 || j == 0 || j == square_size - 1) {
                std::cout << 1 << " ";
            } else {
                std::cout << 0 << " ";
            }
        }
        std::cout << std::endl;
    }
}


/*
run:

1 1 1 1 1 1 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 1 1 1 1 1 1 

*/

 



answered 6 days ago by avibootz
0 votes
#include <iostream>
#include <vector>

using std::vector;

/*
    FUNCTION: createSquare
    ----------------------
    Creates an n×n square stored in a 2D vector.
    The border (top, bottom, left, right) is filled with 1s.
    The inside is filled with 0s.

    Logic:
    - A cell is on the border if:
        i == 0          → top row
        i == n-1        → bottom row
        j == 0          → left column
        j == n-1        → right column
    - Everything else is inside the square → fill with 0
*/
vector<vector<int>> createSquare(int square_size) {
    vector<vector<int>> square(square_size, vector<int>(square_size, 0));

    for (int i = 0; i < square_size; i++) {
        for (int j = 0; j < square_size; j++) {

            // Check if the cell is on any of the four sides
            if (i == 0 || i == square_size - 1 || j == 0 || j == square_size - 1) {
                square[i][j] = 1;   // Border cell
            } else {
                square[i][j] = 0;   // Inside cell
            }
        }
    }

    return square;
}

/*
    FUNCTION: printSquare
    ----------------------
    Prints the 2D vector (the square) to the screen.
*/
void printSquare(const vector<vector<int>>& square) {
    for (const auto& row : square) {
        for (int value : row) {
            std::cout << value << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    int square_size = 7;

    /*
        We call createSquare(square_size) to build the square.
        Then we call printSquare() to display it.
    */

    vector<vector<int>> square = createSquare(square_size);

    std::cout << "\nGenerated square:\n";
    printSquare(square);
}



/*
run:

Generated square:
1 1 1 1 1 1 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 0 0 0 0 0 1 
1 1 1 1 1 1 1 

*/

 



answered 6 days ago by avibootz

Related questions

1 answer 137 views
1 answer 63 views
1 answer 103 views
1 answer 129 views
129 views asked Apr 18, 2023 by avibootz
...