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

  • Java
  • Thread starter Math10
  • Start date
  • #1
301
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:

Answers and Replies

  • #2
3,388
944
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.
 
  • #3
301
0
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.
 
  • #4
3,388
944
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.
 
  • #5
35,227
7,048
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.
 
  • #6
Whoops, moved it down one too many, thanks rootone.
 

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

Replies
6
Views
3K
Replies
6
Views
3K
V
  • Last Post
Replies
4
Views
19K
  • Last Post
Replies
11
Views
86K
Replies
2
Views
6K
  • Last Post
Replies
18
Views
6K
  • Last Post
Replies
7
Views
19K
Replies
4
Views
2K
Replies
7
Views
1K
Top