i want to use if within while loop plz check it out and point out the mistake

$n=2;
$e=8;
$n=$e;
while ($n<=$e)
  {
    if ($n%2=0)
	{
     echo"result is " .$n
	 $n=$n+1;
	  }
	 else
	    {
		 echo "invalid";
		 }
	}

Recommended Answers

All 5 Replies

i dont have a clue what is ment to happen here
but line 8 at the end needs a ;
explain why u need it anu i and other my be able to help

Member Avatar for diafol

Your bracing and indenting is all over the place. Tidy it up! My fave, but other formatting poss:

$n=2;
$e=8;
$n=$e;
while ($n<=$e){
    if ($n%2=0){
        echo"result is " .$n;
	$n=$n+1;
    }else{
	echo "invalid";
    }
}

Now I can see that motters was right - add a ; at end of line 6

Why declare $n=2 on line 1 and then $n=$e on line 3?

I realize you are using "less than or equal to" in your for() loop but is it possible you're getting undesired output because you are reassigning $n? It seems redundant, at the very least.

And listen to ardav- formatting is a must, especially when you use the forums because it's harder for others to read sloppy code ;)

The problem is on line 6. You should write

if ($n%2==0)

instead of

if ($n%2=0)
Member Avatar for diafol

From the other 'spots':

$n=2;
$e=8;
while ($n<=$e){
    if ($n%2==0){
        echo"result is " .$n;
    }else{
	echo "invalid";
    }
    $n++;
}

If you leave in the $n=$e, the loop will run once only as it is at the max permissible value (8).
If you have the incrementer ($n++ or $n=$n+1) inside the conditional structure, you will get an infinite loop once the value of $n is odd.

The above code should give:

result is 2
invalid
result is 4
invalid
result is 6
invalid
result is 8

I'm a little confused as to what the code is supposed to do.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.