ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Source code: How to Add numbers inside an Array Using Recursion

Updated on October 31, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

Add numbers inside An Array

The following codes is a Java source code on adding numbers inside the array. This is just a short program and also a very simple one to illustrate how an array works in Java programming language. I will also upload the code that uses for loop so that you can compare source codes on which you prepare the most, though in my own opinion I prepare looping in for loop but for the sake of knowledge lets learn another looping mechanism which is recursion. Here is the codes,

Java Source code: How to Add Numbers inside an Array Using Recursion

//Java source codes on adding numbers inside the array using recursion

//java class

public class Array
{
    public static int array( int[] arr, int first, int last)
    {
      //  int sum = 0;
        if(arr[first] == arr[last])/* must be if(first == last),but try this one too, study the code, it is interesting */
        {
           return arr[first];
        }
        else
        {  
           return arr[first] + array(arr, first+1, last);
             
        }
       
    }
   

}

//main class


import java.util.Scanner;

public class Main
{

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the size of the input you want to enter: ");
        int size = input.nextInt();
        int[] numArr = new int[size];

        System.out.print("Enter "+ size +" numbers: ");
        for(int i=0; i<numArr.length; i++)
        {
          numArr[i]=input.nextInt();
        }

        System.out.print("The sum of the numbers is: "+   Array.array(numArr, 0 , size-1) );
            

    }
}

Sample Output

Enter the size of the input you want to enter: 5

Enter 5 numbers: 3 46 50 34 150

The sum of the numbers is: 283


Since, I used static on my java method, I did not declare an object to call the class Array on the main class to access the method, simply code it on that way and it will run.

Comments

    0 of 8192 characters used
    Post Comment
    • profile image

      Johnf622 

      5 years ago

      Just wanna input on few general things, The website pattern is perfect, the subject material is real excellent. Believe those who are seeking the truth. Doubt those who find it. by Andre Gide. bgdfagcedeea

    • profile image

      Mackel Kroj 

      6 years ago

      Dear Aisha, you can get solve this issue with out development team i am giving you link of for you help for our developers.

      http://www.imensosoftware.com/

    • aisha91 profile imageAUTHOR

      Rasna Aisha 

      7 years ago from Manila, Philippines

      @ John

      Thanks for stopping by, I will check it out :)

      @dwachira

      Nah, lols, no, I am just a wannabe programmer. But well, I wish I could teach in the future, thanks for voting it up, sharing and rating it dwachira. ;)

    • dwachira profile image

      [ Danson Wachira ] 

      7 years ago from Nairobi, Kenya

      Mastering how to work with loops and arrays is a must for the would be programmers. I'm glad you shared these basics here. By the way, could you be teaching Java? Just curious. Voted up, useful and shared.

    • aisha91 profile imageAUTHOR

      Rasna Aisha 

      7 years ago from Manila, Philippines

      Hi CovexLy,

      You're right actually, the base case should be like that.

      But I suggest that you please try the codes above, try to enter numbers that the first index and the last index are the same,it will give you the right answer as if the algorithm is correct.

      Nah, recursion is really interesting, I entered the numbers you have given above and the program answers 87 which is right and another group of numbers.

      1 2 3 2 1

      The program answers 9.

      Though I overlooked that if statement, but this is fun, hope you'll share you expertise, please do reply back...

      For other java programmers, you may want to participate in this and give your ideas, that would be really highly appreciated.

      By the way, Thank you covexly for stopping here and commenting...:)

    • profile image

      CovexLy 

      7 years ago

      Hey, i was looking through this and i found an error(?) in the code.

      Doesn't this:

      if(arr[first] == arr[last])

      screw up if you for example choose: 15 22 35 15

      whereas the first and the last number is the same?

      Or in any case where the last number is the same as any other number.

      I believe it oughta be something like:

      if(first == last)

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)