From 3f6a61fbcad1da241268b9137ae67bd5d2ebeea1 Mon Sep 17 00:00:00 2001 From: SakshamGupta1995 <44345026+SakshamGupta1995@users.noreply.github.com> Date: Sun, 4 Nov 2018 01:21:23 +0530 Subject: [PATCH] Add the text article Infinite Loop to my article (#25516) * Add the text article Infinite Loop to my article The article "##Infinite Loop by opposite iteration##" gives an example to new java programmer as to how a program can go into infinite loop if we increment the value of i instead of decrementing it and vice-versa. It is a basic but an important example for new coders. * Update index.md * Add Infinite Loop by update This article will give new programmers the example of infinite loop when we increment the value instead of decrementing and vice-versa. * Fixed several formatting issues --- .../java/loops/infinite-loops/index.md | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/guide/english/java/loops/infinite-loops/index.md b/guide/english/java/loops/infinite-loops/index.md index 11e8656198..bd3f9aabd5 100644 --- a/guide/english/java/loops/infinite-loops/index.md +++ b/guide/english/java/loops/infinite-loops/index.md @@ -45,7 +45,30 @@ The loop above runs infinitely because every time i approaches 49, it is set to But a program stuck in such a loop will keep using computer resources indefinitely. This is undesirable, and is a type of 'run-time error'. -To prevent the error, programmers use a break statement to break out of the loop. The break executes only under a particular condition. Use of a selection statement like if-else ensures the same. + +#### Infinite Loop by opposite iteration +Another example of an Infinite Loop can be seen below: +```java +for(int i=0;i<=10;i--) + System.out.println(i); +``` + +In the above example, the initial value of `i` is 0. Since value of `i` is less than equal to 10, we decrement the value of `i` by 1, so `i` will now be -1. Hence, the loop will be infinite. + +Similarly, an example of an infinite while loop example can be seen below: + +```java +int i=1; +while(i>=1) +{ + System.out.println(i); + i+=1; +} +``` + +Here, `i` will always be greater than 1, so the program will be in an infinite loop. + +To prevent the error, programmers use a `break` statement to break out of the loop. The `break` executes only under a particular condition. Use of a selection statement like `if-else` ensures the same. ```java while (true) @@ -62,4 +85,3 @@ while (true) The main advantage of using an infinite loop over a regular loop is readability. Sometimes, the body of a loop is easier to understand if the loop ends in the middle, and not at the end/beginning. In such a situation, an infinite loop will be a better choice. -