0

I am new in recursion, can someone please enlighten me.

The Problem is:

Find the average grade of the quiz of the Students with #101."

I already solve it using iteration, but I have no idea how to convert it into recursion.

import java.io.*; 
import java.util.*;

public class Test{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Scanner sc = new Scanner(System.in);

        String arr[][] = {{"101","Quiz","90"},{"101","CS","80"},{"102","Quiz","85"},{"101","Quiz","75"},{"103","CS","84"},{"101","Quiz","87"}};
        int sum = 0;
        int ave = 0;
        System.out.println("Student #\tType\tGrade");
        for(int ctr = 0; ctr<arr.length; ctr++){
            System.out.println(arr[ctr][0]+"\t\t"+arr[ctr][1]+"\t"+arr[ctr][2]);

            if(arr[ctr][0] == "101"){
                if(arr[ctr][1] == "Quiz"){
                    sum += Integer.parseInt(arr[ctr][2]);
                    ave += 1;
                }
            }

        }
        System.out.println("The Average quiz of Student # 101 is: "+ sum/ave);


    }



}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • 1
    While this `if(arr[ctr][1] == "Quiz")` works since you are comparing literals, you would be unpleasantly surprised if you would compare strings read from user with `==`. Please read ["How do I compare strings in Java?"](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – Pshemo Feb 13 '16 at 03:22
  • @Pshemo Good catch. Classic java gotchya. – Mark W Feb 13 '16 at 03:24
  • 1
    You may want to study existing posts on the topic that can be found https://www.bing.com/search?q=java+convert+loop+to+recursion. Some of the posts even have explanations (in addition to some theoretical articles like https://secweb.cs.odu.edu/~zeil/cs361/web/website/Lectures/recursionConversion/page/recursionConversion.html, but you should already be well aware of general approaches). – Alexei Levenkov Feb 13 '16 at 03:36
  • Why exactly do you need a recursive solution for what is not a recursive problem? – Jim Garrison Feb 13 '16 at 04:44

1 Answers1

0

You could do something like this, I don't think it's elegant/practical/good practice though:

public int[] recursiveAverage(String array[][], int i){
    if (i < array.length)
    {
        int[] previousAverage = recursiveAverage(array, i + 1);
    }
    else
    {
        int[] previousAverage = {0, 0};
    }

    if (array[i][0] == "101" && array[i][1] == "Quiz")
    {
        previousAverage[0] = Integer.parseInt(array[i][2]);
        ++previousAverage[1];
    }

    return previousAverage;
}

Then you would divide previousAverage[0] by previousAverage[1] to get the actual average. This is actually your iterative function, replacing the for loop with recursion.

Be creative.

S.Klumpers
  • 410
  • 3
  • 14