So let's take "banana", what happens when the program gets to if (ch <= 'd')? My understanding is the 'b' is < 'd' so it moves to the else. Am I wrong or right? If I'm right, then what happens at return 1 + g(s, index + 1);

public class Q7f 
    { 
    public static int g(String s) 
        { 
        return g(s, 0); 
        } // g() 
    public static int g(String s, int index) 
        { 
        if (index >= s.length()) 
            return 0; 
        char ch = s.charAt(index); 
            if (ch <= 'd') 
                return 1 + g(s, index + 1); 
            else 
                return g(s, index + 1); 
        } // g() 
    public static void main(String[] args) 
        { 
        System.out.println(g("banana")); 
        System.out.println(g("cat")); 
        System.out.println(g("dog")); 
        } // main()
    } // class Q7f

Try debugging the code by adding some println statements to show where the execution flow goes and to show the values of the variables as they are changed and used.

I got it. It's a recursive loop. 'b' is considered less than 'd' so it returns 1 and increments 'index' by 1 and then goes back up to the top of the function and again. Since 'index' is now 1, and is still not greater than '6' (the length of banana) it runs that program now checking 'a' in banana which also passes the first if-statement and increments 1 again. Now it checks 'n', and since that's not less than 'd', it returns 0. etc. till the program ends. whew!

What do you think NormR1? Am I explaining it correctly?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.