﻿ C# Sharp Exercises: Print the first n natural number - w3resource

# C# Sharp Exercises: Print the first n natural number

## C# Sharp Recursion: Exercise-1 with Solution

Write a program in C# Sharp to print the first n natural number using recursion.

Pictorial Presentation:

Sample Solution:

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 : ");
// Call recursive method with two parameters.
printNatural(1, ctr);
Console.Write("\n\n");
}
}
```
```

Sample Output:

```Recursion : Print the first n natural number :
---------------------------------------------------
How many numbers to print : 20
1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20
```

Flowchart :

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

﻿

New Content: Composer: Dependency manager for PHP, R Programming