7️⃣

8.7 Infinite Loop

Chapter Table of Contents

Ch. 8 Loops

Section Table of Contents

 
Beware! If you set your conditions in your loops such that they never become false, you will end up with an infinite loop and your program may crash. For example, this is an infinite loop which prints 3 infinitely:
int i = 3; // infinite Loop! while (i > 0) { System.out.println(i); }
 
Here’s how you fix the code above: You need to make sure you change your control variables! The following code prints 3, 2, and 1 on their own lines.
int i = 3; // infinite Loop! while (i > 0) { System.out.println(i); i--; }
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.