1
0
mirror of https://gitlab.com/magicalsoup/Highschool.git synced 2025-01-23 16:11:46 -05:00

Update Class_1.md

This commit is contained in:
James Su 2019-09-06 16:26:29 +00:00
parent e150cba542
commit 9e842923be

View File

@ -1,4 +1,4 @@
# Class 1 notes
# Class 1 Notes
# Array Review
@ -8,6 +8,8 @@
- 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
@ -36,3 +38,59 @@
</tr>
</table>
- 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 an `ArrayOutOfBounds Error`.
## Initializing Arrays
- General syntax to declare an array:
```java
final int MAX = 8;
int [] bowlingScores= new int[MAX];
bowlingScores[0] = 180; // initializing
bowlingScores[1] = 120; // initializing
...
```
- To intialize all the values at once, we can do:
```java
int[] luckyNumbers = {2, 3, 10, 4, 17, 21}; // known values
```
## Summing Values In An Array
### In Main
```java
int sum; // declare an accumulator
sum = 0;
for(int i=0; i<MAX i++) {
sum = sum + list[i]; // sum += list[i];
}
System.out.println("The sum of all values in the array in the array is " + sum);
```
### As A Method
```java
public int findSum(int [] list) {
int sum; // declare an accumulator
sum = 0;
for(int i=0; i<MAX i++) {
sum = sum + list[i]; // sum += list[i];
}
System.out.println("The sum of all values in the array in the array is " + sum);
}
```
## Method That Returns An Array
```java
public int[] getNewList() {
int [] list = new int[10];
for(int i=0; i<10; i++) {
list[i] = i;
}
return list;
}
```