Search code examples
nested-loops

Nested loops for beginners


I can't seem to understand the logic of nested loops.
Any tips or easy examples about how to make nested loops less complicated?
New to programming. Thanks.


Solution

  • Nested loops are essential for a good programmer. They are usually used to manage matrices in order to avoid code repetition. Let's have an example:

    for(int i = 0; i < 5; i++){
       for(int j = 0; j < 5; j++){
          Log.i("i:", i);
          Log.i("j:", j);
       }
    }
    

    After using this code (Java) several numbers are written in the log of the IDE. As you can see, the inner loop is run first (in our example 5 strings are written, because the loop needs to be run 5 times in order to make j become equal to 5). After the first 5 results are carried out, the program increments i and runs the inner loop again. The outer loop is also run 5 times, indeed it takes 5 times to make i equal to 5.

    As you can notice, the code written inside the two nested loops is run i*j times.

    I hope my answer was clear enaugh.