w3resource logo


C# Sharp Programming Exercises

C# Sharp Exercises: Print the first n natural number

Secondary Nav

C# Sharp Recursion : Exercise-1 with Solution

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

C# Sharp Code:

using System;

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

C# Sharp Practice online:


using System;

class RecExercise1
{
    static int printNatural(int stval, int ctr)
    {
	if (ctr < 1)
	{
	    return stval;
	}
	ctr--;
	Console.Write(" {0} ",stval);
	return printNatural(stval + 1, ctr);
    }
    static void Main()
    {
	Console.Write("\n\n Recursion : Print the first n natural number :\n");
	Console.Write("---------------------------------------------------\n");
	Console.Write(" How many numbers to print : ");
	int ctr= Convert.ToInt32(Console.ReadLine());
	// Call recursive method with two parameters.	
	printNatural(1, ctr);
	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.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program