Home c++ Output to the console a square in a square with ***

Output to the console a square in a square with ***

Author

Date

Category

Hello!
With an ordinary square, everything is simple, but how to put a smaller square in it, this is a problem … Help please)

# include & lt; iostream & gt;
using namespace std;
void main ()
// Display a square within a square
{
  setlocale (LC_ALL, "Russian");
  int side;
  cout & lt; & lt; "Enter 1 side of the square =";
  cin & gt; & gt; side;
  for (int i = 1; i & lt; = side; i ++)
  {
    for (int j = 1; j & lt; = side * 2; j ++)
    {
      if (i == 1 || j == side * 2 || j == 1 || i == side)
        cout & lt; & lt; '*';
      else
        cout & lt; & lt; '';
    }
    for (int j = 1; j & lt; = side; j ++)
    {
      if (i == side / 3)
        cout & lt; & lt; '*';
      else
        cout & lt; & lt; '';
    }
    cout & lt; & lt; endl;
  }
}

I have already started thinking about using the third for with my if, but the condition for this if does not go into my head … i.e. 21 lines are not correct (


Answer 1, authority 100%

Here is my implementation of your task.

# include & lt; iostream & gt;
#include & lt; stdio.h & gt;
using namespace std;
int main ()
{
  int a, b;
  int k = 0;
  cout & lt; & lt; "INPUT SIZE 1:";
  cin & gt; & gt; a;
  cout & lt; & lt; "INPUT SIZE 2:";
  cin & gt; & gt; b;
  if (a & gt; = 20 || b & gt; = 20) {
    cout & lt; & lt; "Size & gt; = 20! Is err";
    return 0;
  }
  if (a == b) {
    cout & lt; & lt; "Size 1 == size 2! Is err";
    return 0;
  }
  if (a & gt; b) {
    k = (a - b) / 2;
  }
  if (a & lt; b) {
    k = (b - a) / 2;
  }
  char arr [20] [20] = {0};
  for (int i = 0; i & lt; a; i ++) {
    arr [i] [0] = '*';
    arr [0] [i] = '*';
    arr [a-1] [i] = '*';
    arr [i] [a-1] = '*';
  }
  b + = k;
  for (int i = k; i & lt; b; i ++) {
    arr [i] [k] = '*';
    arr [k] [i] = '*';
    arr [b-1] [i] = '*';
    arr [i] [b-1] = '*';
  }
  for (int i = 0; i & lt; 20; i ++) {
    for (int j = 0; j & lt; 20; j ++) {
      cout & lt; & lt; arr [i] [j];
    }
    cout & lt; & lt; endl;
  }
  getchar ();
  return 0;
}

 Result screen

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions