How to apply recursive functions?

Asked

Viewed 42 times

-1

Create a program in c# that allows using a recursive function, to determine the number of times the letter B appears in a word entered by the user.

  • You made some code?

  • didn’t do it yet! @Virgilionovic I’ve never used recursive function , I need Help.

  • You know what a recursive function is?

  • I know ! But I never used...

1 answer

1


Basically a recursive function is the one who invokes it until a certain condition satisfies, in the case of his question it seems that the exercise is to sweep the letter to its end, then a code below to illustrate how to read letter by letter and return this new text so that it is checked again, until there is no more text, example:

using System;

public class Program
{
    static int Count(string word, string letter)
    {   
        if (word.Length > 0){           
            if (letter == word.Substring(0,1))
            {
                return 1 + Count(word.Substring(1), letter);
            }
            else 
            { 
                return Count(word.Substring(1), letter);
            }
        }
        return 0;
    }
    public static void Main()
    {
        string palavra = "bcb0ç";
        System.Console.WriteLine(Count(palavra, "b"));
    }
}

Another code suggests better performance using index, where the occurrence is greater than -1 the value was found and jumps to the next search if it has any higher index than -1 and so on limiting the search in search only of the value sought:

using System;

public class Program
{
    static int Count(string word, string letter)
    {   
        if (word.Length > 0){           
            int index = word.IndexOf(letter);
            if (index > -1) 
            {
                return 1 + Count(word.Substring(index + 1), letter);
            }           
        }
        return 0;
    }
    public static void Main()
    {
        string palavra = "bcc0b00bb";
        System.Console.WriteLine(Count(palavra, "b"));
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.