Hey guys. I have been trying to write a progamme, and for some reason it doesn't give me the result I want. Anyway, here is a description of the programme I want:

"Suppose that a is a positive integer. Suppose we repeatedly modify a as follows: if a is even, we
divide it by 2, if a is odd, we multiply it by 3 and add 1; we stop the process when a is equal to
1. Write the method lengthSeq(a) that returns the number of values assigned to a.
For example lengthSeq(5) should return the value 6 (sequence: 5 16 8 4 2 1), lengthSeq(13)
should return the value 10 (sequence: 13 40 20 10 5 16 8 4 2 1), and lengthSeq(1) should return
the value 1. Write a method that given a value a returns lengthSeq(a)."

Ok, so my programme prints out 2 for all/most values of int a for some reason. I have the feeling that my mistake is painfully obvious (or at least i hope so, otherwise i'd probably have to rewrite the whole thing) could you help me find what is wrong?

public class Question3
{

    public static void main (String arg [])
    {
        int a = 13;
        
       {
  int count = lengthSeq (a);
   System.out.println (count);
}
}
public static int lengthSeq (int a)

{
   
  int count = 0;
  while (a != 1)
  {
      
      
     if (a%2 == 0)
     
     a = (a/2);
     count++;
     
     if (a%2 != 0)
     
     a = ((3*a) + 1);
     count++;
    
     if (a == 1)
     
     count++;
    break;

     }
     a = count;
    return a;
}
}

Edited 5 Years Ago by herstein: n/a

First of all... You have no {} for your if(s).
Second... ALL of your if(s) COULD execute in one loop, rather than be mutually exclusive. However, for what you are doing, that will not make much of a difference.

First of all... You have no {} for your if(s).
Second... ALL of your if(s) COULD execute in one loop, rather than be mutually exclusive. However, for what you are doing, that will not make much of a difference.

thanks for the reply! if i put my if statements in {}, doesn't the count reset? also, if there are brackets, what will happen to the new value of a? doesnt reset as well?

Well... You are using {} in your while loop, and it doesn't reset a or the count.
So, no... They will not reset anything.
If you had a new a or a new count inside the {},
they would be different variables than the a or count outside the {}.

This article has been dead for over six months. Start a new discussion instead.