Home > database >  What is the reason for these two for loop acting differently?
What is the reason for these two for loop acting differently?

Time:05-11

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

    }
}

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

In your second snippet of code

for(int start = scan.nextInt();start<=(start 10);start  )
{
    System.out.println(start);
}

You're comparing start to itself plus 10. Regardless what operation you're going to perform, nothing can't be equals to itself plus 10. start will always be lower than itself plus 10 and therefore producing an infinite loop. It's a semantic error. You should use a different variable to keep track of the loop, as you did in your first snippet, and a second one for the confrontation (start in your case).

  • Related