You are on page 1of 24

Chapter 6: Arrays

Arrays
Arrays

 Life without arrays


– Suppose we needed to get the average grade for
five test scores and then print out all grades lower
than that average.
– Since we don’t know which scores to output until
AFTER all of the data has been input, we will
need to hold data until the five test scores have
been read in.
 So we create five variables, input the information, and
then test each one of them.
Life Without Arrays
//Program to find the average test score and output the average if (test0 < average)
//test score and all the test scores that are less than {Console.WriteLine("{0} is less that the average test score.", test0);}
//the average test score. if (test1 < average)
{Console.WriteLine("{0} is less that the average test score.", test1);}
static void Main(string[] args) if (test2 < average)
{ {Console.WriteLine("{0} is less that the average test score.", test2);}
if (test3 < average)
int test0, test1, test2, test3, test4; {Console.WriteLine("{0} is less that the average test score.", test3);}
double average; if (test4 < average)
{Console.WriteLine("{0} is less that the average test score.", test4);}
Console.ReadKey();
Console.WriteLine("Enter five test scores. One on return;
each line: "); }
test0 = int.Parse(Console.ReadLine());
test1 = int.Parse(Console.ReadLine());
test2 = int.Parse(Console.ReadLine());
test3 = int.Parse(Console.ReadLine());
test4 = int.Parse(Console.ReadLine());

average = (test0 + test1 + test2 + test3 + test4) / 5.0;

Console.WriteLine("The average test score = {0}",


average);
What’s an Array
And how can this help

 An array is a collection of variables of the


same data type.
 The array is referenced by a single name
suffixed with an index pointer.
 Let’s redo our grading example
Life With an Array
int [] test = new int[5]; Console.WriteLine("The average test score =
double average; {0}", average);

Console.WriteLine("Enter five test scores. for (int i =0;i<5;i++)


One on each line: "); {
test[0] = int.Parse(Console.ReadLine()); if (test[i] < average)
test[1] = int.Parse(Console.ReadLine()); Console.WriteLine("{0} is less that the
test[2] = int.Parse(Console.ReadLine()); average test score.", test[i]);
test[3] = int.Parse(Console.ReadLine()); }
test[4] = int.Parse(Console.ReadLine());
Console.ReadKey();
int total = 0; return;
for (int i =0;i<5;i++)
{
total = total + test[i];
}
average = total / 5.0;
Now what can we do?

 Since we have an array basis, we can


– Ask the user how many test scores there are
– Input the test scores using a For or While loop
– Greatly reduce our coding
Revised Grading Program
Console.Write("How Many Scores? "); Console.WriteLine("The average test score = {0}",
int nNumbTests = average);
int.Parse(Console.ReadLine());
for (int i = 0; i < nNumbTests; i++)
int[] test = new int[nNumbTests]; {
double average = 0; if (test[i] < average)
int total = 0; Console.WriteLine("{0} is less that the
average test score.", test[i]);
Console.WriteLine("Enter {0} test scores. }
One on each line: ", nNumbTests);
for (int i = 0; i < nNumbTests; i++) Console.ReadKey();
{ return;
test[i] = int.Parse(Console.ReadLine());
total = total + test[i];
average = (double)total /
(double)nNumbTests;
}
Array Basics
 When declared, memory is set aside based on the variable
type and number of elements in the array
– int[] nPrices = new int [100]
Will allocate an array named nPrices with 100 elements
The elements are indexed from 0 to 99:
Each element can hold one integer value
 The above example is a “one dimensional” array.
 It may be easier to think that the computer is creating 100
separate variables named nPrices[0] through nPrices[99] (or
maybe not)
Array Basics

 Array variables can be used in any of our


expressions just like any other variables. But
they MUST include the suffix with the index.
 In the example we just went through, we had:
– Console.WriteLine("{0} is less that the average
test score.", test[i]);
 What do you think would happen if I
reference just test?
– Console.WriteLine(test);
Array Basics
 Normal arrays sizes are static.
– That is, they cannot be changed once initialized.
– You can use constants or variables in the definitions
 const int nARRAY_SIZE = 20;
 int[] nMyArray = int[nARRAY_SIZE];

 Arrays can be initialized when they are declared


– char[] sLetterGrade = new char[5] {‘A’,’B’,’C’,’D’,’E’};
– int[] nScore = new int[5] {0,0,0,0,0}; // initializes ALL
elements to 0
– int[] nDemo = {3,6,9}; //Creates an array with three
elements
Array Basics

 Supposed we have two arrays


– int[] nArrayOne = {1,2,3,4,5};
– int[] nArrayTwo = new int[5];
 We would like to copy nArrayOne to nArrayTwo
– But we cannot do it directly!!
– We must copy element by element.
– Same is true for comparison, printing, etc.
– Also, as parameters to methods, arrays are always By Ref
Standard Array Copy Routine
for (int i=0;i<5;i++)
{
nArraytwo[i] = nArrayone[i];
}

 how bout doing that in a function?


static void copyArray(int[] pnArrayIn, int[] pnArrayOut, int pSize)
{
for (int i = 0; i < pSize; i++)
{
pnArrayOut[i] = pnArrayIn[i];
}

}
 What happens if I do say nArrayTwo = nArrayOne?
Strings – Strings
and even more Strings

 In the beginning, c had no string manipulation


abilities.
– Instead all they had were character arrays.
– They had to manipulate text using the same type of array
manipulation stuff we just looked at for other simple
variables.
– c was used a lot for scientific calculations and as a
replacement for assembly language (and when compared
to assembly language, the programmers were just as happy
as they could be!!)
Strings – Strings
and even more Strings

 But, as we have seen above, arrays have


limitations that make sense for a series of
numbers, but not a series of letters.
– You can’t compare two arrays without using a for
loop
– You can’t easily move the contents of one array to
another
The String Class
 C# carried the String Library further into the String Class
 Stores a collection of Unicode characters
 Immutable series of characters
– Making a change isn’t making a change, it’s making a new string!!
 Reference type
– Normally equality operators, == and !=, compare the object’s
references, but operators function differently with string than with
other reference objects
 Equality operators are defined to compare the contents or values
 Includes large number of predefined methods
The String Class

 Can process variables of string type as a


group of characters
– Can also access individual characters in string
using an index with [ ]
 First character is indexed by zero

string sValue = "C# Programming";


object sObj;
string s = "C#";
Some String Functions
Some String Functions
More Useful String Functions
More Useful String Functions
Class work

 Write a program that creates a 10 item array


of type int.
 The program should then ask the user to
enter 10 integers.
 Once stored in the array, the program should
use the sort algorithm we just worked out to
sort the numbers, and then output the sorted
array.
Two Dimensional Array

 double[,] fSalesArray = new double [10] [5];


– initializes a two dimensional array with 10 rows and 5 columns
– What could be some examples where we might want to use a two
dimensional array?
– What other “things” look like the example below?
Jagged Arrays

 Really an Array of Arrays where the the first


brackets identifies the number of arrays. The
second the item within that array
– int[][] n7 = new int[2][] { new int[] {2,4,6}, new int[]
{1,3,5,7,9} };
– int[][] n8 = new int[][] { new int[] {2,4,6}, new int[]
{1,3,5,7,9} };
– int[][] n9 = { new int[] {2,4,6}, new int[] {1,3,5,7,9} };
Multidimensional Arrays

 Just like we did with two dimensional arrays,


one can define as many dimensions as you
would like when an array is created.

You might also like