w3resource

C#: 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 numbers using recursion.

Visual Presentation:

C# Sharp Exercises: Print the first n natural number

Sample Solution:

C# Sharp Code:

using System;

// Class definition named 'RecExercise1'
class RecExercise1
{
    // Recursive method to print the first 'ctr' natural numbers starting from 'stval'
    static int printNatural(int stval, int ctr)
    {
        // Base case: If the counter becomes less than 1, return the starting value
        if (ctr < 1)
        {
            return stval;
        }
        ctr--; // Decrement the counter
        Console.Write(" {0} ", stval); // Print the current value
        // Recursive call: Increment 'stval' and decrement 'ctr' to print the next natural number
        return printNatural(stval + 1, ctr);
    }

    // Main method, the entry point of the program
    static void Main()
    {
        // Display a description of the program
        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()); // Read the user input for the count of numbers

        // Call the recursive method to print the first 'ctr' natural numbers starting from 1
        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 :

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

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: C# Sharp Recursion Exercises.
Next: Write a program in C# Sharp to print numbers from n to 1 using recursion.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/csharp-exercises/recursion/csharp-recursion-exercise-1.php