A Review of Arrays

An Element from Start

We have learned how to create an array of values. After creating an array, you can get elements from it. As we saw in previous lessons, the easiest way to get an item is by using its index, and the indexes are 0, 1, 2, etc. Here are examples:

int[] numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

Console.WriteLine("First:  {0}", numbers[0]);
Console.WriteLine("Second: {0}", numbers[1]);
Console.WriteLine("Third:  {0}", numbers[2]);
Console.WriteLine("===============================");

This would produce:

First:  102
Second: 44
Third:  525
===============================

Press any key to close this window . . .

Mixing Types in an Array

Some languages such as Python allow an array (actually called a list in Python; but a list in C# is different a formal array) to contain various types of values, such as strings and numbers. In C#, all elements must be of the same type. In C#, if you want to mix values, you can create each as a string. After creating the array, to access an element by its type, especially if you want to perform an operation on the element, you must first convent the element to the right type. Here are examples:

string[] employee = { "972950", "Frank", "Palleo", "True", "27.6", "9.00", "8.00", "8.50", "7.50", "9.50" };

bool worksFullTime = bool.Parse(employee[3]);
long emplNbr = long.Parse(employee[0]);
double monday = double.Parse(employee[5]);
double tuesday = double.Parse(employee[6]);
double wednesday = double.Parse(employee[7]);
double thursday = double.Parse(employee[8]);
double friday = double.Parse(employee[9]);
double timeWorked = monday + tuesday + wednesday + thursday + friday;
string emplName = employee[1] + " " + employee[2];
double netPay = double.Parse(employee[4]) * timeWorked;

Console.WriteLine("=========================================");
Console.WriteLine("     - Payroll Preparation -");
Console.WriteLine("=========================================");
Console.WriteLine("Employee Information");
Console.WriteLine("-----------------------------------------");
Console.WriteLine($"Employee #:            {emplNbr}");
Console.WriteLine($"Employee Name:         {emplName}");
Console.WriteLine("Employed Full-Time:    {0}", worksFullTime);
Console.WriteLine($"Hourly Salary:         {double.Parse(employee[4]):f}");
Console.WriteLine("=========================================");
Console.WriteLine("Time Worked");
Console.WriteLine("-----------------------------------------");
Console.WriteLine($"Monday:     {monday,16:f}");
Console.WriteLine($"Tuesday:    {tuesday,16:f}");
Console.WriteLine($"Wednesday:  {wednesday,16:f}");
Console.WriteLine($"Thursday:   {thursday,16:f}");
Console.WriteLine($"Friday:     {friday,16:f}");
Console.WriteLine("-----------------------------------------");
Console.WriteLine($"Total Time: {timeWorked,16:F}");
Console.WriteLine($"Net Pay:    {netPay,16:F}");
Console.WriteLine("=========================================");

This would produce:

=========================================
     - Payroll Preparation -
=========================================
Employee Information
-----------------------------------------
Employee #:            972950
Employee Name:         Frank Palleo
Employed Full-Time:    True
Hourly Salary:         27.60
=========================================
Time Worked
-----------------------------------------
Monday:                 9.00
Tuesday:                8.00
Wednesday:              8.50
Thursday:               7.50
Friday:                 9.50
-----------------------------------------
Total Time:            42.50
Net Pay:             1173.00
=========================================

Press any key to close this window . . .

Introduction to Sub-Arrays

Overview

After creating an array, one of the operations you can perform is to create a new array that uses only some of the elements of the existing array. A sub-array is a list of items that are derived from an existing array. The C# language provides various operators you can use to create an array from an array. Other classes from the .NET library provide additional methods you can use. After creating the new array, you can use it just like any other array.

The primary operator to create an array derived from another array is .. (2 periods).

Copying an Array

A copy of an array is an array whose all elements are coming from another array. To copy an array, declare an array variable of the same type as the original. Assign the name if the source array to it, followed by square brackets. In the square brackets, put the .. operator. Here is an example:

string[] typesOfCameras = { "Point of Shoot", "DSLR", "360" };
string[] same = typesOfCameras[..];

Console.WriteLine("Types of Cameras");
Console.WriteLine("===============================");

for (int i = 0; i < typesOfCameras.Length; i++)
    Console.WriteLine("Type of Camera: {0}", typesOfCameras[i]);
Console.WriteLine("-------------------------------");

for (int i = 0; i < same.Length; i++)
    Console.WriteLine("Camera Type:    {0}", same[i]);
Console.WriteLine("===============================");

This would produce:

Types of Cameras
===============================
Type of Camera: Point of Shoot
Type of Camera: DSLR
Type of Camera: 360
-------------------------------
Camera Type:    Point of Shoot
Camera Type:    DSLR
Camera Type:    360
===============================

Press any key to close this window . . .

A Sub-List from a Starting-Point of an Array

When creating a sub-list, you can indicate to the compiler what should be the starting point from an existing array. To do this, in the square brackets of the copy, type the 0-based index followed by the .. operator. Here are examples

int[]    naturals       = { 29, 7594, 3708, 5050, 684 };
float[]  floats         = { 32.00F, 44.50F, 35.00F, 42.00F, 48.50F, 35.00F };
string[] typesOfCameras = { "Point of Shoot", "Instant (Polaroid) Camera", "DSLR", "360" };

int[]    otherIntegers  = naturals[2..];
float[]  otherFloats    = floats[4..];
string[] cameras        = typesOfCameras[1..];

Console.WriteLine("Natural Numbers");
for (int i = 0; i < naturals.Length; i++)
    Console.WriteLine("Integral:     {0}", naturals[i]);
Console.WriteLine("---------------------------------------");
Console.WriteLine("From third index");
for (int i = 0; i < otherIntegers.Length; i++)
    Console.WriteLine("Integral:     {0}", otherIntegers[i]);
Console.WriteLine("========================================");

Console.WriteLine("Single-Precision Numbers");
for (int i = 0; i < floats.Length; i++)
    Console.WriteLine("Real Number:  {0:F}", floats[i]);
Console.WriteLine("----------------------------------------");
Console.WriteLine("From fith position");
for (int i = 0; i < otherFloats.Length; i++)
    Console.WriteLine("Real Number:  {0:f}", otherFloats[i]);
Console.WriteLine("========================================");

Console.WriteLine("Types of cameras");
for (int i = 0; i < typesOfCameras.Length; i++)
    Console.WriteLine("Camera:       {0}", typesOfCameras[i]);
Console.WriteLine("----------------------------------------");
Console.WriteLine("From second type");
for (int i = 0; i < cameras.Length; i++)
    Console.WriteLine("Camera:       {0}", cameras[i]);
Console.WriteLine("========================================");

This would produce:

Natural Numbers
Integral:     29
Integral:     7594
Integral:     3708
Integral:     5050
Integral:     684
---------------------------------------
From third index
Integral:     3708
Integral:     5050
Integral:     684
========================================
Single-Precision Numbers
Real Number:  32.00
Real Number:  44.50
Real Number:  35.00
Real Number:  42.00
Real Number:  48.50
Real Number:  35.00
----------------------------------------
From fith position
Real Number:  48.50
Real Number:  35.00
========================================
Types of cameras
Camera:       Point of Shoot
Camera:       Instant (Polaroid) Camera
Camera:       DSLR
Camera:       360
----------------------------------------
From second type
Camera:       Instant (Polaroid) Camera
Camera:       DSLR
Camera:       360
========================================

Press any key to close this window . . .

A Sub-List of the First n Elements of an Array

To create an array that contains the first n elements of an existing array, in the square brackets you are copying, type .. followed by the desired number of elements. Here are examples:

int[]    naturals       = { 29, 7594, 3708, 5050, 684 };
float[]  floats         = { 32.00F, 44.50F, 35.00F, 42.00F, 48.50F, 35.00F };
string[] typesOfCameras = { "Point of Shoot", "Instant (Polaroid) Camera", "DSLR", "360" };

int[]    otherIntegers  = naturals[..3];
float[]  otherFloats    = floats[..5];
string[] cameras        = typesOfCameras[..2];

Console.WriteLine("Natural Numbers");
for (int i = 0; i < naturals.Length; i++)
    Console.WriteLine("Integral:     {0}", naturals[i]);
Console.WriteLine("---------------------------------------");
Console.WriteLine("First three integers");
for (int i = 0; i < otherIntegers.Length; i++)
    Console.WriteLine("Integral:     {0}", otherIntegers[i]);
Console.WriteLine("========================================");

Console.WriteLine("Single-Precision Numbers");
for (int i = 0; i < floats.Length; i++)
    Console.WriteLine("Real Number:  {0:F}", floats[i]);
Console.WriteLine("----------------------------------------");
Console.WriteLine("First five Numbers");
for (int i = 0; i < otherFloats.Length; i++)
    Console.WriteLine("Real Number:  {0:f}", otherFloats[i]);
Console.WriteLine("========================================");

Console.WriteLine("Types of cameras");
for (int i = 0; i < typesOfCameras.Length; i++)
    Console.WriteLine("Camera:       {0}", typesOfCameras[i]);
Console.WriteLine("----------------------------------------");
Console.WriteLine("Two types of cameras");
for (int i = 0; i < cameras.Length; i++)
    Console.WriteLine("Camera:       {0}", cameras[i]);
Console.WriteLine("========================================");

This would produce:

Natural Numbers
Integral:     29
Integral:     7594
Integral:     3708
Integral:     5050
Integral:     684
---------------------------------------
First three integers
Integral:     29
Integral:     7594
Integral:     3708
========================================
Single-Precision Numbers
Real Number:  32.00
Real Number:  44.50
Real Number:  35.00
Real Number:  42.00
Real Number:  48.50
Real Number:  35.00
----------------------------------------
First five Numbers
Real Number:  32.00
Real Number:  44.50
Real Number:  35.00
Real Number:  42.00
Real Number:  48.50
========================================
Types of cameras
Camera:       Point of Shoot
Camera:       Instant (Polaroid) Camera
Camera:       DSLR
Camera:       360
----------------------------------------
Two types of cameras
Camera:       Point of Shoot
Camera:       Instant (Polaroid) Camera
========================================

Press any key to close this window . . .

A Sub-List from a Range in an Array

A range of items in a new list of an existing list so that the items are from a certain point or index of the existing list to a higher point or index of the existing list. If you have an existing array, you can create a new array that uses a range of vallues from the existing arrays. To do this, in the square brackets of the array you are copying, type the 0-based index of the starting range, followed by the .. operator, followed by the 1-based index of the range, as in [x..y].

To copy the items from the first element of an array, specify the left range as 0. To start from the second item, specify the starting index as 1, etc. If you want to produce an empty array, pass the same value for the start and the end points. Here is an example:

double[] payRates  = { 15.55, 30.05, 24.80, 17.95, 9.98, 22.25 };

double[] noElement = payRates[3..3];

If you want to get only one element, specify the end index as one value higher than the first. Here is an example:

double[] payRates     = { 15.55, 30.05, 24.80, 17.95, 9.98, 22.25 };

double[] firstElement = payRates[0..1];

Remember that, to get a range of values, specify the end point as a 1-based position (not the 0-based index). Here are examples:

double[] payRates       = { 15.55, 30.05, 24.80, 17.95, 9.98, 22.25 };
int[]    naturals       = { 29, 7594, 3708, 5050, 684, 2840, 90755 };
float[]  floats         = { 32.00F, 44.50F, 53.50F, 42.00F, 48.50F, 35.00F };
string[] typesOfCameras = { "Point of Shoot", "Instant (Polaroid) Camera", "DSLR", "360" };

double[] first3         = payRates[0..3];
int[]    secondAnd3rd   = naturals[1..3];
float[]  thirdTo5th     = floats[2..5];
string[] secondOnly     = typesOfCameras[1..2];

Console.WriteLine("Pay Rates");
for (int i = 0; i < payRates.Length; i++)
    Console.WriteLine("Pay Rate:     {0:n}", payRates[i]);
Console.WriteLine("---------------------------------------");
Console.WriteLine("First 3 Pay Rates");
for (int i = 0; i < first3.Length; i++)
    Console.WriteLine("Pay Rate:     {0:N}", first3[i]);
Console.WriteLine("========================================");

Console.WriteLine("Natural Numbers");
for (int i = 0; i < naturals.Length; i++)
    Console.WriteLine("Integral:     {0}", naturals[i]);
Console.WriteLine("---------------------------------------");
Console.WriteLine("From 2nd and 3rd elements");
for (int i = 0; i < secondAnd3rd.Length; i++)
    Console.WriteLine("Integral:     {0}", secondAnd3rd[i]);
Console.WriteLine("========================================");

Console.WriteLine("Single-Precision Numbers");
for (int i = 0; i < floats.Length; i++)
    Console.WriteLine("Real Number:  {0:F}", floats[i]);
Console.WriteLine("----------------------------------------");
Console.WriteLine("From 3rd to 5th elements");
for (int i = 0; i < thirdTo5th.Length; i++)
    Console.WriteLine("Real Number:  {0:f}", thirdTo5th[i]);
Console.WriteLine("========================================");

Console.WriteLine("Types of cameras");
for (int i = 0; i < typesOfCameras.Length; i++)
    Console.WriteLine("Camera:       {0}", typesOfCameras[i]);
Console.WriteLine("----------------------------------------");
Console.WriteLine("Only the 2nd element");
for (int i = 0; i < secondOnly.Length; i++)
    Console.WriteLine("Camera:       {0}", secondOnly[i]);
Console.WriteLine("========================================");

This would produce:

Pay Rates
Pay Rate:     15.55
Pay Rate:     30.05
Pay Rate:     24.80
Pay Rate:     17.95
Pay Rate:     9.98
Pay Rate:     22.25
---------------------------------------
First 3 Pay Rates
Pay Rate:     15.55
Pay Rate:     30.05
Pay Rate:     24.80
========================================
Natural Numbers
Integral:     29
Integral:     7594
Integral:     3708
Integral:     5050
Integral:     684
Integral:     2840
Integral:     90755
---------------------------------------
From 2nd and 3rd elements
Integral:     7594
Integral:     3708
========================================
Single-Precision Numbers
Real Number:  32.00
Real Number:  44.50
Real Number:  53.50
Real Number:  42.00
Real Number:  48.50
Real Number:  35.00
----------------------------------------
From 3rd to 5th elements
Real Number:  53.50
Real Number:  42.00
Real Number:  48.50
========================================
Types of cameras
Camera:       Point of Shoot
Camera:       Instant (Polaroid) Camera
Camera:       DSLR
Camera:       360
----------------------------------------
Only the 2nd element
Camera:       Instant (Polaroid) Camera
========================================

Press any key to close this window . . .

Element Exclusion

Introduction

As you know already, the indexes of an array are 0-based. This means that the first element is an Index 0, the second element is at Index 1, and so on. In some operations, you want to consider the indexes from the end of the array. In this case, the index of the last element is 1. The index of the second item from the end is 2, and so on.

If you have an array of elements, you can create a new list that ignores a range of items from the existing array. When creating the new list, you can ask the compiler to ignore a range of elements from the beginning or the end of the existing array. The operator used to exclude elements is ^ (the circumflex accent or symbol). That operator must be written on the left side of a natural number or a variable that holds an integer.

An Element from End

The indexes of an array are counted from the start of the array. In some cases, you may want to consider the elements from the end of the array. You have various options. One of the options is to pass the Array.Length property. Another solution is to exclude some elements from the end of an existing array. To do this, pass the a 1-based index to the copy. Based on this, the last element of the array is acccessed with ^1. The item before the last is accessed with ^2, etc. Here are examples that use the ^ operator:

int[] numbers = new[] { 102, 44, 525, 38, 6, 28, 24481, 327, 632, 104 };

Console.WriteLine("Elements of the Array");
Console.WriteLine("-------------------------------");

for (int i = 0; i < 10; i++)
    Console.WriteLine("Number:          {0}", numbers[i]);
Console.WriteLine("===============================");

Console.WriteLine("First Element:   {0}", numbers[0]);
Console.WriteLine("Second Element:  {0}", numbers[1]);
Console.WriteLine("Third Element:   {0}", numbers[2]);
Console.WriteLine("-------------------------------");
Console.WriteLine("Last Element:    {0}", numbers[^1]);
Console.WriteLine("Before Last:     {0}", numbers[^2]);
Console.WriteLine("Third from Last: {0}", numbers[^3]);
Console.WriteLine("===============================");

This would produce:

Elements of the Array
-------------------------------
Number:          102
Number:          44
Number:          525
Number:          38
Number:          6
Number:          28
Number:          24481
Number:          327
Number:          632
Number:          104
===============================
First Element:   102
Second Element:  44
Third Element:   525
-------------------------------
Last Element:    104
Before Last:     632
Third from Last: 327
===============================

Press any key to close this window . . .

You can use this characteristics to access the elements of an array and perform operations in them. Here are examples:

string[] employee = { "275847", "Christine", "Palleo", "True",
                      "25.83", "9.00", "8.00", "8.50", "7.50", "9.50" };

string emplStatus;
double friday      = double.Parse(employee[^1]);
double thursday    = double.Parse(employee[^2]);
double wednesday   = double.Parse(employee[^3]);
double tuesday     = double.Parse(employee[^4]);
double monday      = double.Parse(employee[^5]);
double timeWorked  = monday + tuesday + wednesday + thursday + friday;
double netPay      = double.Parse(employee[^6]) * timeWorked;
bool worksFullTime = bool.Parse(employee[^7]);
string emplName    = employee[^9] + " " + employee[^8];
long emplNbr       = long.Parse(employee[^10]);

if (worksFullTime == true)
    emplStatus = "Full-Time with all benefits";
else
    emplStatus = "Unknown status or not available";

Console.WriteLine("===================================================");
Console.WriteLine("     - Payroll Preparation -");
Console.WriteLine("===================================================");
Console.WriteLine("Employee Information");
Console.WriteLine("---------------------------------------------------");
Console.WriteLine($"Employee #:            {emplNbr}");
Console.WriteLine($"Employee Name:         {emplName}");
Console.WriteLine("Employment Status:     {0}", emplStatus);
Console.WriteLine($"Hourly Salary:         {double.Parse(employee[^6]):f}");
Console.WriteLine("===================================================");
Console.WriteLine("Time Worked");
Console.WriteLine("---------------------------------------------------");
Console.WriteLine($"Monday:     {monday,16:f}");
Console.WriteLine($"Tuesday:    {tuesday,16:f}");
Console.WriteLine($"Wednesday:  {wednesday,16:f}");
Console.WriteLine($"Thursday:   {thursday,16:f}");
Console.WriteLine($"Friday:     {friday,16:f}");
Console.WriteLine("---------------------------------------------------");
Console.WriteLine($"Total Time: {timeWorked,16:F}");
Console.WriteLine($"Net Pay:    {netPay,16:F}");
Console.WriteLine("===================================================");

This would produce:

===================================================
     - Payroll Preparation -
===================================================
Employee Information
---------------------------------------------------
Employee #:            275847
Employee Name:         Christine Palleo
Employment Status:     Full-Time with all benefits
Hourly Salary:         25.83
===================================================
Time Worked
---------------------------------------------------
Monday:                 9.00
Tuesday:                8.00
Wednesday:              8.50
Thursday:               7.50
Friday:                 9.50
---------------------------------------------------
Total Time:            42.50
Net Pay:             1097.77
===================================================

Press any key to close this window . . .

A List from the Last n Elements of an Array

To create a new list that contains the last n elements of an existing array, in the square brackets of the copying array variable, type ^.. and, between ^ and .., type the number of elements. Here are examples:

int[]    naturals       = { 29, 7594, 3708, 5050, 684 };
float[]  floats         = { 32.00F, 44.50F, 53.50F, 42.00F, 48.50F, 35.00F };
string[] typesOfCameras = { "Point of Shoot", "Instant (Polaroid) Camera", "DSLR", "360" };

int[]    otherIntegers  = naturals[^3..];
float[]  otherFloats    = floats[^4..];
string[] cameras        = typesOfCameras[^2..];

Console.WriteLine("Natural Numbers");
for (int i = 0; i < naturals.Length; i++)
    Console.WriteLine("Integral:     {0}", naturals[i]);
Console.WriteLine("---------------------------------------");
Console.WriteLine("Last three elements");
for (int i = 0; i < otherIntegers.Length; i++)
    Console.WriteLine("Integral:     {0}", otherIntegers[i]);
Console.WriteLine("========================================");

Console.WriteLine("Single-Precision Numbers");
for (int i = 0; i < floats.Length; i++)
    Console.WriteLine("Real Number:  {0:F}", floats[i]);
Console.WriteLine("----------------------------------------");
Console.WriteLine("Last 4 elements");
for (int i = 0; i < otherFloats.Length; i++)
    Console.WriteLine("Real Number:  {0:f}", otherFloats[i]);
Console.WriteLine("========================================");

Console.WriteLine("Types of cameras");
for (int i = 0; i < typesOfCameras.Length; i++)
    Console.WriteLine("Camera:       {0}", typesOfCameras[i]);
Console.WriteLine("----------------------------------------");
Console.WriteLine("Last two elements");
for (int i = 0; i < cameras.Length; i++)
    Console.WriteLine("Camera:       {0}", cameras[i]);
Console.WriteLine("========================================");

This would produce:

Natural Numbers
Integral:     29
Integral:     7594
Integral:     3708
Integral:     5050
Integral:     684
---------------------------------------
Last three elements
Integral:     3708
Integral:     5050
Integral:     684
========================================
Single-Precision Numbers
Real Number:  32.00
Real Number:  44.50
Real Number:  53.50
Real Number:  42.00
Real Number:  48.50
Real Number:  35.00
----------------------------------------
Last 4 elements
Real Number:  53.50
Real Number:  42.00
Real Number:  48.50
Real Number:  35.00
========================================
Types of cameras
Camera:       Point of Shoot
Camera:       Instant (Polaroid) Camera
Camera:       DSLR
Camera:       360
----------------------------------------
Last two elements
Camera:       DSLR
Camera:       360
========================================

Press any key to close this window . . .

Previous Copyright © 2023, FunctionX Tuesday 07 June 2022 Next