Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Print Numbers from 1 to N without using loop

In this post, we will see how to Print Numbers from 1 to N without using loop.


Problem

Print Number from 1 to N without using any loop.

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

Using Recursion

We can use tail recursion to solve this problem.

  • Base case
    • When n
  • call printNumbers recursively with n-1
  • Print number while returning from recursion.
package org.arpit.java2blog;

public class PrintNumbersWithoutLoop {

	public static void main(String[] args) {
		PrintNumbersWithoutLoop pnwl=new PrintNumbersWithoutLoop();
		pnwl.printNumbers(10);

	}

	public void printNumbers(int n)
	{
		if(n

Output

1 2 3 4 5 6 7 8 9 10

That’s all about how to print Numbers from 1 to N without using loop.

The post Print Numbers from 1 to N without using loop appeared first on Java2Blog.



This post first appeared on How To Learn Java Programming, please read the originial post: here

Share the post

Print Numbers from 1 to N without using loop

×

Subscribe to How To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×