Solved

array sum

Posted on 2015-02-12
3
88 Views
Last Modified: 2015-02-12
Hi,

I am workjing on below challenge

http://codingbat.com/prob/p175763

i wrote as below and passed all tests.

public int sum3(int[] nums) {
int num1=nums[0];
int num2=nums[1];
int num3=nums[2];

return num1+num2+num3;
  
}

Open in new window


i wonder how to improve my code. please advise
0
Comment
Question by:gudii9
  • 2
3 Comments
 
LVL 84

Accepted Solution

by:
ozo earned 400 total points
ID: 40606565
Not an improvement in this case, but if you wanted it to work regardless of the length, you might use something like

  int sum=0;
  for( int n : nums ){
    sum += n;
  }
  return sum;

Or in the length 3 case, you could do it without the variables
  return nums[0]+nums[1]+nums[2];
0
 
LVL 14

Assisted Solution

by:Geisrud
Geisrud earned 100 total points
ID: 40606607
In support of Ozo's comment, when writing a program (even a simple one such as this) always consider how you could re-use your code and how does it scale to other/larger projects.

Your code is great for only this situation, adding arrays of three integers.  If there were four, then you have to rewrite.  Next week there will be five, and another rewrite.  Maybe there's a thousand integers in the array, or a million!  Do you want to hardcode all of those integers?  No.

With Ozo's simple and elegant solution, you can reuse the same snippet of code for any size array.

Points should go to Ozo, doesn't get better than what we provided.
0
 
LVL 14

Expert Comment

by:Geisrud
ID: 40606641
correction - that should say what HE provided.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
mapAB Challlenge 35 124
groovy example issue 10 89
egit plugin on eclipse 8 31
tomcat not starting 6 26
Navigation is an important part of web design from a usability perspective. But it is often a pain when it comes to a developer’s perspective. By navigation, it often means menuing. This is less theory and more practical of how to get a specific gro…
This article will show, step by step, how to integrate R code into a R Sweave document
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This video teaches viewers about errors in exception handling.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now