Learn how to easily print the numbers from 1 to 100 or a custom range without using loops in JavaScript.

A task like printing or storing the numbers within a range e.g from 1 to 100 it's quite intuitive using loops isn't? But what if suddenly a crazy teacher creates an assignment that specifies that you should print the numbers within a range without using loops? It happened to me, so I will be sharing with you the solution for this problem in JavaScript (the logic should work in any other programming language).

Using recursion

The ideal solution uses recursion to print any range of numbers, including negative numbers:

/**
 * This function prints the numbers between a range including them
 * and without using loops (using recursion).
 * 
 * @param start 
 * @param end 
 */
function PrintNumbers(start, end){
    console.log(start);

    if(start < end){
        PrintNumbers((start + 1), end);
    }
}

// Print numbers from 1 to 100 in the console
PrintNumbers(1, 100);

You can see a live example in the following fiddle:

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors