Download presentation
Presentation is loading. Please wait.
Published byElisabeth Neal Modified over 9 years ago
1
Arrays After a while
2
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
3
while loops Allow us to loop for an indeterminate amount of cycles Example: while(door.isLocked()){ ringDoorBell(); waitForResponse(10); } New Keyword boolean condition inside parentheses Curly braces encompass code to be cycled over
4
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
5
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?
6
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:
7
Real life “arrays”
8
Array Syntax Declaration: int[] fibNumbers; Definition pt. 1: fibNumbers = new int[5]; Type of variable the array will hold Square brackets denote array Array Name Array size
9
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!
10
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.