[Java] Write a recursive function to print the following output based on "hello" as input. hello hell hel he h he hel hell hello Then modify the code above to change the output to right justified and remove letter on the left. hello ello llo lo o lo llo ello hello
This is the forward hello code: class RecurseHello { public static void printReducedString(String inp,int num) { int offset; if (num < 0) { offset = 6 + num ; } else { offset = num; } System.out.println(inp.substring(0,offset)); if (num > 1 ) { printReducedString(inp,num-1); } if (num < -1) { printReducedString(inp,num+1); } } public static void main(String[] args) { printReducedString("hello",5); printReducedString("hello",-4); } } And this is the Backward hello code: class BackHello { public static void printReducedString(String inp,int num) { int offset; String offspace =""; if (num < 0) { offset = 5 + num ; } else { offset = num; } for (int x = 0; x < offset ;x++) { offspace = offspace + " "; } if (offset != 5) { System.out.println(offspace + inp.substring(offset,5)); } if (num > 0 ) { printReducedString(inp,num-1); } if (num < -2) { printReducedString(inp,num+1); } } public static void main(String[] args) { printReducedString("hello",-5); printReducedString("hello",5); } } There might be better ways to do this....
Hi, can you please explain your code? I dont really understand. My computer science teacher didn't really teach me anything.
Here is the code with some useful comments for RecurseHello. Sorry for the lack before. Let me know if this helps. class RecurseHello { public static void printReducedString(String inp,int num) { int offset; // If the num argument is negative, offset the count by 1 // more than the size of the string if (num < 0) { offset = 6 + num ; } else { // else use the num argument as offset offset = num; } // This prints the substring of the inp variable System.out.println(inp.substring(0,offset)); // If the num argument is greater than 0 // call the printReducedString with num-1 if (num > 1 ) { printReducedString(inp,num-1); } // if the num argument is less than 0 // call the printReducedString with num + 1 if (num < -1) { printReducedString(inp,num+1); } // If it is 0, then let the function exit. } public static void main(String[] args) { //call recursive function to print string reducing printReducedString("hello",5); // call recursive function to print string increasing printReducedString("hello",-4); } }
If that is confusing, please feel free to ask any questions.
Join our real-time social learning platform and learn together with your friends!