0% found this document useful (0 votes)
29 views6 pages

04 Handout

An array is a collection of elements of the same type that can be accessed using an integer index. Arrays allow storing multiple values in a variable without declaring separate variables. One-dimensional arrays store elements in a list, while two-dimensional arrays arrange elements in rows and columns accessed by two indices. The ArrayList class provides a dynamic array that can increase in size. Strings represent text as sequential characters that can be initialized from literals or character arrays.

Uploaded by

No Thanks
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views6 pages

04 Handout

An array is a collection of elements of the same type that can be accessed using an integer index. Arrays allow storing multiple values in a variable without declaring separate variables. One-dimensional arrays store elements in a list, while two-dimensional arrays arrange elements in rows and columns accessed by two indices. The ArrayList class provides a dynamic array that can increase in size. Strings represent text as sequential characters that can be initialized from literals or character arrays.

Uploaded by

No Thanks
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

IT1907

Arrays
An array is a set of fixed number of values called elements that can be accessed using integer index. Elements on an array are
of the same data type. Indices in an array starts at 0. An array is used to store multiple values of the same data type at a time
without declaring a different variable name for each value. Array elements can be of any data type.
One-Dimensional Arrays
A one-dimensional array is an array in which all elements are arranged like a list. In C#, arrays are implemented as objects. To
define an array, declare a variable first that refers to an array, followed by creating an instance of the array through the new
operator. The following general syntax defines a one-dimensional array:
data_type[] array_name = new data_type[array_size];
The data_type refers to the type of data that will be stored in the array, and the array_size in square brackets specifies the
fixed number of elements can be stored in the array. The new operator creates the array and initializes the array elements to
their default values. The following example of one-dimensional array that can store 10 integers and all the array elements are
initialized to zero:
int[] numbers = new int[10];
The following example shows how to assign values to individual array elements by using an index number:
numbers[0] = 45;
numbers[4] = 23;
The example below shows how to initialize an array upon declaration:
double[] grades = { 2.50, 2.75, 1.25, 5.0, 1.50 };
In the given example, the declared array grades is initialized with five (5) values placed between braces and separated by
commas. Array elements can be accessed by using index number. The following example accesses the element of arraygrades
by placing the index of the element on the square brackets after the name of the array. It gets the array element of index 1
which is 2.75 then copies its value and stores it on the variable studentGrade:
double studentGrade = grades[1];
Console.WriteLine(studentGrade); //prints 2.75

The foreach statement in C# is used to process the elements of an array starting with index 0 up to the ending index. This
iterates through each item of the array. The following example shows how to use a foreach statement to access the all the
elements of the array grades:
foreach (double grade in grades)
{
Console.Write(grade + " / ");
}
Output:
2.5 / 2.75 / 1.25 / 5 / 1.5 /

In the given example of foreach loop, the in keyword is used to iterate over the elements of the array. This gets an item from
the array on each iteration and stores in on the declared variable—in the given example—grade. The number of times the
foreach loop will execute is equal to the number of elements in the array. In the given example, the foreach loop iterates
five (5) times.
Two-Dimensional Arrays
In a two-dimensional array, the array elements are arranged in rows and columns. The elements in this array are arranged in a
tabular form and are therefore stored and accessed by using two (2) indices: one (1) index refers to the row, and the other
refers to the column location. The following is the general syntax for defining a two-dimensional array:
data_type[,] array_name = new data_type[row_size, col_size];

The code data_type[,] defines the two-dimensional array being defined. The row_size and col_size refer to the number
04 Handout 1 *Property of STI
[email protected] Page 1 of 3
IT1907
of rows and columns in the array, respectively. The following example defines a two-dimensional array consisting of two (2)
rows and four (4) columns:
int[,] table = new int[2, 4];
The example below shows how to assign values to individual array elements by specifying the row and column numbers:
table[0, 1] = 18;
table[1, 3] = 4;
The following example shows how to initialize a two-dimensional array upon declaration:
int[,] table = {
{ 2, 3 },
{ 12, 5},
{ 3, 8 },
{ 18, 3 }
};
The following shows how to access the element of a two-dimensional array:
Console.WriteLine(table[3, 0]); //this prints the 18

The ArrayList Class


The ArrayList class in C# is a collection that behaves as a dynamic array where the array size can dynamically increase as
required. The ArrayList class is defined in the System.Collections namespace. The following is the general syntax for
defining an array list. (*Note: The namespace System.Collections must be declared first in order to use the ArrayList class.)
ArrayList name_of_list = new ArrayList();
The following example shows how to create an ArrayList:
ArrayList nameList = new ArrayList();
The Add() method is used to add an element to the list. The following is the example of adding elements on the ArrayList
named nameList:
nameList.Add("Jack Paul");
nameList.Add("Adrian Castro");
nameList.Add("Peter Cruz");
nameList.Add("Angela Cruz");
The elements of an ArrayList can be accessed by specifying an integer index. For example:
Console.WriteLine(nameList[2]); //this will print Peter Cruz
The foreach loop is used to process all the elements of an ArrayList. For example:
foreach (string name in nameList)
{
Console.Write(name + ", ");
}
Output:
Jack Paul, Adrian Castro, Peter Cruz, Angela Cruz,

REFERENCES:
Deitel, P. and Deitel, H. (2015). Visual C# 2012 how to program (5th Ed.). USA: Pearson Education, Inc.
Gaddis, T. (2016). Starting out with visual C# (4th Ed.). USA: Pearson Education, Inc.
Harwani, B. (2015). Learning object-oriented programming in C# 5.0. USA: Cengage Learning PTR.

04 Handout 1 *Property of STI


[email protected] Page 2 of 3
IT1907

Strings
Strings
A string is a sequential collection of characters that is used to represent text. In C#, a string is an object of class string in the
System namespace.
In C#, a string variable can be initialized by using either of the following:
• directly assigning a string literal; or
• using the new keyword and calling the String class constructor.
The most commonly used method for creating a string object is by assigning a string literal to a string variable. The following
example use assignment operator to assign the string literal to a string variable:
string strMessage = "Welcome to this course!";
string strPath = @"C:\Documents\Report.docx";
In the given example, the backslash (\) is used to escape characters with special use, such as newline (\n). The '@' symbol before
the string literal is used to ignore the special use of backslashes.
Calling the String class constructor is the other method used to create a string object in C#. The following statements show
an example of how to use new keyword and String class constructor:
char[] word = { 'H', 'e', 'l', 'l', 'o', '!' };
string strGreet = new string(word);
In the given example, the String class constructor is used to create a string from an array of characters named word. Note
that in C#, there is no String class constructor that takes a string literal as an argument. The String constructors in C# only
creates a string from characters and arrays.
The String class has two (2) properties that can be used to get some information of the string and can be used to manipulate
strings. The following are the properties of the String class:
• char – This property is used to get the character at a specified index position of a string. For example:
string word = "Computer";
char letter = word[2];
//the value of variable letter is character 'm'
• Length – This property is used to get the total number of characters in the string. For example:
string word = "Computer";
int total = word.Length;
//the value of variable total is 8
The String class provides several methods that are used to perform operations on strings. Table 1 shows some of the methods
of String class in C#.
Table 1. Methods in the class String (Harwani, 2015)
Method Description
This returns true if the specified substring occurs within the string object; otherwise, it returns false.
bool
Contains(string For example:
value) string sentence = "The quick brown fox jumps.";
bool doesContain = sentence.Contains("fox"); //returns true
This determines whether the specified substring has the same value with the string object. The
comparisonType parameter specifies the rules to use in comparing strings, such as ignoring the case
bool version of the characters.
Equals(string Example 1:
value, string word = "Computer";
StringComparison bool isSame = word.Equals("computer", StringComparison.CurrentCulture); //this
comparisonType) returns false
Example 2:
string word = "Computer";

04 Handout 2 *Property of STI


[email protected] Page 1 of 4
IT1907
Method Description
bool isSame = word.Equals("computer", StringComparison. CurrentCultureIgnoreCase);
//this returns true
This returns the index position value of the first occurrence of the specified character within the string
int IndexOf(char object if that character is found; otherwise, it returns -1 if not found. For example:
value) string word = "Computer";
int index = word.IndexOf('p'); //returns 3
string This returns a copy of the string object except that all of the occurrences of an old character are replaced
Replace(char with a new character. For example:
oldValue, char string word = "Color";
newValue) string strChanged = word.Replace('o', '#'); //returns a copy of string "C#l#r"
This returns a converted copy of object as a string. For example:
string
ToString() double value = 105.25;
string strValue = value.ToString(); //converted 105.25 into string
This returns a copy of the string object converted to lowercase. For example:
string ToLower() string word = "COMPUTER";
string strConverted = word.ToLower(); //returns a copy of string "computer"
This returns a copy of the string object converted to uppercase. For example:
string ToUpper() string word = "computer";
string strConverted = word.ToUpper(); //returns a copy of string "COMPUTER"
The String class methods only create a copy of the string object and return a new string containing the result of the method
operation.
Strings are immutable. This means that when a string object is created, its contents cannot be changed. Every instance of a
string that has been modified is actually creating a new string in the computer’s memory. For example:
string strComputer = "Computer";
strComputer = strComputer + " is a great invention.";

Figure 1. Memory allocation for String class


In Figure 1, the variable strComputer will allocate a space in the memory with the string "Computer". When the content
of this variable is modified by concatenating the string "is a great invention.", the compiler will allocate new
memory space for the modified string instead of modifying the initial string at the same memory address. This behavior will
delay the performance of the application if the same string is modified multiple times.
To solve this problem, C# provides the StringBuilder class that represents a mutable string of characters.

04 Handout 2 *Property of STI


[email protected] Page 2 of 4
IT1907
The StringBuilder Class
The StringBuilder class represents a mutable string of characters that allows the user to expand the number of characters in
the string object without allocating additional memory space.
The following shows the way of creating a string using the StringBuilder class and using the new keyword and
StringBuilder constructor:
StringBuilder strComputer = new StringBuilder("Computer");
The following syntax shows how to use Append() method to concatenate a string to the string object of StringBuilder
class. The example below will return the string "Computer is a great invention.".
strComputer.Append(" is a great invention.");
Figure 2 shows how a StringBuilder class allocates a memory space when modifying a string object.

Figure 2. Memory allocation for StringBuilder class


In the figure, the content "Computer" of the object strComputer of StringBuilder class is allocated to a memory space.
When the Append() method is used to modify the content of the StringBuilder object, the content "Computer is a
great invention." is allocated to the same memory address.
The StringBuilder class also contains two (2) main properties that can get and manipulate the information on a string.These
properties are char and Length. The following example shows how to use these properties:
StringBuilder word = new StringBuilder("Computer");
word[0] = '#'; //changes the character at index 0 to '#'
for (int index = 0; index < word.Length; index++) {
Console.Write(word[index] + " + "); //gets the character at the specified index
}

Output:
# + o + m + p + u + t + e + r +

04 Handout 2 *Property of STI


[email protected] Page 3 of 4
IT1907
The StringBuilder class contains useful methods that can be used to perform operations on the content of the
StringBuilder object. Table 2 lists some of the methods of StringBuilder class.
Table 2. Some methods in the class String (Harwani, 2015)
Method Description
This appends a copy of the specified substring to the StringBuilder object. For
Append(string value)
example:
StringBuilder word = new StringBuilder("Computer");
word.Append(" Ethics"); //returns the string "Computer Ethics"
This returns true if the specified substring is equal to the StringBuilder object;
otherwise, it returns false. For example:
Equals(string value) StringBuilder wordA = new StringBuilder("computer");
StringBuilder wordB = new StringBuilder("computer");
wordA.Equals(wordB); //returns true because both havesame content
This removes all characters from the current StringBuilder object. For example:
StringBuilder word = new StringBuilder("Computer");
Clear()
word.Clear();
word.Append("Ethics"); //returns only the string "Ethics"
This replaces all occurrences of a specified old character of the StringBuilder object
Replace(char oldValue, char with a new character. For example:
newValue) StringBuilder word = new StringBuilder("Color");
word.Replace('o', '*'); //returns the string "C*l*r"
This converts the value of the StringBuilder object to a string. For example:
ToString() StringBuilder word = new StringBuilder("computer");
string strWord = word.ToString();

REFERENCES:
Deitel, P. and Deitel, H. (2015). Visual C# 2012 how to program (5th Ed.). USA: Pearson Education, Inc.
Gaddis, T. (2016). Starting out with visual C# (4th Ed.). USA: Pearson Education, Inc.
Harwani, B. (2015). Learning object-oriented programming in C# 5.0. USA: Cengage Learning PTR.
04 Handout 2 *Property of STI
[email protected] Page 4 of 4

You might also like