Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: AddEmUp

  1. #1
    Junior Member
    Join Date
    Jun 2010
    Posts
    24
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Exclamation AddEmUp

    Alright guys and girls got a new one I need a lil help with. Im currently writing a program that is supposed to add the elements in a array and return the sum. Its supposed to be a recursive method to. So heres how far I got.

     System.out.println("Hello User");
            System.out.println("How many numbers would you like to enter?");
            Scanner input=new Scanner(System.in);
           int amountofNumbers= input.nextInt();
           if(amountofNumbers>1)
           {
            System.out.println("Very Well then. "+amountofNumbers+" numbers it will be.");
              Scanner keyboard=new Scanner(System.in);
            System.out.println("Enter "+amountofNumbers+" numbers");
             int[] Array =new int [amountofNumbers];
           for(int index=0; index<amountofNumbers; index++)
           {
             Array[index]=keyboard.nextInt();
           }
           }
           else
           {
               System.out.print("I need atleast one number in the list! come on help me out here.");
           }
     
        }
       public static int addElements(int amountofNumbers)
       {
          return 0;
       }
    }

    Now its all about the method addElements and how Im going to make it work. Any Suggestions??
    btw the only reason return 0 is there is to stop the error it would caused if it wasnt there.
    Last edited by helloworld922; July 10th, 2010 at 09:46 PM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: AddEmUp

    add the elements in a array and return the sum. Its supposed to be a recursive method
    Are you sure above the recursive requirement? That's not a normal requirement for processing arrays.

    For ease of testing the code, use a hardcoded array to get the logic of the method worked out, then copy the working method into the main program. You can define an array with numbers in it by:

    int[] anArray = new int[] {2, 3, 4, 5, 6}; // define an array of int for testing

    The Scanner input requirement just makes it hard to test the method and get it working.

  3. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: AddEmUp

    Recursion is just simplify the problem until it becomes trivial.

    So first you need to identify a trivial problem that can easily be solved, say an array with 0 elements. If you have nothing to add, the result is by default 0.

    Next, if you don't have the trivial answer, you need to reduce the problem until it is trivial. In this case, you can reduce the problem by summing the element at the start of the array with the solution to the sum of the rest of the array.
    sum = array[0] + sumOfArray(array.subArray(1,array.length);

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: AddEmUp

    Where is the subArray() method defined? I can't find it in my API doc.

    If there isn't one, how will a poor student figure out how to create a sub array?

  5. The Following User Says Thank You to Norm For This Useful Post:

    Delstateprogramer (July 11th, 2010)

  6. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: AddEmUp

    It's pseudo code Yeah, subArray isn't really defined but there are several ways to create the method (or a similar one which doesn't re-allocate a new array each call).

  7. The Following User Says Thank You to helloworld922 For This Useful Post:

    Delstateprogramer (July 11th, 2010)

  8. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: AddEmUp

    Ok, to do recursion you need at least 2 methods. 1 method to begin the recursion, and 1 method to do the recursion. The 1st method will simply call the 2nd method with the starting case. The 2nd method will continuity call itself and send itself different data until an exit case is met.

    Ok, so we know to stop when we reach the end of our array. But, we dont know for sure when the end of the array is met. So, like you coded, we need to send the length of the array. BUT, we also need access to the Array so we can get the numbers, which we currently dont have due to scope. So there are two options. 1, make the array static and declare it outside your main but construct it inside your main. 2, send it with the method. Regardless of your choice, it makes it sort of pointless to send it the amountofNumbers variable since we can get that from the array.

    So, I'll show you the code for the 2nd since that is probably the easiest because of your setup.

    public static int runProcess(int[] arr)
    {
         //Call our recursive method and send it the array and our starting case, 0
         return addElements(arr,0);
    }
    public static int addElements(int[] arr, int count)
    {
         //Get the number in the position in our array
         int tempNum = arr[count];
         //Check to see if the current number is the last number in the array. arr.length-1 is used 
         //because the array starts at 0
         if(count==arr.length-1)
         {
              //This is the last element, return it the previous addElements call
              return tempNum;
         }
         //Add our number and call the next addElements method. Remember to increase count by 1 
         //so we progress through the array.
         return tempNum + addElements(arr,count++);
    }

    I havent tested the code, but it should work.

    So, what is happening here? Lets use Norm's array to explain since it is not that big.

    Here is our array: int[] anArray = new int[] {2, 3, 4, 5, 6};

    With our call to runProcess(anArray); we start the recursion. This method will call addElement. addElement will determine tempNum = 2 (our first number). The current count = 0, this is not equal to 4 (arr.length-1) so it ignores the if statement. Now we return our number (2) added to a call to addElement and we send it arr and 1.
    **Remember, the first addElement is still running until it gets the results from our new addElement call in order to add the numbers and return the value to runProcess.**
    So our addElement runs with its new parameters. TempNum = 3. Count = 1. Ignore the if statement. Return 3 + addElement(arr,2).
    addElement(arr,2) runs with its new parameters. TempNum = 4. Count = 2. Ignore the if statement. Return 4 + addElement(arr,3).
    addElement(arr,3) runs with its new parameters. TempNum = 5. Count = 3. Ignore the if statement. Return 5 + addElement(arr,4).
    addelement(arr,4) runs with its new parameters. TempNum = 6. Count = 4. Hey, 4 does equal 4, so we use the if statement. We return 6. But where to? Well, we return it to our previous addElement call, addElement(arr,3).
    So, back to addElement(arr,3). Now we can return our value. So, we return 5 + 6. And we return it to our previous addElement call.
    So, back to addElement(arr,2). Now we can return our value. So, we return 4 + 11. And we return it to our previous addElement call.
    So, back to addElement(arr,1). Now we can return our value. So, we return 3 + 15. And we return it to our previous addElement call.
    So, back to addElement(arr,0). Now we can return our value. So, we return 2 + 18. But, this is our original addElement call, so we return it to runProcess.
    runProcess now returns 20 to our main, which is the correct answer.


    Recursion is something that is very difficult to wrap your mind around when you first use it.That is why I tried to provide you with exactly what is happening. If you have any questions, ask and I'll see what I can answer.

  9. The Following User Says Thank You to aussiemcgr For This Useful Post:

    Delstateprogramer (July 11th, 2010)

  10. #7
    Junior Member
    Join Date
    Jun 2010
    Posts
    24
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: AddEmUp

    hey i tried it.. maybe i invoked the method at the wrong point. there is an infinite recursion some where. Heres the code
     public static void main(String[] args) {
            System.out.println("Hello User");
            System.out.println("How many numbers would you like to enter?");
            Scanner input=new Scanner(System.in);
           int amountofNumbers= input.nextInt();
           if(amountofNumbers>1)
           {
            System.out.println("Very Well then. "+amountofNumbers+" numbers it will be.");
              Scanner keyboard=new Scanner(System.in);
            System.out.println("Enter "+amountofNumbers+" numbers");
             int[] Array =new int [amountofNumbers];
           for(int index=0; index<amountofNumbers; index++)
           {
             Array[index]=keyboard.nextInt();
           }
           runProcess( Array);
           addElements(Array,0);
           }
           else
           {
               System.out.print("I need atleast one number in the list! come on help me out here.");
           }
     
        }
       public static int runProcess(int[]Array)
       {
          return addElements(Array,0);
       }
       public static int addElements(int[]Array, int count)
       {
           int tempNum=Array[count];
           if(count==Array.length-1)
           {
               return tempNum;
     
           }
           else {
               return tempNum+addElements(Array, count++);
           }
       }
    }
    Last edited by helloworld922; July 14th, 2010 at 06:52 PM.

  11. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: AddEmUp

    I'll have a look at work. It may be because you named the Array "Array" (because thats a reserved word I think), but I'll have a look.

    Also, remove your call to addElements(Array, 0) from your main. We make that call in runProcess.

  12. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: AddEmUp

    And also please put your code in code tags to keep formatting. Left adjusted code is hard to read.

  13. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: AddEmUp

    Here is what it should be:
    import java.util.*;
     
    public class Test
    {
     
        public static void main(String[] args)
        {
    		System.out.println("Hello User");
    		System.out.println("How many numbers would you like to enter?");
    		Scanner input=new Scanner(System.in);
    		int amountofNumbers= input.nextInt();
    		if(amountofNumbers>1)
    		{
    			System.out.println("Very Well then. "+amountofNumbers+" numbers it will be.");
    			Scanner keyboard=new Scanner(System.in);
    			System.out.println("Enter "+amountofNumbers+" numbers");
    			int[] Array =new int [amountofNumbers];
    			for(int index=0; index<amountofNumbers; index++)
    			{
    				Array[index]=keyboard.nextInt();
    			}
    			System.out.println(runProcess( Array));
    		}
    		else
    		{
    			System.out.print("I need atleast one number in the list! come on help me out here.");
    		}
     
    	}
    	public static int runProcess(int[]Array)
    	{
    		return addElements(Array,0);
    	}
    	public static int addElements(int[]Array, int count)
    	{
    		int tempNum=Array[count];
    		if(count==Array.length-1)
    		{
    			return tempNum;
    		}
    			return tempNum+addElements(Array, count+1);
    	}
    }

  14. #11
    Junior Member
    Join Date
    Jun 2010
    Posts
    24
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: AddEmUp

    ok thx ill try that

  15. #12
    Junior Member
    Join Date
    Jun 2010
    Posts
    24
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: AddEmUp

    it worked thx alot man