The Wayback Machine - https://web.archive.org/web/20240717180320/https://www.geeksforgeeks.org/print-1-to-n-without-using-loops/
Open In App

Print 1 to n without using loops

Last Updated : 09 May, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

You are given an integer N. Print numbers from 1 to N without the help of loops.

Examples:

Input: N = 5
Output: 1 2 3 4 5
Explanation: We have to print numbers from 1 to 5.

Input: N = 10
Output: 1 2 3 4 5 6 7 8 9 10
Explanation: We have to print numbers from 1 to 10.

Approach: If we take a look at this problem carefully, we can see that the idea of “loop” is to track some counter value, e.g., “i = 0” till “i <= 100”. So, if we aren’t allowed to use loops, how can we track something?

Well, one possibility is the use of ‘recursion‘, provided we use the terminating condition carefully. Here is a solution that prints numbers using recursion. 
 

C++

// C++ program to How will you print
//  numbers from 1 to n without using a loop?
#include <iostream>
using namespace std;

class gfg {

    // It prints numbers from 1 to n.
public:
    void printNos(unsigned int n)
    {
        if (n > 0) {
            printNos(n - 1);
            cout << n << " ";
        }
        return;
    }
};

// Driver code
int main()
{
    int n = 10;
    gfg g;
    g.printNos(n);
    return 0;
}

C

#include <stdio.h>

// Prints numbers from 1 to n
void printNos(unsigned int n)
{
    if (n > 0) {
        printNos(n - 1);
        printf("%d ", n);
    }
    return;
}

// Driver code
int main()
{
    int n = 10;
    printNos(n);
    getchar();
    return 0;
}

Java

import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;

class GFG {
    // Prints numbers from 1 to n
    static void printNos(int n)
    {
        if (n > 0) {
            printNos(n - 1);
            System.out.print(n + " ");
        }
        return;
    }

    // Driver Code
    public static void main(String[] args)
    {
        int n = 10;
        printNos(n);
    }
}

Python3

# Python3 program to Print
# numbers from 1 to n


def printNos(n):
    if n > 0:
        printNos(n - 1)
        print(n, end=' ')


# Driver code
n = 10
printNos(n)

C#

// C# code for print numbers from
// 1 to n without using loop
using System;

class GFG {

    // Prints numbers from 1 to n
    static void printNos(int n)
    {
        if (n > 0) {
            printNos(n - 1);
            Console.Write(n + " ");
        }
        return;
    }

    // Driver Code
    public static void Main()
    {
        int n = 10;
        printNos(n);
    }
}

PHP

<?php
// PHP program print numbers 
// from 1 to n without 
// using loop    

// Prints numbers from 1 to n
function printNos($n)
{
    if($n > 0)
    {
        printNos($n - 1);
        echo $n, " ";
    }
    return;
}

// Driver code
$n=10;
printNos($n);
?>

Javascript

// Javascript code for print numbers from 
    // 1 to n without using loop
    
    // Prints numbers from 1 to n
    function printNos(n)
    {
        if(n > 0)
        {
            printNos(n - 1);
            console.log(n + " ");
        }
        return;
    }
    
    var n = 10;
    printNos(n);
Output

1 2 3 4 5 6 7 8 9 10 

Time Complexity: O(n)
Auxiliary Space: O(n)


Previous Article
Next Article

Similar Reads

Print 1 to 100 in C++ Without Loops and Recursion
We can print 1 to 100 without using loops and recursion using three approaches discussed below: 1) Template Metaprogramming: Templates in C++ allow non-datatypes also as parameters. Non-datatype means a value, not a datatype. Example: C/C++ Code // CPP Program to print 1 to 100 // without loops and recursion #include &lt;iostream&gt; using namespac
3 min read
Sort an array using Bubble Sort without using loops
Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based on the following observations: The sorting algorith
9 min read
Multiply two integers without using multiplication, division and bitwise operators, and no loops
By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. Approach: Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times. Base case: When the numbers of times x has to be added becomes 0. Recurs
9 min read
Number of loops of size k starting from a specific node
Given two positive integer n, k. Consider an undirected complete connected graph of n nodes in a complete connected graph. The task is to calculate the number of ways in which one can start from any node and return to it by visiting K nodes. Examples: Input : n = 3, k = 3 Output : 2 Input : n = 4, k = 2 Output : 3 Lets f(n, k) be a function which r
5 min read
Understanding for loops in Java
Suppose it is required to print numbers from 1 to 5. One possible way to do this is with the help of below code: class GFG { public static void main(String args[]) { int a; a = 1; System.out.println(a); a=2; System.out.println(a); a=3; System.out.println(a); a=4; System.out.println(a); a=5; System.out.println(a); } } The above code might look simpl
4 min read
Performance of loops (A caching question)
Consider below two C language functions to compute sum of elements in a 2D array. Ignoring the compiler optimizations, which of the two is better implementation of sum? // Function 1 int fun1(int arr[R][C]) { int sum = 0; for (int i=0; i&lt;R; i++) for (int j=0; j&lt;C; j++) sum += arr[i][j]; } // Function 2 int fun2(int arr[R][C]) { int sum = 0; f
1 min read
Create loops of even and odd values in a binary tree
Given a binary tree with the node structure containing a data part, left and right pointers, and an arbitrary pointer(abtr). The node's value can be any positive integer. The problem is to create odd and even loops in a binary tree. An odd loop is a loop that connects all the nodes having odd numbers and similarly even loop is for nodes having even
10 min read
How to Analyse Loops for Complexity Analysis of Algorithms
We have discussed Asymptotic Analysis, Worst, Average and Best Cases and Asymptotic Notations in previous posts. In this post, an analysis of iterative programs with simple examples is discussed. The analysis of loops for the complexity analysis of algorithms involves finding the number of operations performed by a loop as a function of the input s
15+ min read
Inorder Tree Traversal without recursion and without stack!
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. 1. Initialize current as root 2. While current
9 min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg