Kaarim Saidi
Kaarim Saidi

Reputation: 21

Printing the letters from A-Z using recursion in c#

So here's what I have so for, I'm trying to print all the numbers from A-Z but it only prints Z, please help and thanks (using recursion)

using system;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace AtoZRecursion
{ 
    class Program
    {  
     static void Main(string[] args)
     {
        int number=65;
        getAplha(number);
        Console.WriteLine(Convert.ToChar(getAplha(number)));
        Console.ReadKey();
    }
    public static int getAplha(int number=65)
    {
        if (number==90)
        {
            return Convert.ToChar(number);
        }
        return Convert.ToChar(getAplha(number + 1));
    }

}

}

Upvotes: 2

Views: 1064

Answers (5)

Eser
Eser

Reputation: 12546

You can change the return type of your method and invoke it like Console.WriteLine(getAplha(65));

public static string getAplha(int number = 65)
{
    if (number == 90)
    {
        return "" + (char)number;
    }
    return (char)number + getAplha(number + 1);
}

Upvotes: 2

juharr
juharr

Reputation: 32296

For this to work you need the Console.WriteLine inside of the recursive method

public static void getAplha(int number=65)
{
    Console.WriteLine(Convert.ToChar(number));
    if (number==90)
    {
        return;
    }

    getAplha(number + 1);
}

And then you don't need a return type.

Upvotes: 0

Mario Tacke
Mario Tacke

Reputation: 5498

You are only logging the last value of the recursion in Console.WriteLine. Instead, wrap your WriteLine like this:

using system;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace AtoZRecursion
{ 
    class Program
    {  
        static void Main(string[] args)
        {
            int number=65;
            getAplha(number);

            Console.ReadKey();
        }

        public static int getAplha(int number=65)
        {
            if (number==90)
            {
                Console.WriteLine(Convert.ToChar(number));
                return Convert.ToChar(number);
            }

            Console.WriteLine(Convert.ToChar(number));
            return Convert.ToChar(getAplha(number + 1));
        }
    }
}

Upvotes: 0

BryanT
BryanT

Reputation: 412

The WriteLine only happens once, when you "pop" back from the deepest recursion level. You need to write from the getAlpha method.

Upvotes: 0

Cecilio Pardo
Cecilio Pardo

Reputation: 1717

Remove the WriteLine from Main and put it just at the start of getAlpha, so that every letter is printed, as there is a call for each letter.

Upvotes: 2

Related Questions