# Thread: adding integers of an array

1. Member
Join Date
May 2011
Posts
3
Rep Power
0

## adding integers of an array

Hi

I'm trying to write a simple program that takes an unlimited number of integers from the command line and then adds them together.

Thanks

2. Hi.
We happy for you. You did not point your problems or questions. :)

3. Cool, what have you tried? Are you getting errors? Have you started? If not, try erring somethig up and come here with any problems. If you get errors post the exact errors(no paraphrasing), if you post code use code tags.

[code]
YOUR CODE HERE
[/code]

4. For that project, you need to have a rough idea of how to handle arrays (the input frmo the command line is all sent as an array), make a for-loop to go through the array, and make use of the Integer-class to make them addable. Have a look at Integer (Java Platform SE 6) for the latter.

5. Member
Join Date
May 2011
Posts
3
Rep Power
0
public class one {

public static void main(String [] args){

int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int c = Integer.parseInt(args[2]);

int sum = 0;

for(int i=0; i < args.length; i++)
sum = a+b+c;
System.out.println(sum);
}
}

This is what I have written so far, however it has to take a fixed number of inputs from the command line. I'm not sure how to change this so that the user can enter an unlimited number of inputs.

6. You're actually very much on the right track. However: Why do you loop through the entire args[] array, when all you do in that loop is to add the three sums together?

7. You want to loop through the input array and keep a running total as you loop through.

8. Member
Join Date
May 2011
Posts
3
Rep Power
0
Hey got an answer:

public class one {

public static void main(String[] args) {

double sum = 0.0;

for (int i = 0; i < args.length; i++) {
sum += Integer.parseInt(args[i]);
}

System.out.println(sum);

}

}

Thanks very much for your help :)

9. That'd do the trick, yes. On a small side-note, I would personally change sum to type int instead of double though. You only ever add integers to it. after all.

10. Your welcome, please mark your thread solved with the thread tools at the top.

ps: you can safely make the sum into an integer here since you won't be dividing or anything, if you do division then you wanna switch sum to double.

#### Posting Permissions

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