0

I am trying to run the while loop until it equals to thirty.

<?php
      $num1=0;
  $num2=0;
  $sum= $num1 + $num2;

  while($sum=30){
      $num1++;
      $num2++;      
      echo "$sum is equal to 30";      
     }

   ?>
1
  • 2
    $sum= $num1 + $num2; should be inside the while loop or it is going to be a infinite loop. Commented Nov 11, 2013 at 11:23

5 Answers 5

3

You need to change while($sum=30) to while($sum<30). Then, the while loop will end after you reached 30. The echo then comes after the closing bracket. Sp your working code will look like this:

while( $sum < 30 )
{
  $num1++;
  $num2++;
  $sum = $num1 + $num2;
}
echo "sum is $sum (which is 30)";
Sign up to request clarification or add additional context in comments.

4 Comments

your comparison is wrong echo "$sum is 30"; will print 32 is 30
You are right. I'll fix this. Anyway he should check the result later on, too.
this works, but $sum will be 32 after the last loop cycle (if $num1 and $num2 start with 0) ;) - you enter the loop one last time at $sum == 30, increment both nums and calculate sum again
I know. In this case it works. But in reality you often work with variales that are more complex than here :)
2

You are calculating the sum outside the while loop, so inside the loop the $sum never changes. You have to calculate the sum inside the loop. also = is assignment operator. you must use comparison operator to compare.

    $num1=0;
    $num2=0;
    $sum=0; //initilize you sum to 0
    while($sum<30){ // loop while your sum is less than 30
        $sum= $num1 + $num2; //calculate the sum
        $num1++;
        $num2++;
    }
        echo "$sum is equal to 30"; 
?>

Reference:Comparison Operators

3 Comments

This workds. But why did you change it to less than 30 ($sum<30) ?
The loop has to continue to calculate the sum till it reaches 30.
you can use != in your case, but if you start with $num1=1; or $num2=1; you may never hit sum of 30. so in that case < helps.
0

use equality operator (==) not assignment operator (=)

Comments

0

This loop not ends. $sum ever is 0 !.

Comments

0
$num1=0;
$num2=0;
$sum= $num1 + $num2;

$x = 0;
while(!$x && $sum <=30){
   $num1++;
   $num2++;

   $sum= $num1 + $num2;
   if($sum ==30){
      echo $sum." is equal to 30";
      $x = 1;
   }
}

Try this! Have a nice day !!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.