displaying a square

I dont want to boar anyone with this trivial questions but as im learning C++ from the book by Deitel there are questions in the end of each chaper to test youre knowledge. Most of my questions will be how can i improve my code or if there is another way of doing it without redundant steps. So here is one of them. Could this have been done better ?

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
//deitel chaper  2.28 drawing a square

#include "stdafx.h"
#include <iostream>

using namespace std;

int main(){
	
	int sides, rows, columns;

	//we assume that sides entered by user is > 0
	

	cout << "Enter how big square you want to see: ";
	cin >> sides;

	
	for (rows = 1; rows <= sides; rows++){

		for(columns = 1; columns <= sides; columns++){
			
			 if (rows <= 1 || rows >= sides ) 
				 cout << "*";
			else if(columns <= 1 || columns >= sides) {
				 cout << "*";		 
			 }else
				 cout << " ";
			 
		}
		cout << endl;
	}
	
	return 0;
}
It looks pretty solid to me. There are no system calls which is good because you don't need them here, it works and draws the square. The only thing out of place is stdafx.h, because you don't use anything inside of it, but I know that M$'s IDE puts that in by default so meh.

Try expanding on this, if you're interested in a challenge modify the code to draw a triangle :D! Trust me this is harder then is sounds.
Thank you , ill give it a shot., actually its easy to draw one , it probably will take more steps if you want it hallow on the inside. Was that what you meant ?
Last edited on
Done , thanks for suggestion

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
// drawing a triangle

#include "stdafx.h"
#include <iostream>

using namespace std;

int main(){
	
	int sides, rows, columns;


	/*
	draws a hollow triangle

	*/
	

	cout << "Enter how big triangle you want to see: ";
	cin >> sides;

	
	for (rows = 1; rows <= sides; rows++){

		for(columns = 1; columns <= rows; columns++){
			

			 if (rows <= 1 || rows >= sides ) 
				 cout << "*";
			else if(columns <= 1 || columns >= rows) {
				 cout << "*";		 
			 }else
				 cout << " ";
			
		}
		cout << endl;
	}
	

	return 0;
}
]
Last edited on
Topic archived. No new replies allowed.