Have you ever had to do the dishes? Yeah, me too. The repetition: dish after dish, wash, scrub, rinse, repeat. Well, now you know what a repetition statement is! Yeah, it's that easy. Think about it; all you did was create a series of commands; wash, clean, and rinse; and repeat them while there are still dishes remaining. That is the fundamental of any repetition statement or loop, in any programming language in the world. Woah Woah... let's not get ahead of ourselves; there's still some syntax to learn!
There are four forms of loops that you need to know about for the AP Exam: for loops, for-each loops, while, and do-while loops.
Here is a basic rundown of "each" time of loop (get the pun?):
For Loops(The one you will probably use the most):
This type of loop will be mostly used to track the number of repetitions that have occurred.
Syntax:
for(initialization;condition;incrementaion)
{
//enter code to be repeated here
}
Note: The initialization and incrementation condition are not required, only the conditional
So, this would be acceptable:
int x = 0;
for(;x<50;)
{
System.out.println(x); //prints numbers from 0-49
x++;
}
Example:
for(int x = 0;x<50;x++)
{
System.out.println(x); //prints numbers from 0-49
}
Note: The break command can be used within the loop to exit the loop at any time and the continue command can be used to stop the current iteration and goes back to the conditional to repeat the loop once again.
For each Loops (used for arrays):
Syntax:
for(dataType x: array)
{
//enter code that directly access the element itself within the array, not the index
}
Example:
int[] a = [0,0,0];
for(int i: arr)
{
System.out.println(i); //prints the values in the array
}
While Loops(Used usually if conditional is a boolean expression does not regard integer bounds)
Syntax:
int x = 0;
while(conditional expression)
{
//enter code here, usually want to change some value that changes above boolean expression to avoid infinite loops
}
Example:
int x = 0;
while(x<50)
{
System.out.println(x); //prints numbers from 0-49
x++;
}
Do While Loops(Used if you need the statements to run at least one time, regardless of the conditions)
Note: The main difference between other loops, is that this loop will run at least once, regardless of the conditional expression
Syntax:
do {
// enter code to repeat here
}while(conditional statement);
Example:
int x = 0;
do {
System.out.println(x); //prints numbers from 0-49
}while(x<50);
It's really not that bad once you start to code loops! You can find practice problems online for loops in Java if needed. But this should be the basic summary of loops, as far as the AP exam is concerned.
I hope it helps and happy coding/cramming! Until next time.
Kommentare