fbpx

C++: Nested Loops

Bjarne-stroustrup
 


Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [1,\ldots,20]. The loops iterate rows and columns of the array printing the elements until the value 20 is met. Specifically, this task also shows how to break out of nested loops.

#include<cstdlib>
#include<ctime>
#include<iostream>
 
using namespace std;
int main()
{
    int arr[10][10];
    srand(time(NULL));
    for(auto& row: arr)
        for(auto& col: row)
            col = rand() % 20 + 1;
 
    ([&](){
       for(auto& row : arr)
           for(auto& col: row)
           {
               cout << col << endl;
               if(col == 20)return;
           }
    })();
    return 0;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.