Print 1 to n without using loops in Java Script

Program example to print 1 to n without using loops in Java Script.

Learn how to write a program to print 1 to n using recursive functions.

A function which called itself is called a recursive function.

Example

function fun1()

{

fun1(); // calling fun1() function within the function fun1

}

<html>
<head>
    <title></title>
</head>
<body>
<pre>    <script type="text/javascript">               
        var n = parseInt(prompt("enter the value n:"));

        var i = 1;
        main(i);
        function main(k) 
        { 
             
            if (k <= n) { 
                document.writeln(k);
                k++;
                main(k); //recursive function
            } 
            return 0; 
        } 
        


    </script>
</pre>
</body>
</html>

Input:

Enter the value n: 5

Output

1
2
3
4
5 

Program example to print n to 1 without using loops in Java Script.

<html>
<head>
    <title></title>
</head>
<body>
    <pre>
    <script type="text/javascript">



    var n = parseInt(prompt("enter the value n:"));

    var i = 1;
    main(i);
    function main(k) {

        if (k <= n) {
            
            k++;
            main(k);
            document.writeln(k-1);
        }
        return 0;
    }



    </script>
</pre>

</body>
</html>

Input:

Enter the value n: 5

Output

5
4
3
2
1


Leave a Comment