Hello. I'm currently revising for an exam in structures and algorithims, but recently ran across a problem in my studies. I have already tried lookung through notes, online and Daniel Liangs java book, but can't find exactly what I need. The code is as follows:

public class QuizTest
{
       public static void main (String args[]) {
                 quiz(5);
                 System.exit(0);
}
 
public static void quiz(int i)
{
               if(i>1)
               {
                      quiz(i/2);
                      quiz(i/2);
                }
                System.out.println("*");
     }
}

Now I've entered the code on my own pc, and I know the output is seven *, but I need to know how, and why. I already guessed that the quiz value of five is passed to i when i is created. But why are there two duplicate lines of code where quiz is equal to i divided by two, and if i is five how does it possibly go around 7 times when divided by two every time, or does the presence of the two duplicate lines mean it prints twice?

Sorry for rambling, but this has been bugging me for ages. Any help would be greatly appreciated.

The reason of 2 duplicate lines depends on the person who wrote the program. I don't know what he want to achieve by doing this...!!

The reason that it prints"*" 7 times is as follows

Initial value i =5;
Step 1 ) Called quiz(5)
Here 5>1
so called quiz 5 two times.
Step 2) Quiz(2)
Step 3) Quiz(2)

Now Quiz(2) of 3rd step again satisfy the condition 2>1 so it again calls Quiz 2 times.
Step 4) quiz(1)
This time it doesn't call quiz further because "1>1" condition gets wrong. But still it prints "*" bacause print statement outside if condition.
Step 5) quiz(1)

Similarliy step 3) also calls quiz 2 times

6) quiz(1)
7) quiz(1)

Every call to quiz results in printing of "*" so it gets printed 7 times since you callled quiz 7 times.

Yes! It makes sense now. Thank you so much, your a lifesaver :) I may actually pass now.

you may add System.out.println("middle");in the middle of two quiz statement.that analysis for "*"

This question has already been answered. Start a new discussion instead.