简体   繁体   中英

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 AZ 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));
    }

}

}

Main除去WriteLine并将其放在getAlpha ,这样就可以打印每个字母,因为每个字母都有一个调用。

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);
}

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

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));
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM