Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my do-while loop not producing the same results as my for & while loops?

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);

    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading