Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 loops 1 decremented variable

I have an assignment that calls for an input integer, it then decrements that integer all the way down to 1.

it must use a while loop to display that number all the way down to 1 and on another line use a for loop to do the same.

Now after I initiated the while loop, my output for the for loop does not display. Obviously because startNum is now set to 0 after the while loop.

How can I get around this so that I can display the decremented numbers on both lines? Code I currently have:

public class CountDown 
{

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int startNum = input.nextInt();

        System.out.println("WHILE LOOP: ");

        while (startNum > 0)
        {
            System.out.print(startNum + " ");
            startNum--;
        }

        System.out.println("\nFOR LOOP:");

        for (int x = 0; x < startNum; x++)
        {
            System.out.print(startNum + " ");

        }

    }

}
like image 570
ihaveacode Avatar asked Aug 13 '26 17:08

ihaveacode


1 Answers

Have another variable to reset startNum back to its original value, right before the for loop

// ...
int startNum = input.nextInt(); 
int reset = startNum;
// ...
startNum = reset;
for (int x = 0; x < startNum; x++)
// ...
like image 183
nem035 Avatar answered Aug 15 '26 06:08

nem035



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!