Friday

PHP Script — Display Even and Odd Numbers

PHP script using loop to display even and odd numbers between 1 and a specified end number. The code can be modified for different number range.

Even numbers are those which are divisible by 2. Numbers like 2,4,6,8,10, etc are evenOdd numbers are those which are not divisible by 2; they  are numbers whose remainder equals 1 if divided by two.

This program displays even and odd numbers between 1 and a specified limit. The limit can be changed by changing the value of the last number variable. The initial even or initial odd number value can also be changed to specify the start number.

<?php
	$last_number = 50; #the end number - value can be changed
	# Display Even Number
echo "<p><strong>Even Numbers</strong>:<br />";
$i = 2; # initial even number
while ($i <= $last_number){
/* display $i only if it's remainder division results into 0 */
if($i % 2 == 0){
echo $i.", ";
}
$i++;
}

	#Display Odd Numbers
echo "<p><strong>Odd Numbers</strong>:<br />";
$i = 1; # initial odd number
while ($i <= $last_number){
/* display $i only if it's remainder division results into 1 */
if($i % 2 == 1){
echo $i.", ";
}
$i++;
}
?>

No comments:

Post a Comment