Sunday 28 April 2013

Nested For Loop Simplified

For Loop is used in programming languages almost in every code snippet. Moreover, if a program involves a multidimensional array , then the use of nested loop(inner loop)  is inevitable. The most simplest form of code of assigning a value to the multidimensional array using a For Loop is as follows:


PHP snippet                                                                            
                                                                              
$a = array();

for($l=0;$l<3;$l++){
    for($m=0;$m<3;$m++){
        $a[$l][$m] = 1;
        echo "Array:[".($l)."] [".($m)."]"." ";
         echo "Value: ".$a[$l][$m];
        echo "<br>";
       
    }
}

PHP Result

Array:[0] [0] Value: 1
Array:[0] [1] Value: 1
Array:[0] [2] Value: 1
Array:[1] [0] Value: 1
Array:[1] [1] Value: 1
Array:[1] [2] Value: 1
Array:[2] [0] Value: 1
Array:[2] [1] Value: 1
Array:[2] [2] Value: 1

However, if the same result is to be achieved with one loop rather than using nested loop, then the following code can prove to be useful:

PHP snippet

$l=3;     //Inner Loop
$m =3;   // Outer Loop
$a = array();
  
 for($i=$l;$i<(($m*$l)+$l); $i++){

    $j = $i % $l;
    $k = intval($i/$l);
    $a[$k-1][$j] = 1;
    echo "Array:[".($k-1)."] [".($j)."]"." ";
    echo "Value: ".$a[$k-1][$j];
    echo "<br>";
 }

PHP Result:

Array:[0] [0] Value: 1
Array:[0] [1] Value: 1
Array:[0] [2] Value: 1
Array:[1] [0] Value: 1
Array:[1] [1] Value: 1
Array:[1] [2] Value: 1
Array:[2] [0] Value: 1
Array:[2] [1] Value: 1
Array:[2] [2] Value: 1


This program is also used to reduce the Time Complexity to a certain extent.

1 comment: