Bits & Bytes

Posts Tagged ‘stock’

Using Rectangular and Jagged Arrays in C#

One of the unique and problematic features of C# is its usage of arrays. There are two different and distinct styles of syntax: comma delimited indices for rectangular arrays and repeated bracket operators for jagged arrays. These are written as “MyArray[2,4]” and “MyArray[2][4]”, respectively.

The program below demonstrates how to use both of these types of arrays by creating an example of each. Under the comment Rectangular Array Example, I declare and allocate a rectangular 2-dimensional array of stock price closes a few companies; the first dimension of the array is indexed by company and the second is indexed by the date. Under the comment Jagged Array Example, I declare and allocate a 2-dimensional jagged array of stock trades; the first dimension of the array is indexed by the ticker symbol and the second is indexed by the trade number for that symbol. These arrays could be of any number of dimensions; I have used the simple case of 2 dimensions for illustration.

For the first array, we have a 3 by 5 rectangular array of 5 stock price closes each for 3 companies. The entire 2-dimensional array is allocated all at once. Notice that indices are comma delimited, which is unusual for computer programming. Also, notice the nesting pattern for the braces where I have initialized the array entries. Inside the for-loops, I used the GetLength() function along with the dimensional index to get the length along any given dimension.

For the second array, we have 2 entries along the first dimension and 2 and 3 along the second dimension to specify 2 and 3 trades for each of the 2 symbols. The first dimension is allocated at the declaration; below that, each of the second dimensions are allocated and assigned values separately. The values of the arrays represent sells with positive numbers and buys with negative numbers. Inside the for-loops, I access the Length property to get the size along the first dimension. Then I access the Length property with each index by using the bracket operator to get the varying length along the second dimension. Notice that the more common repeated bracket syntax has replaced the comma delimited syntax in this second example.

The output from running the code is shown below the program.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Arrays {
    class Program {
        static void Main(string[] args) {
            // ***** Rectangular Array Example *****
            // The stock price close for 3 companies for a week
            double[,] daaStockPriceClose = new double[3, 5]{
                {576.11, 585.00, 585.88, 583.82, 583.59},
                {44.94, 44.97, 45.34, 44.84, 45.35},
                {98.49, 99.41, 100.44, 100.57, 100.29}
            };

            for (int iCompany = 0; iCompany < daaStockPriceClose.GetLength(0); ++iCompany) {
                Console.Write("Company #" + iCompany + ":  ");
                for (int iDay = 0; iDay < daaStockPriceClose.GetLength(1); ++iDay) {
                    Console.Write(daaStockPriceClose[iCompany ,iDay] + "  ");
                }
                Console.WriteLine("");
            }
            Console.WriteLine("");

            // ***** Jagged Array Example *****
            // The stock set of stock trades
            double[][] dppStockTrades = new double[2][];
            dppStockTrades[0] = new double[3]{10265.82, -4925.39, -3096.72};
            dppStockTrades[1] = new double[2]{6636.96, -9746.58};
            for (int iSymbol = 0; iSymbol < dppStockTrades.Length; ++iSymbol) {
                Console.Write("Symbol #" + iSymbol + ":  ");
                for (int iTrade = 0; iTrade < dppStockTrades[iSymbol].Length; ++iTrade) {
                    Console.Write("Trade #" + iTrade + ": " + dppStockTrades[iSymbol][iTrade] + "  ");
                }
                Console.WriteLine("");
            }
            Console.WriteLine("");
        }
    }
}

ArraysOutput

Printing Messages to the Console Window in C#

This is one of the most fundamental elements of C# programming. In a simple console application, we often want to output some value or set of values to the console window where we can see them. To do this, we can call the functions Console.Write() and Console.WriteLine(). Both of these functions can be use with all of the primitive data types, including strings. The main difference between the functions is that the second one puts an endline or linefeed/carriage return at the end of the output to set the future output to the next line.

To demonstrate, we have a simple program below that prints the closing prices on a given day for two company stock symbols: MSFT and RSH. These two symbols, MSFT and RSH, are the ticker symbols for the companies Microsoft and Radio Shack. This is a simple Console Application project. All of the code outside of the Main() function is standard, boilerplate code that is generated by the Visual Studio IDE. So, we will ignore that and talk about the output statements inside the Main() function.

Inside the Main() function, I start with four lines that output message “Closing Prices – Date: 8/21/2014” with a line underneath it. Notice that I used the Console.Write() function for the first two print statements so that all of the text from the first three statements was printed on one line. The next call to Console.WriteLiine() adds the endline to separate the output for the next line of dashes. The line of dashes is written with the Console.Write() function. However, I added the “\u000D\u000A” at the end which is the equivalent of a linefeed/carriage return or endline character. This makes the call the equivalent of a call to Console.WriteLine(). It is useful to know this, since this can be used anywhere inside of a string to create an endline.

In the last four lines, I output the symbols for Microsoft and Radio Shack along with their respective closing prices for the day. To do this, I created decimal type variables and assigned them values. The decimal data type requires that I put an “M” suffix at the end of each number so that the compiler interprets it as a decimal type. Then I call Console.WriteLine() twice for each string that is passed in. The first string is created automatically from the string literal, “MSFT: ” concatenated with the decimal value contained in dMsftPrice via the “+” operator. The final output look like this:

ConsoleOutput

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyConsoleApplication {
    class Program {
        static void Main(string[] args) {
            Console.Write("Closing Prices - ");
            Console.Write("Date: ");
            Console.WriteLine(new DateTime(2014, 8, 21).ToShortDateString());
            Console.Write("-----------------------------------\u000D\u000A");

            decimal dMsftPrice = 45.22M;
            Console.WriteLine("MSFT: " + dMsftPrice);
            decimal dRshPrice = .67M;
            Console.WriteLine("RSH:   " + dRshPrice);
        }
    }
}