I just need to know a simpler way to do the code. I did a basic System.out.println(1 + 2); add on the next number 5 times and got the solution correct. But I know that I am doing more work than needed. Please explain how to use a better way. I read about loops? can someone explain?
Can someone show me a more simple way to do this?
Under discussion
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Stephen Engelhardt
18 October 2021, 08:10
Some of the other suggestions might be a little cleaner, but I figured I'd share my loop as well. I think we'll learn a little more about these later, but I gleaned a little info just from examples used earlier in the course.
0
J H U X
11 January 2021, 08:42
Hail to the people that want to do less work than needed! Write a for loop:
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + i;
System.out.println(sum);
}
Make sure you place the {} in the correct place, otherwise your will get errors. Good luck!
+1
Vivek
28 July 2020, 17:15
Bro, only for you , I did all the hard work only for you !
System.out.println(1);
System.out.println(3);
System.out.println(6);
System.out.println(10);
System.out.println(15);
and surprisingly enough this works! to your astonishment !
+4
Gazi Farhad Ahmad Suza
9 January 2020, 03:38
You can do this by using a loop.
in main method you can write the following code
int sum = 0;
for(int i = 1; i <= 5; i++){
sum = sum+i;
System.out.println(sum);
}
+2
Nyerges Ferenc
20 December 2019, 18:37useful
Yes a for loop is what you're looking for, will be explained in few lessons later.
Even later, you might as well do it using a collection.
+2