Write a PHP script to displays numbers between 100 and 150 divisible by 4
Description: Write a PHP script to display the numbers between 100 and 150 that are divisible by 4.
Rules and hints:
- Use a loop and an
ifcondition. - Use the modulus operator (
%). A number is divisible by 4 when$i % 4is 0.
PHP program for numbers divisible by 4
<?php
for ($i = 100; $i <= 150; $i++) {
if ($i % 4 == 0) {
echo $i . " ";
}
}
?>
Output:
Tutorials Class - Output Window
100 104 108 112 116 120 124 128 132 136 140 144 148
How it works
- The loop checks every number from 100 to 150.
%gives the remainder of the division. If the remainder is 0, the number is divisible by 4, and it is printed.
A shorter way
Since 100 is divisible by 4, you can start from 100 and add 4 in every round. You do not need the if condition.
<?php
for ($i = 100; $i <= 150; $i += 4) {
echo $i . " ";
}
?>
Related: PHP Loops and division vs modulus.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |