1
0
mirror of https://gitlab.com/magicalsoup/Highschool.git synced 2025-01-23 16:11:46 -05:00
highschool/Grade 10/Computer Science/ICS4U1/Class_1.md

97 lines
2.1 KiB
Markdown
Raw Permalink Normal View History

2019-09-06 12:26:29 -04:00
# Class 1 Notes
2019-09-06 12:03:47 -04:00
# 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`)
2019-09-06 12:26:29 -04:00
- Once an array has been created, the number of cells **cannot** be changed.
2019-09-06 12:03:47 -04:00
## Example
<table>
<tr>
<th>index</th>
<td>0</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<th>value</th>
<td>80</td>
<td>120</td>
<td>103</td>
<td>138</td>
<td>94</td>
<td>109</td>
<td>83</td>
<td>117</td>
</tr>
</table>
2019-09-06 12:26:29 -04:00
- 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;
}
```