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

  • Context: Java 
  • Thread starter Thread starter Math10
  • Start date Start date
  • Tags Tags
    Java Program
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 2K views
Math10
Messages
301
Reaction score
0
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:

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:
on Phys.org
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.
 
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.
 
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.
 
Math10 said:
Did I wrote this program correctly? If not, then please correct me. Thanks.
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.
 
Whoops, moved it down one too many, thanks rootone.