What is recursive method?
Recursive method is a method which calls itself. There should always be a condition on which the recursion stops, else it will keep running indefinitely. Suppose we have to add numbers consecutively for particular start and end numbers.
Suppose start number is 2 and end number is 8, then consecutively you will add like below -
total = start + ..................... + end
= 2 + 3 + 4 + 5 + 6 + 7 + 8
= 5 + 4 + 5 + 6 + 7 + 8
= 9 + 5 + 6 + 7 + 8
= 14 + 6 + 7 + 8
= 20 + 7 + 8
= 27 + 8
= 35
We use the same concept for writing recursive method to add consecutive numbers.
Class SumRecursive (SumRecursive.java)
public class SumRecursive {
public static void main(String args[]) {
int start = 2, end = 8;
int next = start + 1;
int total = sum(start, next, end);
System.out.println("Total is: " + total);
}
public static int sum(int total, int next, int end) {
int tot = total + next;
if(next != end) {
next++;
tot = sum(tot, next, end);
}
return tot;
}
}
Here is the output:
Total is: 35
Reverse the string using recursive method
To reverse a string, we have created two methods - revStr() and swapChars(). In the main method, user is asked to enter any string. String is converted to a char array. The converted array is passed to the method revStr() as the parameter. revStr() method calls method swapChars() and pass the char array and the first and last character positions to swap. Here is the logic -
Suppose user enters the string: "Logic Blocks" -
Converted char array will be like this.
ch[] = {'L', 'o', 'g', 'i', 'c', ' ', 'B', 'l', 'o', 'c', 'k', 's'}
Characters will be swapped like this
'L' = > 's'
'o' = > 'k'
'g' = > 'c'
'i' = > 'o'
'c' = > 'l'
' ' = > 'B'
Reversed String will be like this
"skcolB cigoL"
Class Reverse (Reverse.java)
import java.util.Scanner;
public class Reverse {
public static void main(String args[]) {
String s1, s2;
char ch[];
System.out.println("Enter the string:");
Scanner sc = new Scanner(System.in);
s1 = sc.nextLine();
ch = s1.toCharArray();
s2 = revStr(ch);
System.out.println();
System.out.println("String backwards:");
System.out.println(s2);
}
public static String revStr(char[] ch) {
swapChars(ch, 0, ch.length-1);
String str = String.valueOf(ch);
return str;
}
public static void swapChars(char[] ch, int left, int right) {
if(left < right) {
char tch = ch[left];
ch[left] = ch[right];
ch[right] = tch;
swapChars(ch, left+1, right-1);
}
}
}
Here is the output:
Enter the string:
Logic Blocks
String backwards:
skcolB cigoL
No comments:
Post a Comment