开发者

Is There a More Efficient Way to Write Nested While Loops?

开发者 https://www.devze.com 2022-12-31 12:56 出处:网络
The code below shows nested while loops, but it\'s not the very efficient. Suppose I wanted to extend the code to include 100 nested while loops.Is there a better way to accomplish this task?

The code below shows nested while loops, but it's not the very efficient. Suppose I wanted to extend the code to include 100 nested while loops. Is there a better way to accomplish this task?

<?php 

$count = 1;

 $num = 1;
 $options=3;
 while ( $num <=$options ) 
    { 
echo "(".$num . ") "; 

    $num1 = 1; 
    $options1=3;
    while ( $num1 <=$options1 ) 
    { 
    echo "*".$num1 . "* "; 

        $num2 = 1; 开发者_StackOverflow
        $options2=3;
        while ( $num2 <=$options2 ) 
        { 
        echo "@".$num2 . "@ ";  

            $num3 = 1; 
            $options3=3;
            while ( $num3 <=$options3 ) 
            { 
            echo $num3 . " ";   
            $num3++; 
            $count++;
            }

        echo "<br />";
        $num2++; 
        }

    echo "<br />";
    $num1++; 
    }

echo "<br />";
$num++; 
} 
  echo $count;
 ?>


You should probably adapt your algorithm to use recursion instead of a nested while loop.


It's perfectly efficient enough if the loops need to be nested.

As others have said, recursion would allow you to "nest" different levels within each other more elegantly, and the level of nesting could be controlled dynamically rather than being hard-coed into your program - but if you find your design requires you to nest 100 loops, then your design is almost certainly completely mad.

(However, in the specific example you give there is no need for any loops (or recursion) at all. As all the loops are of constant length, you can precalculate the result and just echo a single constant string. I presume this is a hyporthetical example rather than the actual code you wish to write?)


You could use recursive functions.

0

精彩评论

暂无评论...
验证码 换一张
取 消