PHP Program to print the even numbers up to n


February 3, 2022, Learn eTutorial
2763

What are Even Numbers?

Even numbers are those numbers Mod(%) 2 and the remainder will be 0. For example, if the entered number is 8 and when '8 % 2' is calculated and the result will be 0 so it is an even number.

How to print the even numbers up to n using PHP?

In this program, we are going to print the even number up to the number entered by the user. For that first of all, we have to accept the limit from the user and assign the value into the variable n. Then we have to Perform the for loop for that first assign the value 1 into the variable i and perform the loop until the condition 'i <=n' becomes false and in the block of the loop we have to check the condition  'i % 2 == 0' if true print the value of the variable i which will be a even number.

ALGORITHM

Step 1: Accept the limit from the user and assign it to the variable n

Step 2: Assign the value 1 into the variable i perform the following sub-step until the condition 'i <= n' becomes false and increment the value of the i in every iteration

        (i) Check the condition 'i % 2 == 0' if true print the value of the variable i which will be a even number

PHP Source Code

                                          <?php
$n = readline("Enter the limit of number required: ");
for ($i = 1; $i <= $n; $i++) {
    if (($i % 2) == 0) {
        echo " $i ";
    }
}
?>
                                      

OUTPUT

Enter the limit of number required: 50
 2  4  6  8  10  12  14  16  18  20  22  24  26  28  30  32  34  36  38  40  42  44  46  48  50