java - Understanding how nested for loop works -


i can't understand how nested loop works. doing ascending order program please explain me step step how works

class ascending {    public static void main(string args[]) {      int temp;     int a[] = {20, 10, 80, 70};     (int = 0; < 4; i++) {       system.out.println(a[i]);     }     (int = 0; < 4; i++) {       (int j = + 1; j < 4; j++) {         if (a[i] > a[j]) {           temp = a[i];           a[i] = a[j];           a[j] = temp;         }       }     }     system.out.println("\n after:");     (int = 0; < 4; i++) {       system.out.println(a[i]);     }   } } 

output:

20 10 80 70 

after:

10 20 70 80 

how nester loops working.

well quite simple, loop define follow :

for(init;condition;increment)

  • init : executed once @ beginning
  • condition : check before every execute (like while)
  • increment : done after code in loop

here, 1 loop,

for (int = 0; < 4; i++) {     // code  } 

this same as

int = 0; while(i < 4){     // code     i++; } 

if have nested loops, idea same, inner loop need execute many time condition true before outer 1 can increment , check condition again.

for (int = 0; < 4; i++) { //loop     (int j = + 1; j < 4; j++) { //loop b          // code     } } 

loop start i = 0, loop b start j = = 0. code execute until j => 4 exit loop b. there, loop execute increment part, i = 1.

the condition still true loop execute code, loop b start j = = 1.

and again ... until loop a's condition false.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -