PHP Program to print the odd numbers up to n


April 19, 2022, Learn eTutorial
2917

What are Odd Numbers?

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

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

In this program, we are going to print the odd 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 odd 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 odd 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
 1  3  5  7  9  11  13  15  17  19  21  23  25  27  29  31  33  35  37  39  41  43  45  47  49