CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Join Date
    Sep 2009
    Posts
    8

    need help with loops plz

    hi i am new to java programming and im working on a looping program involving the fibonacci numbers.
    what i would like to do is to have a program that asks the user how many values of the Fibonacci sequence to output. Then i want to create a loop that outputs the number of values of the Fibonacci sequence requested by the user.
    i only want to use the do....while loop, for loop, and the while loop
    the following code i will post does not do what i want and i cannot figure out why
    first off when i input a number it doesnt display the desired out......it just displays the same exact 15 numbers
    and second my for loop works but all the other ones do not
    any help would be very much appreciated ty

    import javax.swing.JOptionPane;

    public class Lab4
    {
    public static void main(String[] args)
    {
    String aString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int aInt = Integer.parseInt(aString);
    for1();
    do1();
    while1();
    for2();
    do2();
    while2();
    }
    public static void for1()
    {
    String aString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int aInt = Integer.parseInt(aString);
    for(int i = 1; i <= aInt; i++)
    {
    int f = fib(i);
    System.out.println("Fib(" + i + ") = " + f);
    }
    }


    public static void do1()
    {
    String bString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int bInt = Integer.parseInt(bString);
    do
    {
    int f = fib(i);
    }
    while(int h = 1; h <= bInt; h++);
    System.out.println("Fib(" + h + ") = " + f);
    }

    public static void while1()
    {
    String cString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int cInt = Integer.parseInt(cString);
    while(int i = 1; i <= cInt; i++)
    {
    int f = fib (i);
    System.out.println("Fib(" + i + ") = " + f);
    }


    public static int fib(int n)
    {
    if (n <= 2)
    return 1;
    else
    return fib(n - 1) + fib(n - 2);
    }
    }

  2. #2
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: need help with loops plz

    First, when posting code please use [code] tags so your code is readable (properly formatted/indented).

    Second, check the syntax of your do-while and while loops. They don't compile; I don't believe you were even able to run your program, so I don't know how you can claim that it "just displays the same exact 15 numbers".

  3. #3
    Join Date
    Apr 2009
    Location
    TR
    Posts
    97

    Re: need help with loops plz

    your code is incomplete..where is your for2(), do2() and while2() methods..
    u tried something but it seems something went wrong..
    if we look your code :
    Code:
    import javax.swing.JOptionPane;
    import java.util.*;
    
    public class Lab4
    {
    public static void main(String[] args)
    {
    String aString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int aInt = Integer.parseInt(aString);
    
    //why did write code above..(last 3 line)
    
    for1();
    do1();
    while1();
    for2();     //where is your for2() method..
    do2();     // where is your do2() method..
    while2();  //where is your while2() method..
    }
    public static void for1()
    {
    String aString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int aInt = Integer.parseInt(aString);
    for(int i = 1; i <= aInt; i++)
    {
    int f = fib(i);
    System.out.println("Fib(" + i + ") = " + f);
    }
    }
    
    
    public static void do1()
    {
    String bString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int bInt = Integer.parseInt(bString);
    do
    {
    int f = fib(i);     //why did you use i..where did u define i in your do1() method..
    }
    while(int h = 1; h <= bInt; h++);
    System.out.println("Fib(" + h + ") = " + f);
    }
    
    public static void while1()
    {
    String cString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int cInt = Integer.parseInt(cString);
    while(int i = 1; i <= cInt; i++)       //where did u see like this using while :eek:
    {
    int f = fib (i);
    System.out.println("Fib(" + i + ") = " + f);
    }
    
    
    public static int fib(int n)
    {
    if (n <= 2)
    return 1;
    else
    return fib(n - 1) + fib(n - 2);
    }
    } 
    }

    Please use code tags like this :
    [SIGPIC][/SIGPIC]
    Code Your Dreams

  4. #4
    Join Date
    May 2002
    Location
    Lindenhurst, NY
    Posts
    867

    Re: need help with loops plz

    Quote Originally Posted by holestary View Post
    if we look your code :
    The point of code tags is to preserve indentation, not for the pretty colors.

  5. #5
    Join Date
    Sep 2009
    Posts
    4

    Re: need help with loops plz

    Apart from errors already mentioned by others there is a issue with your methods for1() and other loop methods.
    You are taking user input in "userInput" variable and parsing "aString" for loop control. You have given "aString" default value of 15. So, user input is getting ignored.


    Quote Originally Posted by Zero-Method View Post
    hi i am new to java programming and im working on a looping program involving the fibonacci numbers.
    what i would like to do is to have a program that asks the user how many values of the Fibonacci sequence to output. Then i want to create a loop that outputs the number of values of the Fibonacci sequence requested by the user.
    i only want to use the do....while loop, for loop, and the while loop
    the following code i will post does not do what i want and i cannot figure out why
    first off when i input a number it doesnt display the desired out......it just displays the same exact 15 numbers
    and second my for loop works but all the other ones do not
    any help would be very much appreciated ty

    import javax.swing.JOptionPane;

    public class Lab4
    {
    public static void main(String[] args)
    {
    String aString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int aInt = Integer.parseInt(aString);
    for1();
    do1();
    while1();
    for2();
    do2();
    while2();
    }
    public static void for1()
    {
    String aString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int aInt = Integer.parseInt(aString);
    for(int i = 1; i <= aInt; i++)
    {
    int f = fib(i);
    System.out.println("Fib(" + i + ") = " + f);
    }
    }


    public static void do1()
    {
    String bString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int bInt = Integer.parseInt(bString);
    do
    {
    int f = fib(i);
    }
    while(int h = 1; h <= bInt; h++);
    System.out.println("Fib(" + h + ") = " + f);
    }

    public static void while1()
    {
    String cString="15";
    String userInput = JOptionPane.showInputDialog("How many values of the Fibonacci sequence would you like?");
    int cInt = Integer.parseInt(cString);
    while(int i = 1; i <= cInt; i++)
    {
    int f = fib (i);
    System.out.println("Fib(" + i + ") = " + f);
    }


    public static int fib(int n)
    {
    if (n <= 2)
    return 1;
    else
    return fib(n - 1) + fib(n - 2);
    }
    }

  6. #6
    Join Date
    Sep 2009
    Posts
    8

    Re: need help with loops plz

    ok i fixed everything and got it to run
    the only problem is now ....i would like to remove the function at the end of my program and instead i would like to have 3 int variables......i think this would make the program more simplistic but every time ive tried to make a similar program with just the 3 ints instead it fails horribly


    Code:
    import javax.swing.JOptionPane;
    
    public class ex2
    {
      public static void main(String[] args)
      {
        for1();
        while1();
      }
      public static void for1()
      {
        int numFibs = (Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Fibonnacci Numbers to Display")));
    
    for(int i = 1; i <= numFibs; i++)
    {
       System.out.println(fib(i));
    }
      }
      public static void while1()
      {
         int numFibz = (Integer.parseInt(JOptionPane.showInputDialog("Enter the number of Fibonnacci Numbers to Display")));
         int i = 1;
         while(i <= numFibz)
         {
           System.out.println(fib(i));
           i++;
         }
      }
      public static int fib(int n)
        { 
           if (n <= 2)
                return 1;
           else
                return fib(n - 1) + fib(n - 2);
        }
    }

  7. #7
    Join Date
    Feb 2008
    Posts
    966

    Re: need help with loops plz

    Quote Originally Posted by Zero-Method View Post
    ok i fixed everything and got it to run
    the only problem is now ....i would like to remove the function at the end of my program and instead i would like to have 3 int variables......i think this would make the program more simplistic but every time ive tried to make a similar program with just the 3 ints instead it fails horribly


    Code:
    public static int fib(int n)
        { 
           if (n <= 2)
                return 1;
           else
                return fib(n - 1) + fib(n - 2);
        }
    }
    Say what? You want to get rid of this (^) "method"? Well no wonder it doesn't work if you get rid of it. How the hell is it supposed to calculate the Fibonacci sequence without it?

  8. #8
    Join Date
    Apr 2009
    Location
    TR
    Posts
    97

    Re: need help with loops plz

    Quote Originally Posted by Martin O View Post
    The point of code tags is to preserve indentation, not for the pretty colors.
    i know what is it for..i didn't play a game with color text..i wanted to draw attention where i saw wrong..and u can understand that..thanks for your advice..When it comes to my advice if u feel u must write something please help for threads..

    thanks again

    regards
    holestary

    Please use code tags like this :
    [SIGPIC][/SIGPIC]
    Code Your Dreams

  9. #9
    Join Date
    Sep 2009
    Posts
    8

    Re: need help with loops plz

    i wanted to get rid of
    Code:
    public static int fib(int n)
        { 
           if (n <= 2)
                return 1;
           else
                return fib(n - 1) + fib(n - 2);
        }
    }
    and instead have maybe a way to do the whole program using 3 int variables
    like
    int1 =
    int2=
    int3=

    and maybe something like fib = num1 + num2;
    or i dont know i am trying to figure it out lol
    i lose so much sleep over this language

  10. #10
    Join Date
    May 2002
    Location
    Lindenhurst, NY
    Posts
    867

    Re: need help with loops plz

    Quote Originally Posted by holestary View Post
    i know what is it for..i didn't play a game with color text..i wanted to draw attention where i saw wrong..and u can understand that..thanks for your advice..When it comes to my advice if u feel u must write something please help for threads..

    thanks again

    regards
    holestary
    Sorry I just figured if you're going to add the code tags, why leave it as an unindented mess? But now I see you just wanted to easily point out the problem to the OP. Sorry again

  11. #11
    Join Date
    Feb 2008
    Posts
    966

    Re: need help with loops plz

    Quote Originally Posted by Zero-Method View Post
    i wanted to get rid of
    Code:
    public static int fib(int n)
        { 
           if (n <= 2)
                return 1;
           else
                return fib(n - 1) + fib(n - 2);
        }
    }
    and instead have maybe a way to do the whole program using 3 int variables
    like
    int1 =
    int2=
    int3=

    and maybe something like fib = num1 + num2;
    or i dont know i am trying to figure it out lol
    i lose so much sleep over this language
    You are clearly not understand the Fibonacci algorithm. You cannot calculate Fibonacci just using three variables. You need to either use a loop or recursion, which you have done. Removing the method will mean that you are no longer calculating the sequence correctly. This cannot be replaced with three variables. The method you have is about as simple and as elegant as it gets.

  12. #12
    Join Date
    Sep 2009
    Posts
    8

    Re: need help with loops plz

    someone gave me this as a possible answer to getting rid of the last function and just using variables.........can't get it to work yet but it seems like it might be an easier approach
    Code:
    import javax.swing.JOptionPane;
    
    public class ex4
    {
      public static void main(String[] args)
      {
    
    int num1 = 1, numb2 = 0, fib = 0;
    int input = (Integer.parseInt(JOptionPane.showInputDialog(null, "How many numbers do you want to output?")));
    
    for (int i = 0; i < input; i++) {
    
    if (i == 0) {
    System.out.println("0");
    }
    
    else if (i == 1) {
    System.out.println("1");
    }
    
    else {
    fib = num1 + num2;
    System.out.println(fib);
    num2 = num1;
    num1 = fib;
    }
    
    }
      }
    }

  13. #13
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: need help with loops plz

    Quote Originally Posted by ProgramThis View Post
    You are clearly not understand the Fibonacci algorithm. You cannot calculate Fibonacci just using three variables. You need to either use a loop or recursion, which you have done. Removing the method will mean that you are no longer calculating the sequence correctly. This cannot be replaced with three variables. The method you have is about as simple and as elegant as it gets.
    He/she may have messed up the loops syntax, but I think Zero-Method understands the Fibonacci algorithm, his/her original fib() method shows that. The fact that Fibonacci is excellent to implement as a recursive method does not mean it cannot be implemented as a non-recursive one, using just 2 int variables. This method:
    Code:
    private static int nMinus2 = 0;
    private static int nMinus1 = 1;
    
    private static int fib() {
    	int fib = nMinus1 + nMinus2;
    	nMinus2 = nMinus1;
    	nMinus1 = fib;
    	return fib;
    }
    produces the same results as the recursive one. The only difference is that the first number (1) has to be produced out of the loop and the loop should start from the second number (that is the second 1):
    Code:
    System.out.println(1);
    for (int i = 2; i <= n; i++) {
    	System.out.println(fib());
    }
    Also, if you are going to experiment different types of loops you need to reinitialise the variables before starting the new loop.

  14. #14
    Join Date
    Feb 2008
    Posts
    966

    Re: need help with loops plz

    Quote Originally Posted by jcaccia View Post
    He/she may have messed up the loops syntax, but I think Zero-Method understands the Fibonacci algorithm, his/her original fib() method shows that.
    My reference to not understanding the algorithm stemmed from he/she stating that they could just get rid of the method and replace it with variables. Which isn't the case.

    Quote Originally Posted by jcaccia View Post
    The fact that Fibonacci is excellent to implement as a recursive method does not mean it cannot be implemented as a non-recursive one, using just 2 int variables. This method:
    Code:
    private static int nMinus2 = 0;
    private static int nMinus1 = 1;
    
    private static int fib() {
        int fib = nMinus1 + nMinus2;
        nMinus2 = nMinus1;
        nMinus1 = fib;
        return fib;
    }
    produces the same results as the recursive one.
    Not on it's own, which was my point. You cannot replace a recursive algorithm with 'once use' variables.

    Quote Originally Posted by jcaccia View Post
    The only difference is that the first number (1) has to be produced out of the loop and the loop should start from the second number (that is the second 1):
    Code:
    System.out.println(1);
     for (int i = 2; i <= n; i++) {
         System.out.println(fib());
     }
    Also, if you are going to experiment different types of loops you need to reinitialise the variables before starting the new loop.
    And there we go. This was the point I was trying to make, maybe not so clearly. If you are going to remove the recursive algorithm you have to have some type of loop structure to replace it. So, stating
    i would like to remove the function at the end of my program and instead i would like to have 3 int variables
    as the OP did, doesn't make sense. Nowhere did he indicate vai code, or via grammar that he was going to replace the method with a loop, but rather replace the method with 3 variables.

  15. #15
    Join Date
    Feb 2009
    Posts
    32

    Re: need help with loops plz

    Quote Originally Posted by ProgramThis View Post
    The method you have is about as simple and as elegant as it gets.
    Inefficiency isn't elegant.

    Don't use recursion for the Fibonacci sequence. It's running time is exponential --(3/2)^N. Every CS book that has a chapter on algorithmic analysis tells you this.
    Code:
    public class Test {
    	private final static int N = 40;
    	public static void main(String[] args) {
    		long start = System.currentTimeMillis();
    		int a = 0, b = 1, c = 1;
    		for (int i = 4; i <= N; i++) {	// i = 4 -> 5 -> 6 -> 7 ...
    			a = b;			// a = 1    1    2    3
    			b = c;			// b = 1    2    3    5
    			c = a + b;		// c = 2    3    5    8
    		}
    		long end = System.currentTimeMillis();
    		
    		System.out.println("f_" + N + " = " + c + " and iteratively took " +
    			(end - start) + " milliseconds.");
    		
    		
    		start = System.currentTimeMillis();
    		c = fib(N);
    		end = System.currentTimeMillis();
    		
    		System.out.print("f_" + N + " = " + c + " and recursively took " +
    			(end - start) + " milliseconds.");
    	}
    	private static int fib(int n) {
    		if (n <= 3)
    			return 1;
    		return fib(n - 1) + fib (n - 2);
    	}
    }
    Output:
    Code:
    f_30 = 514229 and iteratively took 0 milliseconds.
    f_30 = 514229 and recursively took 16 milliseconds.
    
    f_40 = 63245986 and iteratively took 0 milliseconds.
    f_40 = 63245986 and recursively took 672 milliseconds.
    
    f_50 = -811192543 and iteratively took 0 milliseconds.     (longs obv. don't work well with big N)
    f_50 = -811192543 and recursively took 77359 milliseconds. (1 minute 17.359 seconds...)
    Last edited by Nim; September 25th, 2009 at 11:38 PM.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured