Q1. Can you write a sample code that will count the number of “A”s in a given text? Show iterative, recursive, and tail recursive approaches? “AAA rating” A1. Iteration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class Iteration { public int countA(String input) { if (input == null || input.length( ) == 0) { return 0; } int count = 0; for (int i = 0; i < input.length( ); i++) { if(input.substring(i, i+1).equals("A")){ count++; } } return count; } public static void main(String[ ] args) { System.out.println(new Iteration( ).countA("AAA rating")); // Ans.3 } } |
Recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class RecursiveCall { public int countA(String input) { // exit condition – recursive calls must have an exit condition if (input == null || input.length( ) == 0) { return 0; } int count = 0; //check first character of the input if (input.substring(0, 1).equals("A")) { count = 1; } //recursive call to evaluate rest of the input //(i.e. 2nd character onwards) return count + countA(input.substring(1)); } public static void main(String[ ] args) { System.out.println(new RecursiveCall( ).countA("AAA rating")); // Ans. 3 } } |
Many find it harder to understand recursion, hence…