Write a PHP Program to print 5 to 15 using Conditional statements

Description: Write a PHP program to print the numbers from 5 to 15 using conditional statements, without using any loop.

Rules and hints:

  • You can use a function with arguments.
  • You can not use a loop (for, while, foreach).
  • You can use if conditions.

PHP program to print 5 to 15 without a loop

<?php
function printNumbers($current, $end) {
    if ($current > $end) {
        return;                       // stop
    }

    echo $current . "<br>";
    printNumbers($current + 1, $end); // call the function again
}

printNumbers(5, 15);
?>

Output:

Tutorials Class - Output Window

5
6
7
8
9
10
11
12
13
14
15

How it works

  • The function prints the current number, and then calls itself with the next number.
  • When the current number becomes bigger than the end number, the if condition stops the function. This is called recursion.

Read about PHP functions and see another example of recursion in factorial using recursion.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.