CPP225
Object Oriented
Programming I
Arrays
Öğr. Gör.
İhsan Can İÇİUYAN
2 Object Oriented Programming
Contents
Arrays
Initializing Arrays
Implicitly Typed Arrays
Array of Objects
Multidimensional Arrays
Passing and Receiving Arrays
System.Array Class
Indices and Ranges
3 Object Oriented Programming
Arrays
Array → a set of contiguous data points of the same type
Elements are accessed using a numerical index.
Consider the following example:
// Create an array of 3 integers
int[] myInts = new int[3];
// Create a 100 item string array, indexed 0 - 99
string[] myStrings = new string[100];
The number used in the array declaration represents the total
number of items, not the upper bound.
The lower bound of an array always begins at 0.
4 Object Oriented Programming
Arrays
You can fill the array elements index by index:
// Create and fill an array of 3 integers
int[] myInts = new int[3];
myInts[0] = 100;
myInts[1] = 200;
myInts[2] = 300;
// Now print each value
foreach (int i in myInts)
{
Console.WriteLine(i);
}
If you declare an array but do not explicitly fill each index,
each item will be set to the default value of the data type.
5 Object Oriented Programming
Initializing Arrays
You can fill the items of an array using array initialization syntax.
You can specify each array item within the curly brackets:
int[] intArray = new int[4] { 20, 22, 23, 0 };
When you initialize an array, you do not need to specify the size of
the array:
string[] stringArray = new string[] { "one", "two", "three" };
The size of the array will be inferred by the number of items within
the curly brackets.
When you initialize an array, the use of the new keyword is optional:
bool[] boolArray = { false, false, true };
6 Object Oriented Programming
Initializing Arrays
If there is a mismatch between the declared size and the number
of initializers, you are issued a compile-time error.
Consider the following example:
int[] intArray = new int[2] { 20, 22, 23, 0 };
Since there are more initializers than the size of the array, the
compiler will issue an error.
Consider the following example:
int[] intArray = new int[4] { 20, 22 };
Since there are fewer initializers than the size of the array, the
compiler will issue an error.
7 Object Oriented Programming
Implicitly Typed Arrays
The var keyword can be used to define implicitly typed arrays.
You must use the new keyword when using this approach.
// a is really int[]
var a = new[] { 1, 10, 100, 1000 };
// b is really double[]
var b = new[] { 1, 1.5, 2, 2.5 };
// c is really string[]
var c = new[] { "hello", null, "world" };
The items in the array’s initialization list must be of the same type.
Thus, the following generates a compile-time error:
var d = new[] { 1, "one", 2, "two", false };
8 Object Oriented Programming
Array of Objects
System.Object is the ultimate base class to every type.
If you were to define an array of System.Object data types, the
subitems could be anything at all:
// An array of objects can be anything at all
object[] myObjects = new object[4];
myObjects[0] = 10;
myObjects[1] = false;
myObjects[2] = new DateTime(2024, 12, 20);
myObjects[3] = "Hello World!";
foreach (object obj in myObjects)
{
// Print the type and value for each item in array
Console.WriteLine("Type: {0}, Value: {1}", obj.GetType(), obj);
}
9 Object Oriented Programming
Multidimensional Arrays
C# supports two varieties of multidimensional arrays:
Rectangular array
Jagged array
10 Object Oriented Programming
Multidimensional Arrays
Rectangular array → an array of multiple dimensions, where each
row is of the same length
You can declare and fill a rectangular array as follows:
// A rectangular array
int[,] myMatrix;
myMatrix = new int[3, 4];
// Populate (3 * 4) array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
myMatrix[i, j] = i * j;
}
}
11 Object Oriented Programming
Multidimensional Arrays
Jagged array → contains some number of inner arrays, each of
which may have a different upper limit
You can declare a jagged array as follows:
// A jagged array
// Here we have an array of 5 different arrays
int[][] myJagArray = new int[5][];
// Create the jagged array
for (int i = 0; i < myJagArray.Length; i++)
{
myJagArray[i] = new int[i + 7];
}
12 Object Oriented Programming
Multidimensional Arrays
You can access the elements of a jagged array as follows:
// Print each row
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < myJagArray[i].Length; j++)
{
Console.Write(myJagArray[i][j] + " ");
}
Console.WriteLine();
}
Remember that if you do not initialize the array, each element is
defaulted to zero (if the elements are numeric values).
13 Object Oriented Programming
Passing and Receiving Arrays
After you have created an array, you are free to
pass it as an argument
receive it as a return value
The following method takes an incoming array of ints and prints
each member to the console:
static void PrintArray(int[] myInts)
{
for (int i = 0; i < myInts.Length; i++)
{
Console.WriteLine("Item {0} is {1}", i, myInts[i]);
}
}
14 Object Oriented Programming
Passing and Receiving Arrays
The following method populates an array of strings and returns it
to the caller:
static string[] GetStringArray()
{
string[] theStrings = { "Hello", "from", "World" };
return theStrings;
}
These methods may be invoked as follows:
// Pass array as parameter
int[] ages = { 20, 22, 23, 0 };
PrintArray(ages);
// Get array as return value
string[] strs = GetStringArray();
foreach (string s in strs)
Console.WriteLine(s);
15 Object Oriented Programming
System.Array Class
Every array you create gathers much of its functionality from the
System.Array class.
Following table gives some of the more interesting members of the
System.Array class.
16 Object Oriented Programming
System.Array Class
EX: A program that makes use of the static Reverse() and Clear()
methods to print out information about an array of string types.
Code: 57_ArrayClass.cs
Output:
-> Here is the array:
Object Oriented Programming, Data Structures, Introduction to Algorithms,
-> The reversed array:
Introduction to Algorithms, Data Structures, Object Oriented Programming,
-> Cleared out all but one...
Introduction to Algorithms, , ,
NB: Many members of System.Array are defined as static members
and are, therefore, called at the class level.
17 Object Oriented Programming
Indices and Ranges
C# provides two types and two operators for use when working with
arrays:
System.Index → represents an index into a sequence
System.Range → represents a subrange of indices
Index from end operator (^) → specifies that the index is relative
to the end of the sequence
Range operator (..) → specifies the start and end of a range as
its operands
18 Object Oriented Programming
Indices and Ranges
Arrays are indexed beginning with zero (0).
The end of a sequence is the length of the sequence – 1.
Consider the following example:
string[] courses = { "OOP", "Data Structures", "Algorithms" };
for (int i = 0; i < courses.Length; i++)
{
Index idx = i;
Console.Write(courses[idx] + ", ");
}
19 Object Oriented Programming
Indices and Ranges
Index from end operator (^) → lets you specify how many positions
from the end of sequence, starting with the length
The following code prints the array in reverse:
string[] courses = { "OOP", "Data Structures", "Algorithms" };
for (int i = 1; i <= courses.Length; i++)
{
Index idx = ^i;
Console.Write(courses[idx] + ", ");
}
The last item in a sequence is one less than the actual length,
so ^0 would actually cause an error.
20 Object Oriented Programming
Indices and Ranges
Range operator (..) → specifies a start and end index, and allows
for access to a sub-sequence within a list
The start of the range is inclusive,
The end of the range is exclusive.
To pull out the first two members of the array, create ranges from 0
(the first member) to 2 (one more than the desired index position):
string[] courses = { "OOP", "Data Structures", "Algorithms" };
foreach (var itm in courses[0..2])
{
Console.Write(itm + ", ");
}
21 Object Oriented Programming
Indices and Ranges
Ranges can also be passed to a sequence using the Range data
type:
Range r = 0..2; // the end of the range is exclusive
foreach (var itm in courses[r])
{
Console.Write(itm + ", ");
}
Ranges can be defined using integers or Index variables:
Index idx1 = 0;
Index idx2 = 2;
Range r = idx1..idx2; // the end of the range is exclusive
foreach (var itm in courses[r])
{
Console.Write(itm + ", ");
}
22 Object Oriented Programming
Indices and Ranges
If the beginning of the range is left off → the beginning of the
sequence is used
If the end of the range is left off → the length of the range is used
In the following, all of the ranges represent the same subset:
courses[0..3]
courses[0..^0]
courses[..]
23 Object Oriented Programming
References
Arrays, https://learn.microsoft.com/en-us/dotnet/csharp/language-
reference/builtin-types/arrays
Array Class, https://learn.microsoft.com/en-us/dotnet/api/system.array
C# Jagged Array, https://codebuns.com/csharp-intermediate/jagged-
array/
Indices and Ranges, https://learn.microsoft.com/en-
us/dotnet/csharp/tutorials/ranges-indexes
Index Struct, https://learn.microsoft.com/en-us/dotnet/api/system.index
Range Struct, https://learn.microsoft.com/en-us/dotnet/api/system.range
Member access operators, https://learn.microsoft.com/en-
us/dotnet/csharp/language-reference/operators/member-access-
operators
24 Object Oriented Programming
That’s all for
today!