From 335e4108d395d59a8a4836407d6db0101ecf9e89 Mon Sep 17 00:00:00 2001 From: Colin Lim Date: Mon, 8 Jan 2024 11:34:50 -0800 Subject: [PATCH 1/6] review for 2Darrays for new 122 structure --- book_source/source/2darrays.md | 242 +++++++++++++++++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 book_source/source/2darrays.md diff --git a/book_source/source/2darrays.md b/book_source/source/2darrays.md new file mode 100644 index 0000000..0e377f0 --- /dev/null +++ b/book_source/source/2darrays.md @@ -0,0 +1,242 @@ +# 2DArrays + +## 2DArray Fundamentals + +An 2D array is very similar to an 1D array, or just an array as we have learned, only that instead of storing primiative types, it stores another array. In other words, a 2D array is an array where each element contains another array. Commonly this is represented/used when dealing with images, graphs, tables, and various other 2D representations. + +Much like how you would access a specific element in an array using square brackets '[]', for a 2D array, you need to add one more pair of brackets to access an element in a 2D array. For example, if you wanted to create a 2D array storing integers, an example syntax could be int[][] (read as a 2D array of ints or 2D int array). Although the specific lengths of the arrays can vary, these arrays still have a fixed length once created. For ease of representation, we typically repersent a 2D array with rows being the inner arrays and columns being the array of arrays. For example: +``` +[[0 , 1 , 2 , 3 , 4], +[5 , 6 , 7 , 8 , 9 ], +[10, 11, 12, 13, 14], +[15, 16, 17, 18, 19], +[20, 21, 22, 23, 24]] +``` +Notice there is an extra pair of opening and closing brackets, which represents the array that stores all of the other arrays. The syntax is commonly represented as array[row][col] as seen visually as well. Additionally, the call to an array using the syntax array[1] would still function, only instead of providing a primative type, it would instead provide the array stored at that index of the array of arrays. + +````{tab-set-code} + +```{code-block} java +int[][] array = new int[5][5]; +array[1][2] = 1; +array[1][3] = 14; +array[3][4] = array[1][2]; +array[4][4] = 5; + +for (int i = 0; i < array.length; i++) { + System.out.println(Arrays.toString(array[i])); +} +``` + +```{code-block} python +array = [[0]*5] *5 # Short-hand to make a 2D length 5 list +array[1][2] = 1; +array[1][3] = 14; +array[3][4] = array[1][2]; +array[4][4] = 5; + +print(array) +``` + +```{code-block} javascript +let array = [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]]; + +array[1][2] = 1; +array[1][3] = 14; +array[3][4] = array[1][2]; +array[4][4] = 5; + +console.log(array); +``` + +```{code-block} c +int array[5][5] = {{0}}; +array[1][2] = 1; +array[1][3] = 14; +array[3][4] = array[1][2]; +array[4][4] = 5; + +printf("["); +for (int i = 0; i < 5; i++) { +for (int j = 0; j < 5; j++) { +printf("%d, ", array[i][j]); +} +printf("\n"); +} +``` + +```{code-block} c++ +int array[5][5] = { + {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0}, + {0, 0, 0, 0, 0}, +}; + +array[1][2] = 1; +array[1][3] = 14; +array[3][4] = array[1][2]; +array[4][4] = 5; +for (int i = 0; i < 5; ++i) { +for (int j = 0; j < 5; ++j) { +std::cout << array[i][j] << " "; +} +std::cout << std::endl; +} +``` +```` + +Similarily, if we want to change the value at (3,4) of the 2D array to 1, where 3 is the "x" coordinate or outside array and 4 is the "y" or inner array we would do something like array[3][4] = 1. + +Two important notes about arrays in Java: +maybe add some things that are unique to 2D arrays and things like that?? +* maybe how the array will only be of one type even tho there are two arrays + + +## Looping over 2D Arrays + +We can also use a for loop to view and/or modify each index, although since this is a nested data structure (meaning there is a data structure within another data structure), we need to use a nested for loop in return. The starting value for each loop will typically start at 0, going to either array.length or array[0].length. Note the second for loop, we use array[0].length since we only want to loop through to the end of the inner array length, represented by array[0]. + + +````{tab-set-code} + +```{code-block} java +int[][] array = new int[5][5]; +// Code to fill array with some values + +int sum = 0; +for (int i = 0; i < array.length; i++) { + for (int j = 0; j < array[0].length; j++) { + sum += array[i][j]; + } +} +``` + +```{code-block} python +array = [0] * 5 # Short-hand to make a length 5 list +# Code to fill array with some values + +sum = 0 +for i in range(len(array)): + sum += array[i] +``` + +```{code-block} javascript +let array = [0, 0, 0, 0, 0]; +// Code to fill array with some values + +let sum = 0; +for (let i = 0; i < array.length; i++) { + sum += array[i]; +} +``` + +```{code-block} c +int array[5]; +// Code to fill array with some values + +int sum = 0; +size_t length = sizeof(array) / sizeof(array[0]); +for (int i = 0; i < length; i++) { + sum += array[i]; +} +``` + +```{code-block} c++ +int array[5]; +// Code to fill array with some values + +int sum = 0; +size_t length = sizeof(array) / sizeof(array[0]); +for (int i = 0; i < length; i++) { + sum += array[i]; +} +``` + +```{code-block} c++ +int array[5]; +// Code to fill array with some values + +int sum = 0; +for (int i = 0; i < array.length; i++) { + sum += array[i]; +} +``` +```` + +## Printing 2D Arrays + +Note that unlike with a 1D array, we cannot simply do Arrays.toString(array) on the entire 2D array, instead we have to loop thorugh each of the rows of the 2D array, then call Arrays.toString(array[i]), where i are values 0 through array.length - 1. + +````{tab-set-code} + +```{code-block} java + +int[][] array = new int[5][5]; +array[1][2] = 1; +array[1][3] = 14; +array[3][4] = array[1][2]; +array[4][4] = 5; + +for (int i = 0; i < array.length; i++) { + System.out.println(Arrays.toString(array[i])); +} +``` + +```{code-block} python +array = [0] * 3 # Short-hand to make a length 3 list +array[0] = 8 +array[1] = 1 +array[2] = 7 + +print(array) +// Output: [8, 1, 7] +``` + +```{code-block} javascript +let array = [[], [], [], []]; + + +console.log(array); +// Output: [8, 1, 7] +``` + +```{code-block} c +int array[3]; +array[0] = 8; +array[1] = 1; +array[2] = 7; + +printf("["); +for (int i = 0; i < 2; i++) { + printf("%d, ", array[i]); +} +printf("%d]\n", array[2]); +// Output: [8, 1, 7] +``` + +```{code-block} c++ +int array[3]; +array[0] = 8; +array[1] = 1; +array[2] = 7; + +cout << "["; +for (int i = 0; i < 2; i++) { + cout << array[i] << ", "; +} +cout << array[2] << "]" << endl; +// Output: [8, 1, 7] +``` +```` + +This code yield the following output. + +```text +[0, 0, 0, 0, 0] +[0, 0, 1, 14, 0] +[0, 0, 0, 0, 0] +[0, 0, 0, 0, 1] +[0, 0, 0, 0, 5] +``` \ No newline at end of file From ca25302057be04757e95681e35e47062e7ebd5b8 Mon Sep 17 00:00:00 2001 From: Colin Lim Date: Mon, 8 Jan 2024 11:54:20 -0800 Subject: [PATCH 2/6] add/remove new content for 122 --- book_source/source/2darrays.md | 9 +- book_source/source/io_files.md | 503 --------------------------------- 2 files changed, 2 insertions(+), 510 deletions(-) delete mode 100644 book_source/source/io_files.md diff --git a/book_source/source/2darrays.md b/book_source/source/2darrays.md index 0e377f0..2348a04 100644 --- a/book_source/source/2darrays.md +++ b/book_source/source/2darrays.md @@ -12,7 +12,7 @@ Much like how you would access a specific element in an array using square brack [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]] ``` -Notice there is an extra pair of opening and closing brackets, which represents the array that stores all of the other arrays. The syntax is commonly represented as array[row][col] as seen visually as well. Additionally, the call to an array using the syntax array[1] would still function, only instead of providing a primative type, it would instead provide the array stored at that index of the array of arrays. +Notice there is an extra pair of opening and closing brackets, which represents the array that stores all of the other arrays. The syntax is commonly represented as array[row][col] and is represented visually as so above for clarity. Additionally, the call to an array using the syntax array[1] would still function, only instead of providing a primative type, it would instead provide the array stored at that index of the array of arrays. ````{tab-set-code} @@ -87,12 +87,7 @@ std::cout << std::endl; ``` ```` -Similarily, if we want to change the value at (3,4) of the 2D array to 1, where 3 is the "x" coordinate or outside array and 4 is the "y" or inner array we would do something like array[3][4] = 1. - -Two important notes about arrays in Java: -maybe add some things that are unique to 2D arrays and things like that?? -* maybe how the array will only be of one type even tho there are two arrays - +Similarily, if we want to change the value at (3,4) of the 2D array to 1, where 3 is the "x" coordinate or outside array and 4 is the "y" or inner array we would do something like array[3][4] = 1. Note that the 2D array can only be of one type, just like how a 1D array is only one type. ## Looping over 2D Arrays diff --git a/book_source/source/io_files.md b/book_source/source/io_files.md deleted file mode 100644 index ac5e340..0000000 --- a/book_source/source/io_files.md +++ /dev/null @@ -1,503 +0,0 @@ -# Files and I/O - - -Very commonly, we store data in files that we want to read from in our programs. For example, things like Google Docs are backed by some files somewhere on Google's computers. - -For simplicity, we will only focus on *text files* which store only text data such as the file `poem.txt`. - -```text -she sells -sea -shells by -the sea shore -``` - -## Reading From a File - -To read from a file in Java, we use a `Scanner` object that controls how to read the file. A `Scanner` keeps track of where we are in the file and how to read the next parts bit by bit. The following code snippet shows how to to create a Scanner and read the file each "token" at a time. A *token* is a series of characters separated by whitespace. It is the same idea as the concept of a "word", but more general since there are many non-words that are stored in computer files such as numbers. - -````{tab-set-code} - -```{code-block} java -public class FileReading { - public static void main(String[] args) throws FileNotFoundException { - Scanner fileInput = new Scanner(new File("poem.txt")); - - while (fileInput.hasNext()) { - String token = fileInput.next(); - System.out.println(token); - } - } -} -``` - -```{code-block} python -def main(): - with open("poem.txt") as f: - for line in f.readlines(): - tokens = line.split() - for token in tokens: - print(token) - - -if __name__ == "__main__": - main() -``` - -```{code-block} javascript -// File I/O is not allowed natively on Javascript -// The following code is written for node.js - -var fs = require('fs'); -function main() { - let file = fs.readFileSync('poem.txt', 'utf8'); - let lines = file.split('\n'); - for (let i = 0; i < lines.length; i++) { - let tokens = lines[i].split(' '); - for (let j = 0; j < tokens.length; j++) { - console.log(tokens[j]); - } - } -} - -main() -``` - -```{code-block} c -#include -#include - -int main() -{ - const char *delimiter_characters = " "; - const char *filename = "poem.txt"; - FILE *input_file = fopen( filename, "r" ); - char buffer[ 1024 ]; - char *last_token; - - while( fgets(buffer, 1024, input_file) != NULL ){ - last_token = strtok( buffer, delimiter_characters ); - while( last_token != NULL ){ - printf( "%s\n", last_token ); - last_token = strtok( NULL, delimiter_characters ); - } - - } - - fclose( input_file ); - return 0; -} -``` - -```{code-block} c++ -#include -#include -#include - -using namespace std; - -int main() -{ - string token; - ifstream file("poem.txt"); - while ( getline(file, token) ) - { - istringstream line(token); - while (line >> token) - { - cout << token << endl; - } - } - - return 0; -} -``` -```` - -This code yield the following output. - -```text -she -sells -sea -shells -by -the -sea -shore -``` - -The `Scanner` object keeps track of which position we are in the file. The `hasNext()` method returns `true` if there are any remaining tokens, and the `next()` method will return the next token. In other words, this code is repeatedly asking for one token from the file at a time, until there are no more tokens. - -To construct a `Scanner` we use the syntax to attach a `Scanner` to a particular file. Note that Java requires us to now change the `main` method declaration to include the statement `throws FileNotFoundException` because the file may not exist. You do not need to understand the `throws` keyword, outside you need to include this text when you are reading from files. - -```java -Scanner fileInput = new Scanner(new File("poem.txt")); -``` - -## Line and Token Based Processing - -Very commonly, we might need more granularity when it comes to how we want to read files. For example, consider the problem of counting the number of tokens that appear on each round. So for example, for our `poem.txt` above we might want to print out something like the following to count the number of words per line. - -```text -1: 2 -2: 1 -3: 2 -4: 3 -``` - -The following code snippet shows how to do this in Java. Note that instead of calling the `next()` and `hasNext()` method, we are calling the `nextLine()` and `hasNextLine()`. These methods behave similarly, but instead of returning a single token returns the whole line of text. We then can actually use another `Scanner` made from this line to read just that line token by token! This is a common pattern for mixing line-based processing and token-based processing. - -````{tab-set-code} - -```{code-block} java -public class FileReading { - public static void main(String[] args) throws FileNotFoundException { - Scanner fileInput = new Scanner(new File("poem.txt")); - - int lineNum = 1; - // Loop over every line of the file - while (fileInput.hasNextLine()) { - String line = fileInput.nextLine(); - - // Make a new Scanner attached to just this line of text - Scanner lineInput = new Scanner(line); - - // Loop over every token in this line - int tokenCount = 0; - while (lineInput.hasNext()) { - lineInput.next(); - tokenCount++; - } - - System.out.println(lineNum + ": " + tokenCount); - - // Update the line number for the next iteration - lineNum++; - } - } -} -``` - -```{code-block} python -def main(): - line_num = 1 - with open("poem.txt") as f: - for line in f.readlines(): - tokens = line.split() - - token_count = 0 - for token in tokens: - token_count += 1 - - print(str(line_num) + ": " + str(token_count)) - - line_num += 1 - - -if __name__ == "__main__": - main() -``` - -```{code-block} javascript -// File I/O is not allowed natively on Javascript -// The following code is written for node.js - -var fs = require('fs'); -function main() { - let file = fs.readFileSync('poem.txt', 'utf8'); - let line_num = 1; - let lines = file.split('\n'); - for (let i = 0; i < lines.length; i++) { - let tokens = lines[i].split(' '); - let token_count = 0; - for (let j = 0; j < tokens.length; j++) { - token_count++; - } - console.log(line_num + ": " + token_count); - line_num++; - } -} - -main() -``` - -```{code-block} c -#include -#include - -int main() -{ - const char *delimiter_characters = " "; - const char *filename = "poem.txt"; - FILE *input_file = fopen( filename, "r" ); - char buffer[ 1024 ]; - char *last_token; - int line_num = 1; - - while ( fgets(buffer, 1024, input_file) != NULL ) { - last_token = strtok( buffer, delimiter_characters ); - int token_count = 0; - while ( last_token != NULL ) { - token_count++; - last_token = strtok( NULL, delimiter_characters ); - } - - printf("%d: ", line_num); - printf("%d\n", token_count) - - line_num++; - } - - fclose( input_file ); - return 0; -} -``` - -```{code-block} c++ -#include -#include -#include - -using namespace std; - -int main() -{ - string token; - ifstream file("poem.txt"); - int line_num = 1; - - while ( getline(file, token) ) - { - istringstream line(token); - int token_count = 0; - while (line >> token) - { - token_count++; - } - - cout << line_num << ": " << endl; - cout << token_count << endl; - - line_num++; - } - - return 0; -} -``` -```` - -The beauty of a `Scanner` is it hides all of the logic of figuring out what source of data it is attached to, how to fetch the next thing or tell if there is more data present. All we need to do as programmers is make a new `Scanner` instance and call the methods we want! - -## User Input - -Often, we also want to be able to interact with the user and ask them for input by having them type into the keyboard. It turns out that the `Scanner` was designed for this purpose to since user input is just another data source! We can make a new `Scanner` instance, but instead of attaching it to a file or a `String`, we can attach it to a special source for the user's keyboard called `System.in`. The following program asks the user for their name and age and prints a greeting. When we run this program, every time we call one of the `next` methods it will pause, and wait for the user to type in the requested info. - -````{tab-set-code} - -```{code-block} java -public class UserInput { - public static void main(String[] args) { - Scanner input = new Scanner(System.in); - - System.out.print("What is your name? "); - String name = input.nextLine(); - - System.out.print("What is your age? "); - int age = input.nextInt(); - - System.out.println("Welcome " + name + " (" + age + ")!"); - } -} -``` - -```{code-block} python -def main(): - name = input("What is your name? ") - age = int(input("What is your age? ")) - - print("Welcome " + name + " (" + str(age) + ")!") - - -if __name__ == "__main__": - main() -``` - -```{code-block} javascript -function main() { - let name = prompt("What is your name? "); - let age = Number(prompt("What is your age? ")); - - console.log("Welcome " + name + " (" + age + ")!"); -} - -main() -``` - -```{code-block} c -#include - -int main() -{ - char *name; - int age; - - printf("What is your name? "); - scanf("%s", name); - - printf("What is your age? "); - scanf("%d", &age); - - printf("Welcome %s ", name); - printf("(%d)!", age); - return 0; -} -``` - -```{code-block} c++ -#include - -using namespace std; - -int main() -{ - string name; - int age; - - cout << "What is your name? "; - cin >> name; - - cout << "What is your age? "; - cin >> age; - - cout << "Welcome" << name << "(" << age << ")!" << endl; - - return 0; -} -``` -```` - -There are some things to note about this program: - -* When constructing the `Scanner`, we say `new Scanner(System.in);` to attach it to the user's keyboard. -* We no longer need the `throws FileNotFoundException` in our `main` header since we are no longe reading from a file. -* To get the user's age, we called the method `nextInt()` instead of `next()`. It turns out that turning text data like the `String` `"16"` into a number is quite tricky. So instead, the `Scanner` provides other methods that do the conversion from text to the data type you are interested for you. Some of the methods that are most commonly used for interpreting a token of data include: - * `next()` to get the next token as a `String` - * `nextInt()` to get the next token as an `int` - * `nextDouble()` to get the next token as a `double` - * `nextBoolean()` to get the next token as a `boolean` - * `nextLine()` get the whole line as a `String` - * All of the equivalent `hasNextX()` methods such as `hasNext()` and `hasNextInt()`. - -## Writing to a File - -We use a `PrintStream` object to write output to a file. - -To create a `PrintStream` connected to a specific file, we can pass in the `File` object as a parameter upon initialization. If a file with the given name already exists, it will replace the contents with the new output. Otherwise, the `PrintStream` will automatically create the file for you. - -When using a `PrintStream`, the syntax is very similar to printing to the console. Instead of printing using `System.out` (a.k.a. the console), we are printing using the `PrintStream` object. Let's say we have a `PrintStream` object named `output`; instead of `System.out.println(...)`, we will say `output.println(...)`. - -Common `PrintStream` methods include: -* `println(___)` to write text to the file followed by a newline. -* `print(___)` to write text to the file without a newline afterwards. -* `write(___)` to write a byte value to the file. - -````{tab-set-code} - -```{code-block} java -public class FileWriting { - public static void main(String[] args) throws FileNotFoundException { - PrintStream output = new PrintStream(new File("poem.txt")); - - output.println("she sells sea shells"); - output.println("by the sea shore"); - for (int i = 1; i <= 5; i++) { - output.print(i); - } - } -} -``` - -```{code-block} python -def main(): - f = open("poem.txt", "w") - f.write("she sells sea shells\nby the sea shore\n") - for i in range(1, 6): - f.write(i) - f.close() - -if __name__ == "__main__": - main() -``` - -```{code-block} javascript -// File I/O is not allowed natively on Javascript -// The following code is written for node.js - -var fs = require('fs'); -function main() { - let data = "she sells sea shells\nby the sea shore\n"; - for (let i = 1; i <= 5; i++) { - data += i; - } - fs.writeFile("poem.txt", data, (err) => { - if (err) throw err; - }); -} - -main() -``` - -```{code-block} c -#include -#include - -int main() -{ - const char *filename = "poem.txt"; - FILE *input_file = fopen( filename, "w" ); - int i; - - fprintf( fptr, "she sells sea shells\nby the sea shore\n" ); - - for (i = 1; i <= 5; i++) - { - fprintf( fptr, "%d", i ); - } - - fclose( input_file ); - return 0; -} -``` - -```{code-block} c++ -#include -#include -#include - -using namespace std; - -int main() -{ - ofstream file; - int i; - - file.open("poem.txt"); - file << "she sells sea shells\nby the sea shore\n"; - for (i = 1; i <= 5; i++) { - file << i; - } - - file.close(); - return 0; -} -``` -```` - -This code yield the following output to a file named `poem.txt`. - -```text -she sells sea shells -by the sea shore -12345 -``` From eb6359cbe90a5bf31b36602f22ac0d69d79a5f86 Mon Sep 17 00:00:00 2001 From: Colin Lim Date: Mon, 8 Jan 2024 13:58:07 -0800 Subject: [PATCH 3/6] updated toc to match --- book_source/source/_toc.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/book_source/source/_toc.yml b/book_source/source/_toc.yml index b787e6a..50b49e1 100644 --- a/book_source/source/_toc.yml +++ b/book_source/source/_toc.yml @@ -7,5 +7,5 @@ chapters: - file: loops - file: strings - file: methods - - file: io_files - - file: arrays \ No newline at end of file + - file: arrays + - file: 2darrays \ No newline at end of file From 54df237511af4603416a6b4abf8cce84ba08ef4d Mon Sep 17 00:00:00 2001 From: Colin Lim <67755841+WateringFire@users.noreply.github.com> Date: Wed, 17 Jan 2024 16:03:45 -0800 Subject: [PATCH 4/6] Apply suggestions from code review Co-authored-by: Miya Natsuhara <46756417+mnatsuhara@users.noreply.github.com> --- book_source/source/2darrays.md | 46 +++++++++++++++------------------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/book_source/source/2darrays.md b/book_source/source/2darrays.md index 2348a04..769eab7 100644 --- a/book_source/source/2darrays.md +++ b/book_source/source/2darrays.md @@ -2,9 +2,9 @@ ## 2DArray Fundamentals -An 2D array is very similar to an 1D array, or just an array as we have learned, only that instead of storing primiative types, it stores another array. In other words, a 2D array is an array where each element contains another array. Commonly this is represented/used when dealing with images, graphs, tables, and various other 2D representations. +A 2D or "two-dimensional" array is very similar to the arrays that we talked about in the previous section, but instead of elements of types like `int`, `double`, `String`, etc, its element type is _array_. In other words, a 2D array is an array where each element is a reference to _another_ array. This type of data structure is helpful for representing many different kinds of scenarios, such as in applications using images, graphs, and tables. -Much like how you would access a specific element in an array using square brackets '[]', for a 2D array, you need to add one more pair of brackets to access an element in a 2D array. For example, if you wanted to create a 2D array storing integers, an example syntax could be int[][] (read as a 2D array of ints or 2D int array). Although the specific lengths of the arrays can vary, these arrays still have a fixed length once created. For ease of representation, we typically repersent a 2D array with rows being the inner arrays and columns being the array of arrays. For example: +You can access elements of a 2D array using square brackets `[]`, in the same way that we accessed elements of 1D arrays in the previous section. However, remember that the elements of a 2D array are arrays! If you want to get one of _those_ arrays' elements, you'll need to use two sets of square brackets `[][]`. For example, if you were dealing with a 2D array of integers `arr`, the type of the 2D array would be `int[][]` and you could access an individual `int` from the 2D array with `arr[_i_][_j_]` where `i` and `j` are the row and column index of the element we wanted. ``` [[0 , 1 , 2 , 3 , 4], [5 , 6 , 7 , 8 , 9 ], @@ -50,7 +50,7 @@ console.log(array); ``` ```{code-block} c -int array[5][5] = {{0}}; +int array[5][5]; array[1][2] = 1; array[1][3] = 14; array[3][4] = array[1][2]; @@ -58,40 +58,34 @@ array[4][4] = 5; printf("["); for (int i = 0; i < 5; i++) { -for (int j = 0; j < 5; j++) { -printf("%d, ", array[i][j]); -} -printf("\n"); + for (int j = 0; j < 5; j++) { + printf("%d, ", array[i][j]); + } + printf("\n"); } ``` ```{code-block} c++ -int array[5][5] = { - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, -}; +int array[5][5]; array[1][2] = 1; array[1][3] = 14; array[3][4] = array[1][2]; array[4][4] = 5; for (int i = 0; i < 5; ++i) { -for (int j = 0; j < 5; ++j) { -std::cout << array[i][j] << " "; -} -std::cout << std::endl; + for (int j = 0; j < 5; ++j) { + std::cout << array[i][j] << " "; + } + std::cout << std::endl; } ``` ```` -Similarily, if we want to change the value at (3,4) of the 2D array to 1, where 3 is the "x" coordinate or outside array and 4 is the "y" or inner array we would do something like array[3][4] = 1. Note that the 2D array can only be of one type, just like how a 1D array is only one type. +Note the syntax that we are using to assign values to integer elements of the 2D array - we need to use two pairs of square brackets `[][]` and specify the row _and_ column of the space we want to assign the value to. ## Looping over 2D Arrays -We can also use a for loop to view and/or modify each index, although since this is a nested data structure (meaning there is a data structure within another data structure), we need to use a nested for loop in return. The starting value for each loop will typically start at 0, going to either array.length or array[0].length. Note the second for loop, we use array[0].length since we only want to loop through to the end of the inner array length, represented by array[0]. +To traverse over a 2D array, it's very common to use a _nested for loop structure_ where the outer for loops iterates over each _row_ of the 2D array, and the inner for loop iterates over each _element_ within each row. See some examples below. ````{tab-set-code} @@ -162,7 +156,7 @@ for (int i = 0; i < array.length; i++) { ## Printing 2D Arrays -Note that unlike with a 1D array, we cannot simply do Arrays.toString(array) on the entire 2D array, instead we have to loop thorugh each of the rows of the 2D array, then call Arrays.toString(array[i]), where i are values 0 through array.length - 1. +Recall that we would get a nicely-formatted String representation of a 1D array using `Arrays.toString(...)`. However, passing a 2D array to this method will probably not produce the output you're looking for. Instead, you should use the `Arrays.**deep**ToString(...)` method or iterate over each of the rows of the 2D array, then print out each individual row using `Arrays.toString(...)` as shown below. ````{tab-set-code} @@ -204,10 +198,10 @@ array[1] = 1; array[2] = 7; printf("["); -for (int i = 0; i < 2; i++) { +for (int i = 0; i < 3; i++) { printf("%d, ", array[i]); } -printf("%d]\n", array[2]); +printf("]\n"); // Output: [8, 1, 7] ``` @@ -217,11 +211,11 @@ array[0] = 8; array[1] = 1; array[2] = 7; -cout << "["; -for (int i = 0; i < 2; i++) { +std::cout << "["; +for (int i = 0; i < 3; i++) { cout << array[i] << ", "; } -cout << array[2] << "]" << endl; +std::cout << "]" << endl; // Output: [8, 1, 7] ``` ```` From 58f5a3928e3a4055a429d5451226523aed40215c Mon Sep 17 00:00:00 2001 From: Colin Lim Date: Fri, 19 Jan 2024 01:05:07 -0800 Subject: [PATCH 5/6] finalized final examples in all languages --- book_source/source/2darrays.md | 62 ++++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/book_source/source/2darrays.md b/book_source/source/2darrays.md index 769eab7..32fb3c1 100644 --- a/book_source/source/2darrays.md +++ b/book_source/source/2darrays.md @@ -4,6 +4,8 @@ A 2D or "two-dimensional" array is very similar to the arrays that we talked about in the previous section, but instead of elements of types like `int`, `double`, `String`, etc, its element type is _array_. In other words, a 2D array is an array where each element is a reference to _another_ array. This type of data structure is helpful for representing many different kinds of scenarios, such as in applications using images, graphs, and tables. +A grid is typically represeted using columns and rows, where columns are all the elements of a vertical line of the grid and a row is all of the elements on a horizontal line of a grid. The same logic applies to a 2D array where a commonly used reprensetation to describe the arrays is that the outer array's indexes are the rows of the grid, and the inner arrays indexes are the columns. This can be seen in the 2D array representation below. + You can access elements of a 2D array using square brackets `[]`, in the same way that we accessed elements of 1D arrays in the previous section. However, remember that the elements of a 2D array are arrays! If you want to get one of _those_ arrays' elements, you'll need to use two sets of square brackets `[][]`. For example, if you were dealing with a 2D array of integers `arr`, the type of the 2D array would be `int[][]` and you could access an individual `int` from the 2D array with `arr[_i_][_j_]` where `i` and `j` are the row and column index of the element we wanted. ``` [[0 , 1 , 2 , 3 , 4], @@ -12,7 +14,6 @@ You can access elements of a 2D array using square brackets `[]`, in the same wa [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]] ``` -Notice there is an extra pair of opening and closing brackets, which represents the array that stores all of the other arrays. The syntax is commonly represented as array[row][col] and is represented visually as so above for clarity. Additionally, the call to an array using the syntax array[1] would still function, only instead of providing a primative type, it would instead provide the array stored at that index of the array of arrays. ````{tab-set-code} @@ -165,7 +166,6 @@ Recall that we would get a nicely-formatted String representation of a 1D array int[][] array = new int[5][5]; array[1][2] = 1; array[1][3] = 14; -array[3][4] = array[1][2]; array[4][4] = 5; for (int i = 0; i < array.length; i++) { @@ -174,49 +174,59 @@ for (int i = 0; i < array.length; i++) { ``` ```{code-block} python -array = [0] * 3 # Short-hand to make a length 3 list -array[0] = 8 -array[1] = 1 -array[2] = 7 +array = [[0] * 5 for _ in range(5)] -print(array) -// Output: [8, 1, 7] +array[1][2] = 1 +array[1][3] = 14 +array[4][4] = 5 + +for row in array: + print(row) ``` ```{code-block} javascript -let array = [[], [], [], []]; +let array = new Array(5).fill().map(() => new Array(5).fill(0)); +array[1][2] = 4; +array[1][3] = 14; +array[4][4] = 5; console.log(array); -// Output: [8, 1, 7] ``` ```{code-block} c -int array[3]; -array[0] = 8; -array[1] = 1; -array[2] = 7; +int array[5][5]; + +array[1][2] = 4; +array[1][3] = 14; +array[4][4] = 5; printf("["); -for (int i = 0; i < 3; i++) { - printf("%d, ", array[i]); +for (int i = 0; i < 5; i++) { + printf("["); + for (int j = 0; j < 5; j++){ + printf("%d, ", array[i][j]); + } + printf("]\n"); } -printf("]\n"); -// Output: [8, 1, 7] +printf("]"); ``` ```{code-block} c++ -int array[3]; -array[0] = 8; -array[1] = 1; -array[2] = 7; +int array[5][5]; +array[1][2] = 4; +array[1][3] = 14; +array[4][4] = 5; std::cout << "["; -for (int i = 0; i < 3; i++) { - cout << array[i] << ", "; +for (int i = 0; i < 5; i++) { + std::cout << "["; + for (int j = 0; j < 5; j++){ + std::cout << array[i][j] << ", "; + } + std::cout << "]" << std::endl; } -std::cout << "]" << endl; -// Output: [8, 1, 7] +std::cout << "]" << std::endl; ``` ```` From 05cb85dc64bf95ac0dcbd1137bad3e6f1a2df32d Mon Sep 17 00:00:00 2001 From: wateringfire Date: Wed, 15 Jan 2025 13:18:09 -0800 Subject: [PATCH 6/6] fixed incorrect java data type --- book_source/source/variables_expressions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book_source/source/variables_expressions.md b/book_source/source/variables_expressions.md index 1375319..9078c42 100644 --- a/book_source/source/variables_expressions.md +++ b/book_source/source/variables_expressions.md @@ -290,7 +290,7 @@ Java has no operator for exponentiation (e.g., $3^2$). Instead, you have to use public class Expressions { public static void main(String[] args) { int x = 3; - int y = Math.pow(x, 2); + double y = Math.pow(x, 2); } } ```