Reputation: 21
Hi can anyone help me with this?
First block of codes gives the output as intended. But second one goes for infinite loop. What is the reason?
Thank you.
1.
import java.util.Scanner;
class Numbers
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a starting number: ")
int start = scan.nextInt();
for(int a = start;a<=(start+10);a++)
{
System.out.println(a);
}
}
}
2.
import java.util.Scanner;
class Numbers
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a starting number: ")
for(int start = scan.nextInt();start<=(start+10);start++)
{
System.out.println(start);
}
}
}
Upvotes: 1
Views: 87
Reputation: 7130
In your second snippet, you have a semantic error, since you're comparing start
to itself plus 10
.
for(int start = scan.nextInt();
start <= (start + 10);
start++)
Regardless of what you perform in a loop, a variable is always equal or lower than itself plus 10
, hence the conceptually infinite loop. In reality, just a really long loop until start + 10
overflows to Integer.MIN_VALUE
, turning the condition to false
.
To fix your code, you should use a different variable to keep track of the loop iteration (as you did in the first snippet), leaving start
unmodified and just for confrontation to terminate the loop.
Upvotes: 1
Reputation: 123
In the first block, start
is a constant variable which has fixed value and the condition is between a
and start
(a
keeps increasing a++
and start
won't change its value).
While in second block, the condition is between start
and start+10
, but start
keeps increasing with start++
in the loop function, which makes the loop is infinite (start
keeps changing its value so start<=(start+10)
is always true).
Upvotes: 2
Reputation: 26763
This for(int start = scan.nextInt();start<=(start+10);start++)
compares the changing variable to a changing value, which keeps the same distance ahead.
I.e. the value of start
will always be lower than start+10
, what you get is at first an endless loop. It can only terminate when values get so high that they cannot be represented anymore an strange things occur. At that point start+10
might appear to be lower than 0 for example and hence seem also lower than start
which not yet is past that weird border.
Upvotes: 2