w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Print the natural numbers from n to 1

Secondary Nav

C# Sharp Recursion : Exercise-2 with Solution

Write a program in C# Sharp to print numbers from n to 1 using recursion.
Test Data :
How many numbers to print : 10
Expected Output
:
10 9 8 7 6 5 4 3 2 1

C# Sharp Code:

using System;

class RecExercise1
{
    static int printNatural(int ctr,int stval)
    {
	if (ctr < 1)
	{
	    return stval;
	}

	Console.Write(" {0} ",ctr);
		ctr--;
	return printNatural(ctr,stval);
    }
    
    static void Main()
    {
	Console.Write("\n\n Recursion : Print the natural numbers from n to 1 :\n");
	Console.Write("--------------------------------------------------------\n");
	Console.Write(" How many numbers to print : ");
	int ctr= Convert.ToInt32(Console.ReadLine());
	// Call recursive method with two parameters.	
	printNatural(ctr,1);
	Console.Write("\n\n");
    }
}

C# Sharp Practice online:


using System;

class RecExercise1
{
    static int printNatural(int ctr,int stval)
    {
	if (ctr < 1)
	{
	    return stval;
	}

	Console.Write(" {0} ",ctr);
		ctr--;
	return printNatural(ctr,stval);
    }
    
    static void Main()
    {
	Console.Write("\n\n Recursion : Print the natural numbers from n to 1 :\n");
	Console.Write("--------------------------------------------------------\n");
	Console.Write(" How many numbers to print : ");
	int ctr= Convert.ToInt32(Console.ReadLine());
	// Call recursive method with two parameters.	
	printNatural(ctr,1);
	Console.Write("\n\n");
    }
}

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.