Download presentation
Presentation is loading. Please wait.
1
Visual Programming COMP-315
Chapter #4 Arrays & String
2
Arrays An array stores multiple elements of the same type
that type can be simple (value) types or objects for arrays of simple types, each element contains one value of the declared type for arrays of reference types (e.g., objects), every element of the array is a reference to an object of the data type of the array Refer to particular element in the array by position number the name of the array followed by the position number (subscript) of the element in square brackets ([]) [ ] is considered as an operator
3
Arrays: Declaration and Instantiation
An array can be allocated using the keyword new to specify how many elements the array should hold bool[] flags; // declare flags flags = new bool[20]; // create an array and make flags a ref. // now flags is reference to another array flags = new bool[10]; // declare variable grades; create an array; make grades a // reference of the array int[] grades = new int[12]; float[] prices = new float[500]; string[] codes = new string[26]; Time1[] times; times = new Time1[10];
4
Array: An Array of Simple Values
grades[ 0 ] -45 6 72 1543 -89 62 -3 1 6453 -78 grades[ 1 ] grades[ 2 ] grades grades[ 3 ] grades[ 4 ] grades[ 5 ] grades[ 6 ] grades[ 7 ] position number (index or subscript) of the element within array grades grades[ 8] grades[ 9 ] grades[ 10 ] grades[ 11 ] A 12-element array of values.
5
Array: An Array of Objects
times[ 0 ] ref to obj 0 times[ 1 ] ref to obj 1 times[ 2 ] ref to obj 2 times times[ 3 ] ref to obj 3 times[ 4 ] ref to obj 4 times[ 5 ] ref to obj 5 times[ 6 ] ref to obj 6 times[ 7 ] ref to obj 7 position number (index or subscript) of the element within array times times[ 8] ref to obj 8 times[ 9 ] ref to obj 9 A 10-element array of objects
6
Arrays as Objects In C#, an array behaves very much like an object
declaration and instantiation are like objects declare an array variable create an array using new make a variable a reference of an array parameter passing is similar to objects we will discuss the detail later. an array has the Length property
7
Array: Length Each array has a public property called Length that stores the size of the array once an array is created, it has a fixed size It is referenced using the array name (just like any other object): grades.Length Note that Length holds the number of elements, not the largest index
8
Array and Bound An index used in an array reference must specify a valid element That is, the index value must be in bounds (0 to N-1), where N is the length For example, if the array grades can hold 12 values, it can only be indexed using the numbers 0 to 11 problem for (int index=0; index <= grades.Length; index++) scores[index] = index*50 + epsilon; It’s common to introduce off-by-one errors when using arrays
9
Array Instantiation and Initialization in One Step: Initializer List
An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Allocate space for the array – number of elements in initializer list determines the size of array Elements in array are initialized with the values in the initializer list The new operator is not used Examples: int[] units = {147, 323, 89, 933, 540}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'}; string[] wordList = {“cs112“, “computer", “television"};
10
Command-Line Arguments
The signature of the Main method indicates that it takes an array of string as parameter These values come from command-line arguments that are provided when the program is invoked For example, the following invocation of the interpreter passes an array of three string objects into Main: C:\> Calculator 2 + 3 These strings are stored at positions 0-2 of the parameter
11
strings as Arrays You can use a string as an array
You can access the length of a string using the Length property You can access each character of a string using [ ], e.g., string resp = Console.ReadLine().ToUpper(); for (int i = 0; i < resp.Length; i++) Console.Write( resp[i] );
12
Two Types of Variables A variable represents a cell in memory
Value type int, char, byte, float, double, string A value type variable stores a value of the type of the variable in the memory int x = 45; double y = 45.12; Reference type A variable that “stores” object or array actually stores a reference to an object or array, e.g., A reference is a location in computer’s memory where the object or array itself is stored Time3 t1; t1 = new Time3(11, 45, 59); x 45 y 45.12 t1 11 45 59
13
Implications of the Two Types of Variables: Assignment
An assignment of one value variable to another value variable copies the value, e.g., int x = 45; double y = 45.12; int z; z = x; An assignment of one reference variable to another reference variable copies the reference, e.g., Time3 t1; t1 = new Time3(11, 45, 59); Time3 t2; t2 = t1; x 45 y 45.12 z 45 t1 11 45 59 t2
14
Implications of the Two Types of Variables: Change
Change the value of one value variable will not change the other: int x = 45; double y = 45.12; int z; z = x; x = 23; Change the content (state) by one reference may affect another reference variable Time3 t1; t1 = new Time3(11, 45, 59); Time3 t2; t2 = t1; t2.SetTime(22, 22, 22); x 23 45 y 45.12 z 45 t1 22 11 45 59 t2
15
Passing Arguments by Value and by Reference
Passing a value type argument to methods The value of an actual argument is copied to the formal argument The formal argument has its own memory location Any changes to the formal argument in the method do not affect the actual argument Passing a reference type argument to methods A copy of the reference to the object/array is made to the formal argument Any changes to the contents of the object/array in the method, do affect the object/array outside the method Because both the formal argument and the actual argument are reference to the same object/array
16
Calling a Method Each time a method is called, the actual arguments in the invocation are copied into the formal arguments If a value type, it is the value that is copied If a reference type, it is the reference that is copied int num = SquareSum (2, 3); static int SquareSum (int num1, int num2) { num1 = num1 + num2; return num1 * num1; } num1 5 2 num2 3
17
Calling a Method: Value Type
Even if formal arguments and actual arguments have the same name, modifications to formal arguments in a method will not affect actual arguments num1 2 int num1 = 2; int num2 = 3; num2 3 int num = SquareSum (num1, num2); static int SquareSum (int num1, int num2) { num1 = num1 + num2; return num1 * num1; } num1 2 5 num2 3
18
Calling a Method: Using ref/out
If an argument of a method is ref (or out), then the formal argument and the actual argument are aliases of each other, i.e. they share the same memory cell n1 5 2 int n1 = 2; n2 3 int n2 = 3; num 25 int num = SquareSum (ref n1, ref n2); static int SquareSum (ref int num1, ref int num2) { num1 = num1 + num2; return num1 * num1; }
19
Calling a Method: Side Effect of Reference
If an argument is a reference type, then modifying the content/state of the array/object through the reference will have side effect int[] array = {1, 2, 3}; array DoubleArray (array); 1 2 3 2 4 6 static void DoubleArray (int[] array) { for (int i = 0; i < array.Length; i++) array[i] *= 2; } array i
20
Arrays as Parameters: Summary
If an argument of a method is an array, a reference to a array is passed to the method Changing an array element in the method changes the original An array element can be passed to a method as well, and follow the parameter passing rules of that element's type
21
Two-Dimensional Arrays
A one-dimensional array stores a list of values A two-dimensional array, also called double-subscripted array, can be thought of as a table of values, with rows and columns a two-dimensional array element is referenced using two index numbers
22
Two Types of Double-Subscripted Arrays
rectangular arrays often represent tables in which each row is the same size and each column is the same size, e.g., int[,] a1 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; int[,] a11 = new int[3,4]; jagged arrays arrays of arrays arrays that compose jagged arrays can be of different lengths, e.g., int[][] array2 = new int[ 3 ][]; array2[ 0 ] = new int[] { 1, 2 }; array2[ 1 ] = new int[] { 3 }; array2[ 2 ] = new int[] { 4, 5, 6 }; array2[2][1] = 3;
23
Double-Subscripted Arrays
Column 0 Column 1 Column 2 Column 3 Row 0 a[0][0] a[0][1] a[0][2] a[0][3] Row 1 a[1][0] a[1][1] a[1][2] a[1][3] Row 2 a[2][0] a [2][1] a[2][2] a[2][3] Column index (or subscript) Row index (or subscript) Array name Double-subscripted array with three rows and four columns.
24
Class String A string is essentially an encapsulation of an array of characters since we use string so often, C# defines the string class and provides many methods (behaviors) We have already seen several methods method ToUpper replaces lower case letter original string remains unchanged method ToLower Method Format We will cover some methods; for many other methods, please read chap. 6 of the textbook and the String method link on the lecture-notes page
25
Class String: Creating New Strings
Constructors C# provides eight constructors for initializing strings CopyTo method copies specified number of characters into a char array Substring method extracts a sub string Concat method Combine two strings
26
Class String: Comparison and string Search
Methods CompareTo and Equals uses lexicographical comparison Methods StartsWith and EndsWith Find the position of a char or string IndexOf IndexOfAny LastIndexOf LastIndexOfAny
27
More String Methods Method Trim
removes whitespaces at the beginning and end original string is changed Method Replace Change all occurrences of one char or string with another one original string remains unchanged
28
Class StringBuilder Class StringBuilder
Create and manipulate dynamic string information Capable of resizing
29
Method EnsureCapacity
StringBuilder Indexer, Length and Capacity Properties, and EnsureCapacity Method Method EnsureCapacity Allows programmers to guarantee StringBuilder has capacity that reduces the number of times capacity must be increased Doubles StringBuiler instance’s current capacity Length property returns number of character in StringBuilder Capacity property returns number StringBuilder can store without allocating memory
30
StringBuilder Append and AppendFormat Methods
Append method Allow various data-type values to append to the end of a StringBuilder Convert argument into string AppendFormat method Convert string to a specifiable format
31
StringBuilder Insert, Remove and Replace Methods
Insert method StringBuilder provides 18 overloaded methods Insert into at any position Program may throw ArgumentOutOfRangeException Remove method Takes two argument Replace method Substitute specified string
32
Recap: Class String A string is essentially an encapsulation of an array of characters Since we use string so often, C# defines the string class and provides many methods (see link on the schedule page), e.g., Constructors, CopyTo, Format, Substring, Concat CompareTo, Equals, ==, !=, StartsWith, EndsWith, IndexOf, IndexOfAny, LastIndexOf, LastIndexOfAny ToUpper, ToLower, Trim, Replace, Insert, Split
33
Char Methods For the char value type, there is a Char class
Most methods are static IsLetter IsDigit IsLetterOrDigit IsLower IsUpper ToUpper ToLower IsPunctuation IsSymbol IsWhiteSpace
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.