0

How can a get a sum of a loop?

Need the output to look exactly like this: Enter the upper limit: 500 1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 + 256 = 511 This is what I have so far what should I do: int limit, i = 1; long sum = 0; //Input System.out.print("Enter the upper limit:"); limit = input.nextInt(); //Setting up the math for(int I; i <= limit; i*=2) { System.out.print(i+"+");

8th Feb 2019, 11:40 PM
Gary Hu
Gary Hu - avatar
4 Réponses
0
Hi Gary, have you done any of the Java course on here. Lots of things that won't work in your code.
9th Feb 2019, 12:19 AM
Duncan
Duncan - avatar
0
I have not:(
9th Feb 2019, 12:24 AM
Gary Hu
Gary Hu - avatar
0
Just with some algorithmic mind you can solve your problem. This is a simple solution for your problem. for(int i=1; i<=limit; i*=2){ System.out.println(i + " +"); sum+=i; } System.out.println("= " + sum); https://code.sololearn.com/cY18P416AysJ
9th Feb 2019, 12:42 AM
Elghozi Nasreddine
Elghozi Nasreddine - avatar
0
Gary Hu I would strongly recommend you start with the course. As great as it is that Ghozzi Nassreddine has provided an excellent solution, you will get limited benefit just jumping in like you have.
9th Feb 2019, 4:38 AM
Duncan
Duncan - avatar