Learning Nested Loops C++ confused with example

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Learning Nested Loops C++ confused with example



Hello taking an online class on nested loops and this was provided as the example but I don't really know what is going on.



The following code example shows nesting for loops to output a chess or checkerboard representation using the characters X and O. Why do we need x and y variables to execute a certain amount of times. And what does alternate = !alternate; mean? About the x and y wouldn't it just do it 8 times total because its greater than the amount of times y supplies? what is the difference in purpose for the two for statements? Thank you.


for (int x = 0; x < 8; x++)

for (int y = 0; y < 4; y++)

if (alternate)

cout << "X ";
cout << "O ";


else

cout << "O ";
cout << "X ";



alternate = !alternate;

cout << endl;





Fix your indenting, it's very misleading. You seem to have some issues understanding what nested loops do, try asking your teacher.
– Fei Xiang
Aug 12 at 18:55





1 Answer
1



The variable x used for the number of lines you want to print X-O pairs. Variable y used to specify the number of X-O pairs in 1 line. So for printing 8 lines of X-O pairs and in each line, 4 pairs of X-O, you should do just like that.



The operator '!' used for getting the opposite of a value (it's logical NOT) (for example, 1 to 0 or false to true). so alternate = !alternate; means that after every line of X-O pairs, it changes from true to false or vise versa.



So lines' first character (X or O) will change according to 'alternate' variable.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard