ArrayIteration Flashcards
What is the syntax for a while loop?
A while statement has the following syntax:
while(condition) {
statement(s);
}
● If the condition is true, the while loop executes the statement(s).
● Then the condition is evaluated again. If it is still true, the while loop executes the statement(s) again.
● This continues until the condition evaluates to false. If it’s never true, it never executes.
What is the syntax for a do while loop?
do {
statement(s);
} while(condition);
The statement(s) are executed once first and then the condition is evaluated.
● If the condition is true, the statement(s) are executed again.
● This continues until the condition is false.
● This is also often called a do loop.
What is the syntax for a for loop?
for(initialize; condition; modify) {
statement(s);
}
The initialization section can be used to declare a variable.
If a variable already exists, it can be left blank (;).
In fact, any of the parts of the for loop header may be left blank.
○ e.g. for(;;){}
● Like a while loop, the condition is tested before executing the statement(s) in the body.
○ If initially false, the statement(s) are never executed.
What is an array?
Fixed length data structure.
Data in the array is accessed via index.
Initialized with null or 0.
What is the for each loop?
To iterate over an array.
for(int i : numbers) {
System.out.println( i );
}
This kind of loop only works with iterable types, including arrays.
How do you initialize and access a 2-D Array?
int[][] table= new int[3][5];
int value = table[2][3];
How do you iterate through a 2-D Array?
Nested for loop.
for(int row=0; row<array.length; row++) {
for(int col=0; col<array[row].length; col++) {
System.out.print(array[row][col]);
}
}
One loop iterates over the rows, each
of which is an array of values…
…the nested loop iterates over each
column in the row.
Both indices are needed to retrieve a
value from the array.