arrays after a while. remember for loops? for(int i = 0; i < 10; i++){ system.out.println(i); }...
TRANSCRIPT
ArraysAfter a while
Remember for loops?
for(int i = 0; i < 10; i++){System.out.println(i);
}
-But what if we are unsure of how many cycles we need?
1. declare and define a counter variable
2. boolean condition, checked every iteration
3. update counter variable every iteration
while loops
• Allow us to loop for an indeterminate amount of cycles• Example:
while(door.isLocked()){ringDoorBell();waitForResponse(10);
}
New Keywordboolean condition inside parentheses
Curly braces encompass code to be cycled over
Beware of infinite loops!
• If the boolean condition of a while loop is always true, the loop will never exit
• This is called an infinite loop and can be a really annoying bug to fix
• Used to cause computers to freeze, now OS’s are more robust
• Still bad news for your program
A Problem
• Until now, we have used variables that hold a single object/value• What if we want to hold lots of data?• Imagine trying to store the first 20 numbers of the Fibonacci sequence? int _firstNum;
int _secondNum; int _thirdNum;
...int _twentiethNum;
• This is annoying, and what about storing the first 1,000 or 1,000,000?
Arrays to the rescue!
• Arrays store a specified number of homogenous(same type) data elements (variables)• You can refer to a specific element by its index• Indexing starts at 0 and ends at the size of the array – 1• This is a visualization of an array of size 20:
Real life “arrays”
Array Syntax
• Declaration:
int[] fibNumbers;
• Definition pt. 1:
fibNumbers = new int[5];
Type of variable the array will hold
Square bracketsdenote array Array Name
Array size
Initializing Elements of the array
• Definition pt.2:
fibNumbers[0] = 1;fibNumbers[1] = 1;fibNumbers[2] = 2;fibNumbers[3] = 3;fibNumbers[4] = 5;
But wait a minute, this isn’t any better than before!
A Cleverer Way to Initialize
• Using a for loop to initialize the elements of an array is much better
• Let’s do this for the Fibonacci sequence