Open In App

PHP Program to Print Numbers from N to 1 in Reverse Order

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number N, the task is to print numbers from N to 1 in reverse order using PHP. This is a common programming task that can be accomplished using different approaches, such as loops or recursion.

Examples:

Input: N = 10
Output: 10 9 8 7 6 5 4 3 2 1

Input: N = 15
Output: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Below are the approaches to print numbers from N to 1 in reverse order in PHP:

Using For Loop

One of the simplest method to print numbers in reverse order is by using a for loop. In this approach we define the printReverseNums() function which takes an integer $n as an argument and uses a for loop to print numbers from $n to 1. The loop starts with $i = $n and decrements $i by 1 in each iteration until $i is greater than or equal to 1.

Example: This example shows the use of the above-explained approach.

PHP
<?php

function printReverseNums($n) {
    for ($i = $n; $i >= 1; $i--) {
        echo $i . " ";
    }
}

printReverseNums(10);

?>

Output
10 9 8 7 6 5 4 3 2 1 

Using While Loop

Another method to print numbers in reverse order is by using a while loop. In this approach, we define the printReverseNums() function which uses a while loop to print numbers from $n to 1. The loop continues as long as $i is greater than or equal to 1, and $i is decremented by 1 in each iteration.

Example: This example shows the use of the above-explained approach.

PHP
<?php

function printReverseNums($n) {
    $i = $n;
    while ($i >= 1) {
        echo $i . " ";
        $i--;
    }
}

printReverseNums(10);

?>

Output
10 9 8 7 6 5 4 3 2 1 

Using Recursion

Recursion is used to solve those problems where some logic is being repeated multiple times. In this approach, we define the printReverseNums() function which uses recursion to print numbers from $n to 1. The function calls itself with $n – 1 as the argument until $n is less than 1, which is the base condition that stops the recursion.

Example: This example shows the use of the above-explained approach.

PHP
<?php

function printReverseNums($n) {
    if ($n >= 1) {
        echo $n . " ";
        printReverseNums($n - 1);
    }
}

printReverseNums(10);

?>

Output
10 9 8 7 6 5 4 3 2 1 

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads