programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Another beginner problem...

Greenhorn
Posts: 13
• Number of slices to send:
Optional 'thank-you' note:
So...here's the exercise I'm working on:

Write a program that adds up integers that the user enters. First the programs asks how many numbers will be added up. Then the program prompts the user for each number. Finally it prints the sum.

How many integers will be added:
5
Enter an integer:
3
Enter an integer:
4
Enter an integer:
-4
Enter an integer:
-3
Enter an integer:
7

The sum is 7

Be careful not to add the number of integers (in the example, 5) into the sum.

This is what I've come up with so far:

My issue is trying to figure out how to store, then add the integers that are input by the user.

I know this is very basic, and maybe it's because I've been working all day and trying to figure this out afterwards and my brain is fried, but I just can't seem to get the logic down.

I promise, one day I'll get this stuff down and can actually contribute help instead of asking for it.

Greenhorn
Posts: 12
• Number of slices to send:
Optional 'thank-you' note:
int total = 0;

total = total + num;

System.out.println("Total is " + total);

I'll leave it to you to insert the code in your program.
Cheers
Robert

Ranch Hand
Posts: 255
• Number of slices to send:
Optional 'thank-you' note:

int sum;

give num an initial value, like this

int sum = 0;

sum = sum + num;

That takes the current value of sum, adds the value of num, and makes that total number to be the value of sum.
So if you have the numbers 2,4, and 6, sum changes like this:

sum = 0;
sum = 0 + 2;
sum = 2 + 4;
sum = 6 + 6;

Then later, you want to calculate the average, which means you divide by the number of integers entered, so just make sure you don't make the computer divide by 0.

Tod Novak
Greenhorn
Posts: 13
• Number of slices to send:
Optional 'thank-you' note:
Thank you both for the help. Just needed a push in the right direction.

Appreciate it!

Edit: I've made the suggested changes and all is working as intended.

Thanks again
[ May 21, 2008: Message edited by: Tod Novak ]

Marshal
Posts: 79412
377
• Number of slices to send:
Optional 'thank-you' note: