settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Even Numbers from 1 to N in PHP

+2 votes

You are given a number num. Write a PHP script that loops through all of the numbers from 1 to num and prints only the even ones. The input comes as a parameter named num. The parameter num will hold a positive integer.

Examples:

Parameter name

Input

Output

num

5

2

4

 

Input

Output

2

2

 

asked in PHP category by user sam

1 Answer

+1 vote
 
Best answer

Here is the answer:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
<form>
    N: <input type="text" name="num"/>
    <input type="submit"/>
</form>
<?php
if (isset($_GET['num'])) {
    $num = intval($_GET['num']);
    for ($i = 0; $i <= $num; $i++) {
        if ($i % 2 == 0 && $i != 0) {
            echo $i . " ";
        }
    }
}
?>
</body>
</html>

 

answered by user samfred5830
selected by user golearnweb
...