Gemini Krishna
Gemini Krishna

Reputation: 21

Java: Unable to understand for loop behaviour

I am slightly new to coding, I am solving a problem which should print all the integers between variables L and R including L,R. but I am getting the required output repeatedly. I don't understand the reason for it.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int L = sc.nextInt();
        int R = sc.nextInt();

        for (int i = 0; ; i++) {
            if (i >= L && i <= R) {
                System.out.print(i + " ");
            }
        }
    }

Input: L=4 ,R=8

Output: 4 5 6 7 8 4 5 6 7 8 4 5 6 7 8 and so on...

Upvotes: 1

Views: 162

Answers (2)

Seshidhar G
Seshidhar G

Reputation: 265

If are new to coding then follow this link to understand how for loop works

And you are not defining any condition when for loop should stop executing the code block

for(int i = L; i <= R; i++) {
    System.out.print(i+" ");
}

This is how your for loop should be

Upvotes: 0

Eran
Eran

Reputation: 394146

You put the condition is the wrong place, so your loop is infinite.

To further explain, since your loop has no exit condition, i will be incremented forever, but after reaching Integer.MAX_VALUE, the next i++ will overflow, so i will become negative (Integer.MIN_VALUE). Then it will continue to increment until it reaches again the range you wish to print, so that range will be printed again and again, forever.

The correct loop should be:

for(int i = L; i <= R; i++) {
    System.out.print(i+" ");
}

Now i will start at the first value you wish to print (L), and the loop will terminate after printing the last value you wish to print (R).

Upvotes: 5

Related Questions