I'm trying to write the same loop to calculate the sum of the integers from 1 to the input value, and output the sum 3 different ways, and so far I've completed my for and while loops correctly, and had them output the same result. However, for some reason my do-while loop isn't working properly, and instead of adding the sum of all the numbers together, it just adds one to the user input. Can anyone help me figure out how to get it to copy the process of my other loops correctly? Attached is my code.
import java.util.Scanner;
public class CountLoop{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int total = 0;
int total2 = 0;
int total3 = 0;
int n = 0;
System.out.println("Please input a positive integer");
int input = sc.nextInt();
System.out.println("while loop:");
while(n<=input){
total = n;
n ;
System.out.println(total);
}
System.out.println(" ");
System.out.println("for loop:");
for(n = 0; n <= input; n ){
total2 = n;
System.out.println(total2);
}
System.out.println(" ");
System.out.println("do while loop:");
do {
total3 = n;
n ;
System.out.println(total3);
} while(n<=input);
}
}
CodePudding user response:
Before your "do... while()", you have to set n to 0, otherwise n is equal to the number entered plus one. If you do so, you will have the same answer.
System.out.println("do while loop:");
n = 0;
do {
total3 = n;
n ;
System.out.println(total3);
} while(n<=input);
Tip : avoid when possible to use a variable is several places and have long living variables (especially when they are mutable).
The for (n=0; n<input; n )
could be replace with for (int i=0; i<input; i )
for example, which avoid using an existing variable and avoid complex state.
CodePudding user response:
Between the for loop and the do while loop you didn't reset the value of n. It is still equal to input because of the for loop