Nested loops in C++




вложенные циклы C++

We all got acquainted with three repetition structures in C ++ programming. It loops for, 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, you need to draw a rectangle 5 х 15 of the characters @.

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:

вложенные циклы в C

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:

The result depends on the input, which asks the user. I turned the black square of the issues :)

вложенные циклы в C++

One more example: print a multiplication table.

As a result, we see a multiplication table:

вложенные циклы в C++

вложенные циклы в C++

.

.

.

.

.

.

.

.

.

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. We are grateful, if you share the article with your friends, clicking on your social network, under Article.

Newsletter of programming:

Date
page
Nested loops in C++
Rating
51star1star1star1star1star

25 thoughts on “Nested loops in C++

    1. It's hard to say what you mean by basic rules?
      Fundamental rules:
      – Cycles should be invested according to the principle “matrjoşki”: each inner loop must be completely ** ** placed inside covering;
      – Never change the setting (variable) the outer loop in an internal;
      – You never get out of the nested loops operator goto;

    1. Basically, nothing more than.
      Although C # … it sucks, and to the discussions on this site has nothing to do.

  1. Tell, данное решение примера из вашего урока с квадратом из символов, эквивалентно вашему решению приведённому в уроке? Или же ваш вариант всё таки имеет преимущество? Если да то в чём? Thank you.

    1. Decision any задачи можно записать многими, часто многими десятками, разными способами.

      Критерием правильности программы является только результат её выполнениязапустите и убедитесь.

      1. А как сделать: пользователь вводит радиус и рисуется круг с таким радиусом
        P.s. Извиняюсь если есть ошибки( я школьник:) )

  2. to Soldier:
    рисуется круг” – это задача из области графики, она не имеет ни малейшего отношения к языку программирования C++, and 100% определяется тем, какими графическими библиотеками (фреймворком: MFC, Qt, GTK, wxWidgets и др.) вы пользуетесь + в какой операционной системе.

      1. “a circle” нельзярисовать” in C++.
        “a circle” шt is possible “рисоватьтолько функциями из разных графических библиотеккоторые могут вызываться, including, и из кода на C++.
        Но непосредственно к C++ это не имеет никакого отношения.

        P.S. Передайте это своему другу.

Leave a Reply

Place code in tags: <pre class="lang:c++ decode:true ">YOUR CODE</pre>