Renuz
Renuz

Reputation: 1667

Does this program end in an infinite loop? How can I tell?

I run the program and all I see is white space below Netbeans.

At first I thought it did not run then I ran four of the programs by accident and Netbeans crashed. So my first question: is it an infinite loop, and if so why?

From what I can see it is int = 0, 0 is >=0 So it should run as 0 + 0... wait if int number and int sum are both zero then does that mean the program can't proceed because it is stuck with looping zeros? But why wouldn't it show the output of 0 many times instead of being blank?

public static void main(String[] args) {

    int number = 0;
    int sum = 0;
    while (number >= 0 || number <= 10) {
        sum += number;
        number += 3;
        System.out.print(" Sum is " + sum);
    }
 }

Upvotes: 2

Views: 1515

Answers (4)

Glen P
Glen P

Reputation: 709

You step through it in the debugger!!

It's worth learning how to use the debugger especially if you're not got at spotting bugs manually yet.

Upvotes: 0

Gapton
Gapton

Reputation: 2124

Yes it will be an infinite loop || means or

while (a || b) {
  //do something
}

you only need to satisfy ANY ONE CONDITION (be it a, or b, or both) for the while loop to execute.

As for why a bunch of whitespaces instead of a bunch of zeros, I have no idea.

Upvotes: 0

Mysticial
Mysticial

Reputation: 471567

Yes, it's an infinite loop, you probably meant:

while (number >= 0 && number <= 10)

Otherwise, the number will always be greater than or equal zero, and will always loop again.

EDIT:

The number >= 0 isn't even necessary. It will work with just:

while (number <= 10)

Upvotes: 4

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

Think through the logic yourself. When will the number ever not be greater than or equal to 0? You know you have an or operator (||), and you know that it will be true if either statement on the right or left are true. Maybe you want to use a different operator there?

Again think through the logic as it won't lie to you. In fact you should walk through your code with a pencil and paper starting with 0, and seeing what happens on paper as this will show you your error.

Upvotes: 6

Related Questions