{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1f7e06b9-1ca3-4eed-a975-d214242f4a46",
   "metadata": {},
   "source": [
    "```{index} array; one dimensional\n",
    "```\n",
    "\n",
    "(one-dim-arrays)=\n",
    "\n",
    "# 1D Arrays\n",
    "\n",
    "```{index} array; [ ] declaration\n",
    "```\n",
    "\n",
    "An array is a `data structure` that contains a number of variables that are accessed\n",
    "through computed indices. The variables contained in an array, also called the\n",
    "`elements` of the array, are all of the same type, and this type is called the\n",
    "`element type` of the array. [1]\n",
    "\n",
    "In C#, an array is a structure representing a **fixed length** `ordered` collection of\n",
    "values or objects with the **same type**. Arrays make it easier to organize and\n",
    "operate on large amounts of data. For example, rather than creating 100 integer\n",
    "variables, you can just create one array that stores all those integers and access\n",
    "them using array indices. [2]\n",
    "\n",
    "You have learned that a string is an immutable `sequence` of characters and how to\n",
    "loop through the sequence. Arrays provide more general sequences, with the\n",
    "same indexing notation, but with free choice of the `type` of the items in the\n",
    "sequence, and the ability to `change` the elements in the sequence.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dffd3b7b",
   "metadata": {},
   "source": "## Creating Arrays\n\nA C# `array variable` is declared similarly to a non-array variable, with the\naddition of square brackets (`[]`) after the `type` specifier to denote it as an array.\nSo, the general form for declaring an array variable of the element type is:\n\n> **type**`[]` variableName;\n\nFor example, if you want to create an array called `a` with the type `int`\nfor elements, you declare the array variable as:\n\n    int[] a;\n\nIn this declaration, you do *not* know how many elements will be in this array\nfrom the preceding declaration. You must give further information to create the\ncorresponding `array object`. A new object can be created using the `new`\nsyntax. An array must get a definite length, which can be a literal integer or\nany integer expression. The general syntax to create a new array is\n\n> `new` **type**`[` *length* `]`\n\nAfter the type, there are square brackets enclosing an expression for the length\nof the array - this length is unchangeable after creation. For example\n\n    int[] a;\n    a = new int[4];\n\nor, you may combine with the declaration,\n\n    int[] a = new int[4];\n\nto creates an array that holds 4 integers. After specifying the number of the elements\nof the array, the default initial values are also assigned. For example, numerical\narrays get initialized to all 0’s (false for boolean, the character with Unicode\nnumber zero for char, and null for objects and string) with this syntax by default, so when you loop\nthrough the array variable:\n\n    > foreach (int i in a)\n      {\n          Console.Write(i);\n      }\n    0000\n    >\n\nAn **array initializer** consists of a sequence of variable initializers,\nenclosed by “`{`” and”`}`” tokens and separated by “`,`” tokens.\nAn array initializer can be used in a variable declaration:\n\n    int[] a = {0, 2, 4, 6, 8};\n\nwhich is a shorthand for the equivalent `array creation expression`:\n\n    int[] a = new int[] {0, 2, 4, 6, 8};\n\nNote that the actual data for an array is *not* stored directly in the memory location\nallocated by the declaration. The array could have any number of items, and hence\nthe memory requirements are not known at compile time. Like all other object\n(as opposed to primitive) types, what is actually stored at the memory location declared\nfor `a` is a *reference* to the actual place where the data for the array is stored.\nIn actual compiler implementation, this reference is an address in memory. In the diagram\nbelow, you see the object references with an arrow *pointing* to the actual location\nfor the object’s data after `a` is initialized:\n\n`{image} ../../images/newArray1.png :align: center :alt: new array :width: 300 pt`\n\nThe small box beside `a` is meant to indicate the memory space allocated when `a` is\ndeclared. As you can see that space does not actually contain the array, but rather a\n*reference* to the array, pointing to the actual sequence of data for the array.\nAlso, in the diagram you see the indices associated with each element, though they\nare not actual a part of what is stored in memory."
  },
  {
   "cell_type": "markdown",
   "id": "f82a1d79",
   "metadata": {},
   "source": "## Accessing Array Elements\n\n```{index} array; indexing\n```\n\nThe elements inside an array can to referenced with the same index notation used\nearlier for strings.\n\n    a[2]\n\nrefers to the element at index 2 (third element because of 0 based indexing).\n\nUnlike with strings, this element can not only be read, but also be assigned to:\n\n    a[0] = 7;\n    a[1] = 5;\n    a[2] = 9;\n    a[3] = 6;\n\nThese four assignment statements\nwould replace the original 0 values for each element in the array.\n\nThis is a verbose way to specify all array values. An array with the\nsame final data could be created with the single declaration:\n\n    int[] b = {7, 5, 9, 6};\n\n`{image} ../../images/newArray2.png :align: center :alt: new array initialized with braces :width: 300 pt`\n\nThe list in braces ONLY is allowed as an initialization of a variable\nin a *declaration*, not in a later assignment statement.\nTechnically it is an initializer, not an array literal.\n\nIndividual array elements can *both* be used in expressions, and be assigned to.\nContinuing with the earlier example code:\n\n    a[2] = 4*a[1] - a[3];\n\n`a[2]` now equals 4\\*5 - 6 = 14.\n\nArrays, like strings, have a `Length` property:\n\n    Console.WriteLine(b.Length); // prints 4\n\njust like with strings. In practice array elements are almost always referred\nto with an index variable. A very common pattern is to deal with each element\nin sequence, and the syntax is the same as for a string. Print all elements\nof array `b`:\n\n    for (int i= 0; i < b.Length, i++) {\n       Console.WriteLine(b[i]);\n    }\n\nThe `foreach` syntax would be:\n\n    foreach ( int x in b) {\n       Console.WriteLine(x);\n    }\n\nwhile the `while` loop syntax would be:\n\n    > int[] a = { 1, 2, 3, 4, 5 };\n    > int i = 0;\n    > while ( i < a.Length){\n       Console.Write(a[i]);\n       i++;\n      }\n    12345\n    >\n\nIn the `foreach` loop, the `int` type for `x` matches the element type of the array `b`.\n\nThe shorter `foreach` syntax is not as general as the `for` syntax.\nFor example, to print only the first *3* elements of b:\n\n    for(int i= 0; i < 3; i++) {\n       Console.WriteLine(b[i]);\n    }\n\nbut the `foreach` syntax would not work, since it must process *all* elements.\n\nAlso, you may use the `for` syntax to assign new values to the array elements,\nrather than just use the values in expressions:\n\n    for(int i= 0; i < b.Length; i++) {\n       b[i] = 5*i;\n    }\n\nNow the array `b` of our earlier examples (of length 4) would now contain 0, 5,\n10, and 15.\n\nThere is no analog of *changing* the value of `b[i]` with a\n`foreach` loop. To change values in an array, we must\nassign to each location in the array by *index*.\nA `foreach` loop only provides the *value* of each sequence element\nfor us to read.\n\nWe have had the array indices so far be given by a single symbol,\nwhich is the most common case in practice, but in fact what appears\ninside the square braces can be any `int` *expression*.\nLike parentheses, square brackets *delimit*\nthe inside expression, which gets evaluated first, before the array value is\nlooked up. Consider this csharprepl sequence:\n\n``` none\n> int[] a = {5, 9, 15, -4};\n> int i = 2;\n> a[i];\n15\n```\n\nThis should be clear. Now think first, what should `a[i+1]` be?\n\n``` none\n> a[i+1];\n-4\n```\n\nIn steps: `a[i+1]` is `a[2+1]` is `a[3]` is -4. Be careful,\n`a[i+1]` is *NOT* `a[i] + 1` (which would be 16).\n\n```{index} array; as parameter\n```\n\n(printstrings)=\n\nThe code above to print each element of an array performs a\nunified and possibly useful operation, so it would make sense to\nencapsulate it into a function. A function can take any type as a\nparameter, so an array type is perfectly reasonable! Above we\nprinted each element of an array of integers. This time let’s choose strings,\nso the formal parameter is an array of strings: `string[]`.\n\n```{literalinclude} ../../examples/string_array/string_array.cs\n:dedent: 6\n:end-before: chunk\n:linenos: true\n:start-after: chunk PrintStrings\n```\n\nWith this definition, the code fragment\n\n    string[] hamlet = {\"To be\", \"or not\", \"to be!\"};\n    PrintStrings(hamlet);\n\nwould print:\n\n``` none\nTo be\nor not\nto be!\n```\n\nHere we are just reading the data from the array parameter.\nWe will see that there are more wrinkles to array parameters in {ref}`alias`.\n\n```{index} function; return array\n```\n\nAn array type can also be\nreturned like any other type. Examine the function definition:\n\n```{literalinclude} ../../examples/string_array/string_array.cs\n:dedent: 6\n:end-before: chunk\n:start-after: chunk InputNStrings\n```\n\nThis code follows a standard pattern for functions returning an array:\n\n- In order to return an array, we must *first create* a new array\n  with the `new` syntax. We must set the proper length (`n` here).\n- And we are not done with one line of creation: Since the array has\n  multiple parts, we need a loop to assign all the values. We have a simple\n  `for` loop to assign to each element in turn.\n- Finally we must return the array that we created!"
  },
  {
   "cell_type": "markdown",
   "id": "59fcd1c0",
   "metadata": {},
   "source": "```{index} command line; parameter\n```\n\n(command-line-param)=\n\n## Parameters to Main\n\nThe `Main` method may take an array of strings as parameter, as in example\n[print_param/print_param.cs](https://github.com/mstbit/introcs-csharp-examples/blob/master/print_param/print_param.cs):\n\n```{literalinclude} ../../examples/print_param/print_param.cs\n:dedent: 3\n:end-before: chunk\n:start-after: chunk\n```\n\nBy convention, the formal parameter for `Main` is called `args`,\nshort for arguments.\n\nCompile (`dotnet build`) and run (`dotnet run`) the program from the command line.\nRun it with some things at the end of the line in `macOS` like:\n\n``` none\n[username]@[computer]:~/workspace/introcscs/Ch08Arrays$ dotnet run hi there 123\n```\n\nor in `Windows` like:\n\n``` none\nPS C:\\Users\\[username]\\workspace\\introcscs\\Ch08Arrays> dotnet run hi there 123\n```\n\nand it should print for you:\n\n``` none\nThere are 3 command line parameters.\nhi\nthere\n123\n```\n\nSee what quoted strings do. Use command line parameters (with the quotes)\n`\"hi there\" 123`. This should print for you:\n\n    There are 2 command line parameters.\n    hi there\n    123"
  },
  {
   "cell_type": "markdown",
   "id": "b0ca1d4b",
   "metadata": {},
   "source": "(command-line-adder-exercise)=\n\n### Command Line Adder\n\nA code block in the Main method of your project that calculates and prints\nthe sum of three command line parameters taken from user input:\n\n    2 5 22\n\nthen the program prints 29.\n\nThe code could look like this:\n\n    ////////// args array from command line.\n    int sum = 0;\n    for (int i = 0; i < args.Length; i++)\n    {\n          sum = sum + int.Parse(args[i]);\n    }\n    Console.WriteLine(sum);\n\nHere we are using the `arg` array directly just like the preceding section.\n\nTo run the code this time, go down to your project’s bin/Debug/net8.0 directory\nfrom the command line, and run `ls`. You will find the executables (the `.dll` or `.exe`\nfiles) that you can execute. In `Windows`, it should look like:\n\n``` none\nPS C:\\Users\\[username]\\workspace\\introcscs\\Ch08Arrays\\bin\\Debug\\net8.0> Ch08Arrays.exe 2 5 22\n```\n\nand you will see the output. You can also run the project by issuing:\n\n``` none\nPS C:\\Users\\[username]\\workspace\\introcscs\\Ch08Arrays> dotnet run 2 5 22\n```\n\nas before to see the same output. In earlier version of `macOS`, you run this\nwith `dotnet run` in your project folder at command line with the arguments:\n\n``` none\n[username]@[computer]:~/workspace/introcscs/Ch08Arrays$ dotnet run 2 5 22\n```\n\nor in more current versions of `macOS`:\n\n``` none\n[username]@[computer]:~/workspace/introcscs/Ch08Arrays/bin/Debug/net8.0$ dotnet Ch08Arrays.dll 2 5 22\n```\n\nand you will see the output of the sum of the integers.\n\nJust like the preceding section, this shows that the `string[] args` in the Main method is a `string array` taking its\nelements from the command line when the project is executed in the command line with arguments provided.\n\nAlso, this code execution shows us the location of the executable files in the project.\n\n```{index} string; Split Split method for strings\n```\n\n(split)=\n\n% String Method Split\n\n% ———————\n\n% A string method producing an array:\n\n% `string[] Split(char` **separator** `)`\n\n% Returns an array of substrings from *this* string. They are the pieces left\n\n% after chopping out the separator character from the string.\n\n% A piece may be the empty string.\n\n% Example:\n\n% .. code-block:: none\n\n% \\> var fruitString = “apple pear banana”;\n\n% \\> string\\[\\] fruit = fruitString.Split(’ ’);\n\n% \\> fruit;\n\n% { “apple”, “pear”, “banana” }\n\n% \\> fruit\\[1\\];\n\n% “pear”\n\n% \\> var s = ” extra spaces “;\n\n% \\> s.Split(’ ’);\n\n% { ““,”“,”extra”, ““,”“,”spaces”, “” }\n\n% Note: The response with the list in braces is a purely *csharprepl* convention for displaying\n\n% sequences for the user. There is no corresponding string displayed by C# Write commands.\n\n% Also see that the string is split at *each* `separator`,\n\n% even if that produces empty strings.\n\n% .. index:: IntsFromString1\n\n% index; parallel arrays\n\n% .. \\_ints_from_string1:\n\n% `Split` is useful for parsing a line with several parts. You might get a group of\n\n% integers on a line of text, for instance from::\n\n% string input = UI.PromptLine(\n\n% “Please enter some integers, separated by single spaces:”);\n\n% To extract the numbers, you want to the separate the entries in the string\n\n% with `Split`, *and* you probably want further processing:\n\n% If you want them as integers, not strings, you must convert each one separately.\n\n% It is useful to put this idea in a function.\n\n% See the type returned. It is an array `int[]` for the int results::\n\n% /// Return ints taken from space separated integers in a string.\n\n% public static int\\[\\] IntsFromString1(string input)\n\n% {\n\n% string\\[\\] integers = input.Split(’ ’);\n\n% int\\[\\] data = new int\\[integers.Length\\];\n\n% for (int i=0; i \\< data.Length; i++)\n\n% data\\[i\\] = int.Parse(integers\\[i\\]);\n\n% return data;\n\n% }\n\n% In a call to `IntsFromString1(\"2 5 22\")`, `integers` would be\n\n% an array containing strings `\"2\"`, `\"5\"`, and `\"22\"`.\n\n% We need the conversions to `int` to go in a new array that we call `data`.\n\n% We must set its length, which will clearly be the same as for `integers`,\n\n% `integers.Length`.\n\n% To assign elements into `data` we need a loop providing indices,\n\n% like the `for` loop provided. Then for each index, we parse a\n\n% string in `integers` into an `int`,\n\n% and place the `int` in the corresponding location in `data`. We need to return\n\n% `data` at the end to make it accessible to the caller.\n\n% Again we use the basic pattern for returning an array.\n\n% Dealing with arrays is hard for many students for several reasons:\n\n% \\* You have new array declaration and creation syntax.\n\n% \\* Array are compound objects, so there is a lot to think about.\n\n% \\* Loops are hard for many people, and you almost always deal with loops.\n\n% \\* You usually must deal with index variables, and there are many\n\n% patterns.\n\n% The last point is significant,\n\n% so it is important to note the special pattern in the example above:\n\n% .. note::\n\n% The use of the same index variable for more than one array is\n\n% a standard way to have\n\n% *related* entries in *corresponding* positions in the arrays.\n\n% We will introduce a refinement of this function in the\n\n% :ref:`intsfromstring_exercise`. It will rely on a more complicated\n\n% index-handling pattern."
  },
  {
   "cell_type": "markdown",
   "id": "18a73707",
   "metadata": {},
   "source": "```{index} alias\n```\n\n(alias)=\n\n## References and Aliases\n\nObject variables, like arrays, are references,\nand this has important implications for\nassignment.\n\nWith a primitive type like an `int`, an assignment copies the data:\n\n`{image} ../../images/intCopy.png :align: center :alt: copying an int :width: 90 pt`\n\nIn the diagram, the contents of the memory box labeled `b` is copied to the\nmemory box labeled `d`. The value of `d` starts off equal to the value of `b`,\nbut can later be changed independently.\n\nContrast an assignment with arrays. The value that is copied is the *reference*,\nnot the array data itself, so both end up pointing at the *same* actual array:\n\n`{image} ../../images/arrayAlias.png :align: center :alt: copying an array reference :width: 300 pt`\n\nHereafter, array assignments like:\n\n    b[2] = -10;\n    d[1] = 55;\n\nwould both change the *same* array. Now `b` and `d` are essentially\nnames for the same thing (the actual array). The technical term matches English:\nThe names are *aliases*.\n\nThis may seem like a pretty silly discussion. Why bother to give two different\nnames to the same object? Isn’t one enough? In fact it is very important\nin function/method calls. An array reference can be passed as an actual value,\nand it is the array *reference* that is copied to the formal parameter, so\nthe formal parameter name is an **alias** for the actual parameter name.\n\nIf an array passed as a parameter to a method has elements changed in the\nmethod, then the change affects the actual parameter array.\nThe change *remains* in the actual parameter array *after*\nthe method has terminated.\n\n```{index} array; Scale example\n```\n\nFor example, consider the following function:\n\n    // Modify a by multiplying all elements by multiplier.\n    static void Scale(int[] a, int multiplier)\n    {\n       for (int i = 0; i < a.Length; i++) {\n          a[i] *= multiplier;  // or:  a[i] = a[i] * multiplier\n       }\n    }\n\nThe fragment:\n\n    int[] nums = {2, 4, 1};\n    Scale(nums, 5);\n\nwould *change* nums, so it ends up containing elements 10, 20, and 5."
  },
  {
   "cell_type": "markdown",
   "id": "6632864b",
   "metadata": {},
   "source": "```{index} OOP; default value\n```\n\n(default-fields)=\n\n## Default Initializations\n\nDid you notice that when the first example array of integers was created,\nit was filled with zeros? It is a safety feature of C# that the internal fields\nof objects always get a specific value, not random data. Here are the defaults:\n\n\\`\\`\\`{eval-rst}\n.. csv-table:: Default Values\n:header: “Type”, “Value”\n:widths: 30, 10\n\n    \"primitive numeric types\", \"0\"\n    \"bool\", \"false\"\n    \"all object types\", \"null\"\n\n\n    :::{warning}\n    An array with elements of object type, like `string[]`,\n    without a specific initializer,\n    gets initialized to all `null` values. The creation is totally\n    legal, but if you try to use the created value, like\n\nstring\\[\\] words = new string\\[10\\];\nConsole.WriteLine(words\\[0\\].Length); // run time error here\n\n\n    The error is because `null` is not an object - it does not have a `Length`\n    property. If, for example,\n    you want an array of empty strings you would need to initialize it with\n    a loop:\n\nstring\\[\\] words = new string\\[10\\];\nfor (int i = 0; i \\< words.Length; i++) {\nwords\\[i\\] = ““;\n}\n\n    :::\n\n    ## LINQ Methods\n\n\n    :::{note}\n    Language-Integrated Query ([LINQ](https://learn.microsoft.com/en-us/dotnet/csharp/linq/)) is the name for a set of technologies based\n    on the integration of query capabilities directly into the C# language.\n    :::\n\n    All the arrays in C# are derived from an abstract base class [System.Array](https://learn.microsoft.com/en-us/dotnet/api/system.array?view=netframework-4.7.2).\n    The Array class implements the `IEnumerable interface`, so you can LINQ\n    extension methods such as Max( ), Min( ), Sum( ), reverse( ), etc on arrays:\n\nint\\[\\] nums = new int\\[5\\]{ 10, 15, 16, 8, 6 };\n\nnums.Max(); // returns 16\nnums.Min(); // returns 6\nnums.Sum(); // returns 55\nnums.Average(); // returns 55\n\n\n    ```{rubric} Footnotes\n\n[1] See [Arrays](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/arrays) in Microsoft Langauge Reference.\n\n[2] See [C# Arrays](https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-arrays/cheatsheet) of codeacademy."
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}