0

How can I make this code a recursive method?

for (int i = 3; i < arr.length; i++) {
    writer.write(arr[i] + "\n");
    strout += arr[i] + "\n";
}
3
  • 4
    Why would you want to make that recursive? Commented Apr 20, 2022 at 19:36
  • i have only one for loop in my code and professor wants a recursive function Commented Apr 21, 2022 at 16:12
  • i was finally able to get the recursive function to work in my code. there were a few things I had to change in order to make it happen. this is what i did to call the function. String strRec = printRecursive(writer,arr,3); writer.write(strRec); strout +=strRec; Commented Apr 23, 2022 at 20:26

2 Answers 2

2

You can try encapsulating the code in a function:

 public static String printRecursive(BufferedWriter writer, String[] arr, int i) throws IOException {        
     String strout = "";
     if(i<arr.length) {
        writer.write(arr[i] + "\n");
        //System.out.println(arr[i] + "\n");
        strout += arr[i] + "\n" + printRecursive(writer,arr,i+1);
     }
    return strout;
 }

And you can call it from main:

  String strRec = printRecursive(writer,arr,3);

I hope this help you.

Edited: Added writer according last comment

Sign up to request clarification or add additional context in comments.

4 Comments

when i add the above code block i get error. to create a class for writer.
I will try to help you, but I don't know how you have defined your writer because in your question I can't see this. Of course, you should declare inside the function if it isn't a general variable of the class. Also you can uncomment the System.out.println I wrote.
try (BufferedWriter writer = new BufferedWriter(new FileWriter(symbol + ".csv"))) { writer.write("Date,Open,High,Low,Close,Adj Close,Volume\n"); for (int i = 3; i < arr.length; i++) { writer.write(arr[i] + "\n"); strout += arr[i] + "\n"; }
I've edited the answer above, you can add the writer as parameter.
0

Something like that?

let arr = [/* array elements */];
let idx = 3;
let stdout = "";

const recursiveMethod = () => {
  writer.write(`${arr[idx]}\n`);
  strout += `${arr[idx]}\n`;
  
  if(idx < arr.length) {
    idx++;
    return recursiveMethod();
  }
}

recursiveMethod();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.