This loop cycles through again and again, while the condition is considered true.
It’s similar to the if statement.
If the condition is false then the loop will continue to run, until the condition returns true.
However, if the condition is true then it will execute the statement, and it will exit the loop, and if there is another condition present then that will start running instead.
However, sometimes loops aren’t well written, because sometimes there might not be any sort of statements that go through the loop to help change the value of the expression to be true.
This would be considered an infinite loop, which, as its name suggests, means that the loop goes on forever.
It has the similar feeling of TikTok freezing on you when you're on your daily Tiktok spiral.
So an infinite loop isn’t desirable in all situations.
Note: On the AP Exam, you need to be able to trace code in multiple-choice questions and detect infinite loops. In the free-response questions, you need to write code that is free of infinite loops.
All loops are dependent on the conditions that are found within them.
If there are multiple conditions found in the loop when can use boolean operators to simplify it. (View Chapter 5 for a review of boolean operators)
Let’s look at our paintbrush example again.
In this case, you would end up using the && (and) boolean operator, because while the paintbrush is both wet and dirty, then only will the paintbrushes be put away.
So if the paintbrush is dirty and wet then don’t put away the paintbrush, otherwise, put away the paintbrush.
for(int num = 1; num <= 22; num++)
System.out.println(num);
//Explanation: The loop above will show every number and the output on the screen on separate lines.
for( int num = 1; num <= 3; num++)
System.out.println(num);
System.out.println(“Done”);
//Explanation: The example above shows that num starts at the value of 1, and as long as the number is less than or equal to 3 the for loop will continue to execute. When the for loop executes it prints the value of num. Each time you go through the loop, the value of num increases by 1. Once the value of num hits 4, it will exit the for loop, and print done instead.
Concepts covered on the AP CSA Exam | Concepts not on the AP CSA Exam | |
---|---|---|
Primitives | int, double, boolean | short,long,byte,char,float |
Increment/Decrement Operators | x++,x-- | ++x,- - x |
Logical Operators | ==,!=, | &,|,^,< |
Conditional Statements | *if/else,****for,***while | *switch,****break,***continue, do/while |
Miscellaneous | ?:(ternary operator)User inputJavaDoc comments |
\