-
Do While Loop
Hi,
I am new to Java and would appreciate it if someone could me with the following:
Write a do while loop so it calculates: 1; 1+2; 1+2+3; 1+2+3+4; 1+2+3+4+5.
At the moment, I have done a basic do while loop for displaying 1 to 5.
public static void main(String[] args){
int i =1;
do
{
System.out.println(+ i);
i++;
}while(i <=5);
}
}
Thanks!
-
Declare an int variable (I'd call it "sum") before the do-while loop and add i to the sum value inside of the loop.
-
So yeah, code tags, read about them :D
As per your question, I'm a bit confused, do you want to calculate the sum of 1, 1+2, 1+2+3, or do you want to print out the expression without calculating? If all you want to do is the sum, you were pretty well on your way, not much else needs to be done to your code.