mirror of
https://gitlab.com/magicalsoup/Highschool.git
synced 2025-01-23 16:11:46 -05:00
2.1 KiB
2.1 KiB
Class 1 Notes
Array Review
What is an Array:
- An (reference) object used to store a list of values
- A contiguous block of memory is used to store the values.
- Each cell holds a value
- All the values are the same type
- It can store all kinds of data,
int
,double
,object
, etc, the type stored can be primitive (int
) or reference (object
) - Once an array has been created, the number of cells cannot be changed.
Example
index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|---|
value | 80 | 120 | 103 | 138 | 94 | 109 | 83 | 117 |
- The array name is
bowlingScores
, you can access specific value at a specific index: eg.bowlingScores[3]
= 138. - If there are \(`n`\) cells in the array the indexes will be from \(`0`\) to \(`n-1`\), arrays are 0-index based.
- If we are acessing a value out of the range of the array, such as
bowlingScores[8]
, then we get anArrayOutOfBounds Error
.
Initializing Arrays
- General syntax to declare an array:
final int MAX = 8;
int [] bowlingScores= new int[MAX];
[0] = 180; // initializing
bowlingScores[1] = 120; // initializing
bowlingScores...
- To intialize all the values at once, we can do:
int[] luckyNumbers = {2, 3, 10, 4, 17, 21}; // known values
Summing Values In An Array
In Main
int sum; // declare an accumulator
= 0;
sum for(int i=0; i<MAX i++) {
= sum + list[i]; // sum += list[i];
sum }
System.out.println("The sum of all values in the array in the array is " + sum);
As A Method
public int findSum(int [] list) {
int sum; // declare an accumulator
= 0;
sum for(int i=0; i<MAX i++) {
= sum + list[i]; // sum += list[i];
sum }
System.out.println("The sum of all values in the array in the array is " + sum);
}
Method That Returns An Array
public int[] getNewList() {
int [] list = new int[10];
for(int i=0; i<10; i++) {
[i] = i;
list}
return list;
}