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); 
                return g(s, index + 1); 
        } // g() 
    public static void main(String[] args) 
        } // 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?

This question has already been answered. Start a new discussion instead.