Home > Enterprise >  C Nested Loops: n*n grid
C Nested Loops: n*n grid

Time:09-23

I need help with this assignment. enter image description here

I already tried something and I can include the code that I wrote so far.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int i, j, n;

    cout << "Please enter the positive integer:";
    cin >> n;

    if (n < 0) {
        cout << "\nEntered integer is not positive! Please enter the positive integer:";
        cin >> n;
    }

    for (i = 1; i <= n; i  ) {
        for (j = 1; j <= n; j  ) {
            if (i == 1 || i == n || j == 1 || j == n) {
                cout << setw(n) << "*";
            }
            else {
                cout << setw(n) << " ";
            }
        }
        cout << endl << "\n";
    }
    
    return 0;
}

Thanks in advance!

CodePudding user response:

Assuming a 1x1 grid looks like this:

****
*  *
*  *
****

e.g., is not also dependent on the number inputted, I would use the following:

for (int i = 0; i < n * 3   1;   i) {
    cout << "*"; //First row with stars
}
cout << endl;
for (int i = 0; i < n;   i) {
    cout << "*"; //First column with stars
    for (int j = 0; j < n;   j) {
        cout << "  *"; //Empty box and closing star
    }
    cout << endl;
    cout << "*"; //First column with stars
    for (int j = 0; j < n;   j) {
        cout << "  *"; //Empty box and closing star
    }
    cout << endl;
    for (int j = 0; j < n * 3   1;   j) {
       cout << "*"; //Bottom row of box with stars
    }
    cout << endl;
}

This code is not tested but just quickly typed, it might not work, so be careful using it. Let me know if there are some problems.

CodePudding user response:

There are several issues in your implementation:

if (n < 0) {
    cout << "\nEntered integer is not positive! Please enter the positive integer:";
    cin >> n;
}

The above condition will validate the user input only once. If the user enter a negative number more than once, it will not be checked.

cout << endl << "\n";

This will cause two end of lines to be printed, which is not needed.

Here is a working program which does the required job:

int main()
{
    int n;

    cout << "Please enter the positive integer: ";
    cin >> n;

    while (n < 0) {
        cout << "\nEntered integer is not positive! Please enter the positive integer: ";
        cin >> n;
    }

    for (int i = 0; i <= (n*n); i  ) {
        for (int j = 0; j <= (n*n); j  ) {
            if (i == 0 || (i % n == 0) || (j == 0) || (j % n == 0)) {
                cout << setw(2) << "*";
            } else {
                cout << setw(2) << " ";
            }
        }
        cout << '\n';
    }
    return 0;
}

Here is the output from the program:

enter image description here

  • Related