an exercise by a begginer (true begginer)

Good evening from colombia to all.

I am learning programming in c ++, and doing some exercises.

Might you check this one?.

Regards and thanks.


/*Square of Asterisks) Write a program that reads in the size
of the side of a square, then prints a hollow square of that size out
of asterisks and blanks. Your program should work for squares of
all side sizes between 1 and 20.*/

//is this program solution well solved?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
	

	int sizeSide;
	int column;
	int row = 2;
	int topRow = 0;
	int bottonRow = 0;
	
	
	cout << "Enter the size of the sides of a square ";
	cin >> sizeSide;
	
	//Top side.
	while (topRow < sizeSide)
	{	
		cout << "* ";
		topRow++;	
	}
	
	//Lateral sides
	while(row < sizeSide)
	{
		column = 0;
		
		cout << endl;
		
		while(column < sizeSide)
		{
			//Left side (left column)
			while(column == 0)
			{
				
				cout << "*";
				++column;
			}
			
			//Right side (Right column)
			while(column == sizeSide - 1)
			{
				
				cout << " *";
				++column;		
			}
				
			cout << "  ";
			++column;
		}
		
		++row;
	}
		
	//Bottom side
	cout << endl;
	
	if ( topRow == sizeSide)
	{
		while (bottonRow < sizeSide)
       {
	   		
			cout << "* ";
			bottonRow ++;	
	   }		
	}
	return 0;
}
Last edited on
Try with input: 1

Does this really have to be a loop?
1
2
3
4
5
while (column == 0)
{
  cout << "*";
  ++column;
}

Would if be enough?
You have a lot of meaningless "loops", i.e., while loops that only execute their body once.
It should be more like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

int main()
{
    using std::cout;

    int size;
    cout << "Enter the size of the sides of a square ";
    std::cin >> size;
    
    for (int col = 0; col < size; col++)
    {
        cout << "* ";
    }        
    cout << '\n';
    
    for (int row = 1; row < size - 1; row++)
    {
        cout << "*";

        for (int col = 1; col < size - 1; col++)
        {
            cout << "  ";
        }

        cout << " *\n";
    }
        
    for (int col = 0; col < size; col++)
    {
        cout << "* ";
    }        
    cout << '\n';
}

thank you two , the tips i will keep it in mind. Muchas gracias,
Topic archived. No new replies allowed.