Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java [Java] Did I write this program correctly? Please check

  1. Apr 6, 2015 #1
    Write a Java program to find the sum of all numbers between 1 to 10.

    So we all know that 1+2+3+4+5+6+7+8+9+10=55 and that answer to this problem is 55. Please check my work below:

    Code (Java):
    public class Standard
           public static void main(String[] args)
                    // Create a for loop.
                    for (int x=1; x<=10; x=x+1)
                          // Print result.
                          System.out.println("Sum of numbers from 1 to 10 is" x=x+1);
    Did I wrote this program correctly? If not, then please correct me. Thanks.
    Last edited by a moderator: Apr 9, 2015
  2. jcsd
  3. Apr 6, 2015 #2
    Have you actually tried it?, that's the only real test.
    It doesn't look right to me though.
    My experience is in C type languages, not Java, but it looks like this will simply loop 10 times and give you a number on each pass.
    'x' is your loop counter variable, you have no other variable in which the final result is being computed.
  4. Apr 6, 2015 #3
    I tried it and it didn't work. Like you said, it looped 10 times like this:

    Sum of numbers from 1 to 10 is
    Sum of numbers from 1 to 10 is
    '' "
    " "
    For 10 times.
  5. Apr 6, 2015 #4
    Yeah, I was wondering if it would even print a number.
    I'm not going to do this for you but the general idea is that you need another variable, 't', I guess, for total will do.
    Start that variable at zero and add the value of x to it each time you go the through the loop.
    When the loop has been completed, then you print the value of t.
    That should be enough to get you going in the right direction.
  6. Apr 6, 2015 #5


    Staff: Mentor

    To add to what rootone said, before you post questions like this, run your program and see what it produces. If it doesn't run for some reason, tell us about that, including error messages.
  7. Apr 9, 2015 #6
    Whoops, moved it down one too many, thanks rootone.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook