banner



How To Draw A Square In C++

Hello There,

How practice i Write a program that describe a square of stars ( * ), the length of square will be entered past the user. and i take to use a void role to practise information technology inside the role "void draw_square(int len)", where len is the formal parameter that will exist used to specify the length of the foursquare.

Please bank check the image of that illustrates an example of the intended output
https://imgur.com/AG3kMq8

i literally take no thought how to start coding it, all i know that i need to use for loop i think, then some aid here?

Howdy RaiN3772,

No you need 2 for loops or more than to the point a nested for loops. The first volition control the rows and the inner for loop will control the columns.

I would first get it to draw the square then work on calculation the (/\). That should be adjusting the inner for loop to print the (/\) as needed based on what row you are printing.

Andy

                      1
2
3
4
5
6
7
8
                                              #include <iostream>                        #include <string>                        int                        chief() {                        int                        numstars{};     std::cin >> numstars;                        for(int                        i = 0; i < numstars; ++i) std::cout << std::string(numstars,                        '*') <<                        '\n'; }                    

Terminal edited on

@TheToaster,

I like that thought, but based on

i literally have no idea how to start coding information technology, all i know that i demand to use for loop i think

I tried to keep information technology elementary for at present until I see some code to piece of work with.

Andy

@RaiN3372
Based on what Andy said above, I will explain what my code does. std::string is a type provided by the C++ standard that stores strings, hence the name. There is a "constructor" that initializes the string with a count argument and a char argument. A constructor is similar to a office, but you volition acquire about them when you lot larn about classes.

So, the lawmaking std::string(numstars, '*') will create a "string" by calling its constructor. This particular constructor has ii parameters that accept a count value and a character, and generates a string appropriately. Thus, the last string will be a cord that has numstars characters of type '*'. Nosotros then append a newline at the end (using '\n') and repeat it in a for loop for numstars lines.

If you wanted to do it without using std::cord, you lot could apply a nested for loop every bit Andy said above:

                        1
2
3
four
5
                                                  for(int                          i = 0; i < numstars; ++i) {                          for(int                          j = 0; i < numstars; ++j) std::cout.put('*');     std::cout.put('/n'); }                      

The inner for loop will output numstars (*) characters. Once it breaks out of that loop, it will print a new line and restart the inner loop. This will happen numstars times. Thus you are left with a square of numstars*numstars, with '*' characters.

I think (as @Handy Andy) I'd use a nested for loop (outer loop for rows, inner loop for elements inside a row), with

structure to output chars (one of '\\', '/', '*').

Watch out for even- and odd-length sides.

Last edited on

                      1
ii
3
4
v
vi
7
8
ix
10
11
12
13
xiv
15
xvi
17
18
xix
20
21
22
23
24
25
26
27
28
29
30
31
32
                                              #include <iostream>                        using                        namespace                        std;                        void                        draw_square(int                        len) {                        for                        (int                        a = 0, j = 0; a < len; a++) {                        for                        (int                        i = 0; i < len; i++) {                        if                        (i == j) { 				cout <<                        '\\'; 			}                        else                        if(i == (len - ane) - j) { 			    cout <<                        '/'; 			}                        else                        { 				cout <<                        '*'; 			} 		} 		j++; 		cout << endl; 	} }                        int                        main() {                        int                        size; 	std::cin >> size;  	draw_square(size);                        render                        0; }                    

Last edited on

oh cmon guys, i didnt wait that much of replies and explanation, actually much helpful,

also i coded as andy said, it was a good idea to put for loop inside a for loop, i coded it and it's working as i expected

                        1
2
3
4
v
six
7
8
9
ten
11
12
13
xiv
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
xxx
31
32
33
34
35
36
37
                                                  #include <iostream>                          using                          namespace                          std;                          void                          draw_square(int                          lenght) {                          for                          (int                          loop = one; loop <= lenght; loop++) {                          for                          (int                          v = 1; v <= lenght; v++) {                          if                          (loop == v && 5 == (lenght + 1) - loop) { 				cout <<                          "| "; 			}                          else                          if                          (loop == five) { 				cout <<                          "\\ "; 			}                          else                          if                          (v == (lenght + 1) - loop) { 				cout <<                          "/ "; 			}                          else                          { 				cout <<                          "* "; 			} 		} 		cout << endl; 	}  }                          int                          main() {                          int                          lenght; 	cout <<                          "Please enter the Square Lenght: "; 	cin >> lenght; 	draw_square(lenght);                          return                          0; }                      

besides i'm looking for a improved way to that lawmaking.

thank you guys

PS: Manga i saw your lawmaking late, its exaclty the aforementioned code i made, that what i was looking for lmao, give thanks you anyhow

Last edited on

Hullo RaiN3772,

At present that you have it working, if I may offer some suggestions:

                        1
two
three
iv
5
6
7
8
9
10
eleven
12
thirteen
14
15
16
17
18
19
20
21
22
23
24
                                                  for                          (int                          row                          = one; row <= length; row++) {                          for                          (int                          col                          = 1; col <= length; col++) 	{                          if                          (row == col && col == (length + 1) - row) 		{ 			std::cout <<                          "| "; 		}                          else                          if                          (row == col) 		{ 			std::cout <<                          "\\ "; 		}                          else                          if                          (col == (length + one) - row) 		{ 			std::cout <<                          "/ "; 		}                          else                          { 			std::cout <<                          "* "; 		} 	}  	std::cout << std::endl; }                      

When information technology comes to giving the loop iterator a name "i" and "j" are most frequently used, just if you telephone call then "row" and "col" you volition discover the rest of your code easier to sympathise and follow. Making the code easy to read and sympathise will first do good y'all then others later. Also some well placed blank lines volition make the lawmaking easier to read, e.1000.,

                        1
ii
3
4
5
6
seven
8
9
10
eleven
                                                  int                          main() {                          int                          length;  	cout <<                          "Please enter the Foursquare's Length: "; 	cin >> length;  	draw_square(length);                          render                          0; }                      

With Time and practice yous will effigy out what works all-time for you.

I am guessing English is non your first language because it is spelled "length" to be correct. To the compiler is makes no difference as long as information technology is spelled the same everywhere you use it.

Your use of the {}s is fine. Just be consistent in their employ. Do not mix different styles. Equally yous notice the style I utilise is easier to read and that pert is what is most of import.

You tin see different styles of {}s at https://en.wikipedia.org/wiki/Indentation_style#Brace_placement_in_compound_statements The "Allman" fashion is what I prefer, just yous are free to use what you take learned and are use to. I am not saying that you need to change what yous have learned.

Just a minor matter. When an if/else if/else only has one line the {}s are not needed. Some will use them in case later they need to add something. Either manner information technology makes no difference. This also applies to for loops and while loops.

Andy

Hello Andy, aye my english isn't my main language, and so sometimes its hard to empathize the whole thing since its not my showtime language, and i try to understand whatever code by trying it out using some knowledge from hither and there, also when information technology comes to the last code i try to optimize it as much every bit i can, rename every varble, brand it easier, section it.

and i know if the "if argument" is only i line no demand for "{}" but i prefer to use it anyway i still dont know why, maybe im used to information technology.

any manner thanks very much

and i know if the "if statement" is but 1 line no need for "{}" just i adopt to use it anyway i nevertheless dont know why, mayhap im used to it.

You're absolutely right to do so. It'south good defensive coding exercise.

Topic archived. No new replies allowed.

Source: https://www.cplusplus.com/forum/beginner/270566/

Posted by: blancharddeve1941.blogspot.com

0 Response to "How To Draw A Square In C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel