1

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

2
  • 1
    Please format your code properly. Also, why did you paste the class Main twice? Commented Dec 30, 2019 at 11:50
  • sorry I am new here editing the code right now Commented Dec 30, 2019 at 11:51

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

But why does it print 4 5 6 7 8 again and again when I put i++ there? shouldn't 8 change to 9 due to i++?
@GeminiKrishna did you read the paragraph I added in my edit?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.