banner



How To Draw Squares In C?

Hello There,

How do i Write a program that draw a square of stars ( * ), the length of foursquare will be entered by the user. and i accept to use a void function to do it inside the function "void draw_square(int len)", where len is the formal parameter that will be used to specify the length of the square.

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

i literally accept no idea how to showtime coding it, all i know that i need to use for loop i think, then some help here?

Hi RaiN3772,

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

I would first get it to draw the square then work on adding the (/\). That should exist adjusting the inner for loop to print the (/\) as needed based on what row y'all are press.

Andy

                      i
2
iii
4
five
six
7
viii
                                              #include <iostream>                        #include <cord>                        int                        master() {                        int                        numstars{};     std::cin >> numstars;                        for(int                        i = 0; i < numstars; ++i) std::cout << std::string(numstars,                        '*') <<                        '\north'; }                    

Terminal edited on

@TheToaster,

I like that idea, just based on

i literally have no idea how to start coding it, all i know that i demand to utilise for loop i recollect

I tried to keep it simple for now until I see some code to work with.

Andy

@RaiN3372
Based on what Andy said above, I will explicate what my lawmaking does. std::cord is a type provided by the C++ standard that stores strings, hence the name. There is a "constructor" that initializes the cord with a count argument and a char argument. A constructor is like to a office, but you will larn nearly them when y'all learn about classes.

And then, the code std::string(numstars, '*') will create a "string" by calling its constructor. This particular constructor has two parameters that take a count value and a character, and generates a cord appropriately. Thus, the concluding cord volition be a string that has numstars characters of type '*'. We then append a newline at the end (using '\northward') and repeat it in a for loop for numstars lines.

If you wanted to do it without using std::string, you could use a nested for loop as Andy said above:

                        1
two
three
iv
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 information technology breaks out of that loop, it volition print a new line and restart the inner loop. This will happen numstars times. Thus you lot are left with a square of numstars*numstars, with '*' characters.

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

construction to output chars (1 of '\\', '/', '*').

Watch out for even- and odd-length sides.

Last edited on

                      1
2
3
4
5
6
7
viii
9
ten
11
12
thirteen
14
fifteen
xvi
17
eighteen
19
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 - i) - j) { 			    cout <<                        '/'; 			}                        else                        { 				cout <<                        '*'; 			} 		} 		j++; 		cout << endl; 	} }                        int                        main() {                        int                        size; 	std::cin >> size;  	draw_square(size);                        return                        0; }                    

Final edited on

oh cmon guys, i didnt expect that much of replies and caption, really much helpful,

also i coded as andy said, it was a good idea to put for loop within a for loop, i coded it and information technology'due south working as i expected

                        1
2
three
4
5
6
7
8
9
ten
11
12
13
14
15
sixteen
17
xviii
19
twenty
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 = ane; loop <= lenght; loop++) {                          for                          (int                          five = 1; five <= lenght; 5++) {                          if                          (loop == five && 5 == (lenght + i) - loop) { 				cout <<                          "| "; 			}                          else                          if                          (loop == five) { 				cout <<                          "\\ "; 			}                          else                          if                          (five == (lenght + 1) - loop) { 				cout <<                          "/ "; 			}                          else                          { 				cout <<                          "* "; 			} 		} 		cout << endl; 	}  }                          int                          main() {                          int                          lenght; 	cout <<                          "Please enter the Square Lenght: "; 	cin >> lenght; 	draw_square(lenght);                          render                          0; }                      

also i'm looking for a improved way to that code.

cheers guys

PS: Manga i saw your code late, its exaclty the aforementioned code i fabricated, that what i was looking for lmao, cheers anyway

Final edited on

Hello RaiN3772,

Now that you lot have it working, if I may offer some suggestions:

                        1
2
3
4
5
six
7
eight
ix
x
xi
12
thirteen
fourteen
15
16
17
eighteen
nineteen
xx
21
22
23
24
                                                  for                          (int                          row                          = 1; row <= length; row++) {                          for                          (int                          col                          = ane; col <= length; col++) 	{                          if                          (row == col && col == (length + ane) - row) 		{ 			std::cout <<                          "| "; 		}                          else                          if                          (row == col) 		{ 			std::cout <<                          "\\ "; 		}                          else                          if                          (col == (length + ane) - row) 		{ 			std::cout <<                          "/ "; 		}                          else                          { 			std::cout <<                          "* "; 		} 	}  	std::cout << std::endl; }                      

When it comes to giving the loop iterator a name "i" and "j" are most often used, simply if you call and then "row" and "col" y'all will find the residue of your code easier to understand and follow. Making the code piece of cake to read and understand volition first do good yous and so others later. Also some well placed blank lines will make the code easier to read, eastward.g.,

                        1
2
3
four
v
vi
7
8
9
x
11
                                                  int                          master() {                          int                          length;  	cout <<                          "Please enter the Square's Length: "; 	cin >> length;  	draw_square(length);                          render                          0; }                      

With Fourth dimension and exercise you will figure out what works best for y'all.

I am guessing English is not your outset language because information technology is spelled "length" to be correct. To the compiler is makes no divergence equally long equally information technology is spelled the same everywhere you utilise information technology.

Your use of the {}due south is fine. Merely be consequent in their utilise. Do non mix different styles. As you notice the style I use is easier to read and that pert is what is most important.

You can run into dissimilar styles of {}s at https://en.wikipedia.org/wiki/Indentation_style#Brace_placement_in_compound_statements The "Allman" mode is what I adopt, but you are free to use what you have learned and are use to. I am non saying that you demand to change what you have learned.

Just a small thing. When an if/else if/else but has 1 line the {}s are not needed. Some will use them in example later they need to add something. Either way it makes no difference. This likewise applies to for loops and while loops.

Andy

Hello Andy, yes my english isn't my master language, and so sometimes its hard to sympathise the whole thing since its not my get-go language, and i try to understand any lawmaking by trying it out using some cognition from hither and in that location, also when it comes to the terminal lawmaking i try to optimize it every bit much as i can, rename every varble, arrive easier, section it.

and i know if the "if statement" is only one line no need for "{}" simply i adopt to use it anyway i still dont know why, maybe im used to it.

any way thanks very much

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

You're admittedly right to do and so. It'due south good defensive coding exercise.

Topic archived. No new replies immune.

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

Posted by: baileylierearmeng.blogspot.com

0 Response to "How To Draw Squares In C?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel