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