Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Java 

Need help with this Loop and 2 more situations.

Here's the code we were given for this class assignment.


Code:


package lab04a;

/** A program to sum the numbers from 1 to 10.
Also to sum their squares.
@author Mark Young (A00000000) /
public class SumIntegers {

   public static final int MAX = 10;

   public static void main(String[] args) {
       // create required variables
       int sum;
       
       // print sum of numbers from 1 to 10
       sum = 0;
       System.out.print("I'm adding up the numbers: ");
       for (int i = 1; i <= MAX; ++i) {
           System.out.print(i + " ");
           sum += i;
       }
       System.out.println(".\n"
               + "The sum of the integers from 1 to " + MAX
               + " is " + sum);
               
       // print sum of squares from 1 to 10
   }
   
}

Note: We are using Netbeans

Here's the instructions we were given to do:

It presently prints the sum of the integers from 1 to 10. Add another loop (after the first) so that it also so that it sums the squares of the integers from 1 to 10. (That is, it sums 1, 4, 9, 16, ..., 100 -- which should come out to 385.)

"I'm adding up the numbers: 1 2 3 4 5 6 7 8 9 10 .
The sum of the integers from 1 to 10 is 55
I'm adding up the numbers: 1 4 9 16 25 36 49 64 81 100 .
The sum of the squares from 1 to 10 is 385"

There are 2 more Activities to do with this project I need help as this is due 12am Today.


Figured out this problem! If you want the answer its:

public class SumIntegers {

   public static final int MAX = 10;

   public static void main(String[] args) {
       // create required variables
       int sum;

       // print sum of numbers from 1 to 10
       sum = 0;
       System.out.print("I'm adding up the numbers: ");
       for (int i = 1; i <= MAX; ++i) {
           System.out.print(i + " ");
           sum += i;
       }
       System.out.println(".\n"
               + "The sum of the integers from 1 to " + MAX
               + " is " + sum);

       // print sum of squares from 1 to 10
       sum = 0;
       System.out.print("I'm adding up the numbers: ");
       for (int i = 1; i <= MAX; ++i) {
           System.out.print(i
i + " ");
           sum += i * i;
       }
       System.out.println(".\n"
               + "The sum of the integers from 1 to " + MAX
               + " is " + sum);
       // print sum of squares from 1 to 10
   }
Yes that is correct, went and completed it just to see you edited your post lmaooo.

What are the 2 other additions to this? Post them or PM me.
[Image: wKo4TU0.gif]


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Java] by ohxerxeFeb 4, 2018 03:26 PM 3 306 Feb 4, 2018 03:26 PM
Last Post: matt
[Java] by SUI-3183372Oct 21, 2017 02:42 AM 7 421 Oct 21, 2017 02:42 AM
Last Post: ☕⚛Austin⚛☕
[Java] by prodigyhfSep 1, 2017 05:22 PM 0 223 Sep 1, 2017 05:22 PM
Last Post: prodigyhf