Home / Programs / Program with Off-by-One Error
🚀 Programming Example

Program with Off-by-One Error

👁 0 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

💻 Program Code

public class OffByOneErrorExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        for (int i = 0; i <= numbers.length; i++) {
            System.out.println(numbers[i]);
        }
    }
}
                        

📘 Explanation

What is the error here?

The problem is this line:

  
i <=numbers . length

Array index starts from 0 and ends at numbers.length - 1.

For this array:

  
{10, 20, 30, 40, 50}

Valid indexes are:

  
0, 1, 2, 3, 4

But when i becomes 5, the program tries to access:

  
numbers[5]

That does not exist, so Java gives:

  
ArrayIndexOutOfBoundsException

Correct Program

public class OffByOneErrorFixed {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }
    }
}
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.