We all got acquainted with three repetition structures in C ++ programming. It loopsfor, while и do while. If you've been paying attention, attachment structures logical choice if and else in the loops have been applied. Now we consider the nested loops – when the body is one loop (external) hosts another loop (internal). Such nested loops in the external loop may be somewhat.
On its structure, nested loops remind me boxes of different sizes, as in our drawing. These boxes can be easily folded into one another and placed in a large box. So with loops. Program, to get to the nested loop, you must first begin any of the outer loop (open the lid of a large box), run, what is written in the code to the inner loop, and then proceed with the implementation of this loop.
There is one interesting common example, to showcase the work of nested loops. Consider it: using loops, must draw a rectangle of size 5 x 15 of the characters @.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> using namespace std; int main() { for (int i = 0; i < 5; i++) // этот цикл отвечает за кол-во строк { for (int j = 0; j < 15; j++) // этот - за кол-во символов в каждой строке { cout << '@'; } cout << endl; // переход на строку ниже } return 0; } |
At first it starts loop for in string 6. Since his body nothing is written to the second loop, the program immediately starts executing this nested loop – strings 8 – 11. As a result of its implementation, on the screen are displayed on one line 15 characters @ and it exits. Here work cout in string 12, the control variable i increased by one and continue the implementation of the main and nested loops. That is, again 15 characters on the screen and move to the line below. So it will be done 5 times, after which the program exits. On the screen we see the, that was in the condition:
You can slightly complicate the task. Now, let the symbol for printing the user selects pieces, by keyboard input. He chooses the size of the – width and height. Another innovation – the figure should be empty, not filled, as in our previous example. That is, it must consist solely of the contour. Here is our solution:
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 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); int lines = 0; int symbInLines = 0; char symbol = 0; cout << "Введите символ: "; cin >> symbol; cout << "Количество строк: "; cin >> lines; cout << "Количество символов в строке: "; cin >> symbInLines; cout << endl; for (int i = 1; i <= lines; i++) { if (i == 1 || i == lines) // 1-я и последняя строка { for (int j = 1; j <= symbInLines; j++) { cout << symbol; // сплошная из символов } } else // все строки между первой и заключительной { cout << symbol; // показать один символ for (int j = 1; j <= symbInLines - 2; j++) { cout << ' '; // пробелы в строке (symbInLines - 2) раз } cout << symbol; // показать ещё один символ } cout << endl; // новая строка } cout << endl; return 0; } |
The result depends on the input, which asks the user. I turned the black square of the issues :)
One more example: print a multiplication table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> using namespace std; int main() { for (int f = 2; f <= 9; f++) { for (int s = 1; s <= 9; s++) { cout << f << " * " << s << " = " << f * s; cout << endl; } cout << endl; } cout << endl; return 0; } |
As a result, we see a multiplication table:
.
.
.
.
.
.
.
.
.
Figures showing only the beginning and the end of the table.
I hope the lesson has been useful for you. Nested constructs in C++ programming are fairly common. Necessarily consider the tasks, we have prepared. If you have any questions on the topic – we are waiting for them in the comments.
At this time, examples of appealing.
cout <> symbol;
Why cin before indenting More? so it is necessary?
I am pleased to see that some kind of praise from you )
About cin indented code, I would highlight the proposal to introduce a bit of data and data entry itself, that was written all in a solid block 6 strings. About tom, it is necessary to exactly, Of course no one says )
Hello!
Read the book “C ++ for Dummies” And somehow vaguely in her painted theme of nested loops. I searched the internet and came across your website. Examples are very clear and are available for beginners. Even compared with five other sites, You are the best!
huge Pasiba! It seems difficult subject, and thanks to all of your article as ABC. Respect!
I could not help but thank you for such work…
Thank you! It is a pleasure to read such comments to my lessons! It inspires nothing less, than criticism :)
Zdravstvuyte.Ya tried to solve the problem (second)
#include
using namespace std;
int fields,symbol;
int main()
{
cout<<"Kol-vo strok/i="strok;
cout<<"Kol-vo simbol/j"simbol;
for(int i=1;i<= stroke;i )
{
for(int j=1;j<= symbol;j )
{
if ((i!==1 && (strok-i!==1))&&( j==1 || j==2 )&&(j == simbol|| j==(symbol-1)))
{
cout<<"*";
}
if (i==1||stroke-1!==1)
{
cout<<"*";
}
}
cout <KOD.cpp
1>c:\usersтимурdesktopdocumentsvisual studio 2008projectsvl_chirluvl_chirlukod.cpp(14) : error C2059: syntax error: =
1>c:\usersтимурdesktopdocumentsvisual studio 2008projectsvl_chirluvl_chirlukod.cpp(15) : error C2143: syntax error: lack of “;” before “{”
1>c:\usersтимурdesktopdocumentsvisual studio 2008projectsvl_chirluvl_chirlukod.cpp(19) : error C2059: syntax error: =
1>c:\usersтимурdesktopdocumentsvisual studio 2008projectsvl_chirluvl_chirlukod.cpp(20) : error C2143: syntax error: lack of “;” before “{”
Prompt in what an error?????
Plug the library correctly
#include
and now this has no !== necessary !=
wonderful lesson!! Thank you.
But, Please help me with a problem 2, which draws a rectangle.
Do not understand the line
for (int j = 1; j <= symbInLines – 2; j )
explain, you are welcome, in detail.
symbInLines a variable, which indicates what the width of the square.
For example symbInLines = 50. Description j = 1; j <= symbInLines – 2 He says that the cycle should run 48 time withdrawing 48 gaps between two characters border square.
Thank you, I entered!
Can anyone be interested in While
#include
using namespace std;
int main()
{
int a=1,b=0,c=1,d=0;
cout<<b;
cout<<d;
while(a<=b)
{
c=1;
while(c<=d)
{
if (a==1||a==b)
{
cout<<"0";
}
else if (c==1||c==d)
{
cout<<"0";
}
else
{
cout<<"1";
}
c++;
}
a++;
cout<<endl;
}
return 0;
}
class lesson!!!
good afternoon!
Lessons zamechatelnye.vso very clear raspisano.Spasibo you very much.
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if ((i == 0 || i == height - 1) || (j == 0 && i != 0 && i != height - 1) || (j == width - 1 && i != 0 && i != height - 1 ))
{
cout << symbol;
}
else
{
cout << ' ';
}
}
cout << endl;
}
good lessons)