12 arrays loading

24
C# Arrays   part 1

Upload: noor-baloch

Post on 04-Jun-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 1/24

C#

Arrays –  part 1

Page 2: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 2/24

2

Overview of Topics

Declaring Arrays

Loading Arrays

Partially Filled ArraysArrays Elements as Arguments

Declaring and Loading Constant Arrays

Page 3: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 3/24

3

Arrays are Tables

Array is a different word for a table.

A table is made up of columns and rows.

Just like an Excel spreadsheet.

Page 4: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 4/24

4

Array Defined

An array is used to process a collectionof data all of which is of the same data

type (Integer, Decimal, String, etc.).

First we’ll look at single dimensionalarrays (one column, many rows).

Think of a single dimensional array as a

list of variables.

Page 5: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 5/24

5

Declaring Array

int intQty1, intQty2, intQty3;

int[ ] intQty = new int[3]; //3 integer variables

dataType[ ] arrayName = new dataType[arraySize];

An array of 3 elements of type integer is created.

The arraySize is used by C# to determine how muchmemory to allocate.

Arrays will usually be class-level because after valuesare loaded in we don’t want to lose the values.

Page 6: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 6/24

6

Array SubscriptdataType[ ] arrayName = new dataType[arraySize];

Arrays are allocated consecutive memory.

Each element is referenced using a subscript.

Subscript are integers.

The number of elements that are created is arraySize.

The first element in the array is referenced with avalue of zero [0].

The last element is referenced with a subscript valueof [arraySize –  1].

A subscript is also referred to as an index.

Short variable names for subscripts are acceptable.

Page 7: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 7/247

Memory Map

Address Variable Value

1010 intQty1 0

1020 intQty2 0

1030 intQty3 0

1040 intQty[0] 0

1050 intQty[1] 0

1060 intQty[2] 0

1070 decPrice 0

Page 8: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 8/248

Subscript Out Of Range

If during execution, the subscript value

referenced an element past the end of the

array, the program would throw an

exception (run-time error).

The programmer must make sure that the

logic in the program does not allow the

subscript to exceed the array size.This is called being out of range.

Page 9: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 9/249

Preventing Out of Range

C# will not prevent a subscript out of range error, butit will abort the execution when it happens.

It aborts because the subscript would be referencingsome other section of memory than what was

allocated for the array. The programmer is responsible for preventing the out

range error.

We can use some of the Array Class properties and

methods to manage arrays,arrayName.LengtharrayName.GetUpperBound(0).

The For Each (foreach) command may also be used towalk through arrays.

Page 10: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 10/2410

Array Class Properties & Methods

int[ ] intQty = new int[3]; //3 integer variables

arrayName.Length –  intQty.Length is equal to 3.

 –  intQty.Length is the number of entries that can be loaded. –  The last valid subscript value is one less than Length.

arrayName.GetUpperBound(0). –  intQty.GetUpperBound(0) is equal to 2.

 –  intQty.GetUpperBound(0) is last valid subscript value.

Depending the loop structure, we may use: –  less than Length or

 –  Equal to GetUpperBound(0)

Page 11: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 11/2411

Array Processing

1. Declare Array

2. Load Array• After creating the array, data must be loaded.

• Use arrayName.Length or arrayName.GetUpperBound(0) to

 prevent out of range errors.•  Note: Arrays can be declared and loaded with constant values.

3. Process Array• Use individual elements in calculations or as arguments.

• Send entire arrays to methods for processing.• Sort, Search, Display

• Use a lot of For loops or For Each loops.

Page 12: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 12/2412

Declare Array

//Arrays are declared at the class level,//so they can be referenced by all methods.

int[ ] cintTestScores = new int[20];int cintNumberOfStudents;

//We can load up to 20 scores, but we will

//save how many tests are actually loaded in

cintNumberOfStudents.

Page 13: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 13/2413

Declare Array with a Const

//Arrays can be declared using a constant for the size.

const int intARRAY_SIZE = 20;

int[ ] cintTestScores = new int[intArraySize];

//We can still load up to 20 scores

Page 14: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 14/2414

cintTestScores Array Memory Map

Position Address Index Value1 1010 [0] 0

2 1014 [1] 0

3 1018 [2] 04 1022 [3] 0

5 1026 [4] 0

6 1030 [5] 07 1034 [6] 0

…  …  …  … 

20 1086 [19] 0

Page 15: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 15/2415

Load Array//Loads Array with scores saved in a data file.

 private void btnLoadArray_Click( )

{ FileStream studentFile = new FileStream("cs12ex.txt", FileMode.Open);

StreamReader studentStreamReader = new StreamReader(studentFile);int i = 0; //subscript initialized to zero

while (studentStreamReader.Peek() != -1){

if (i < cintTestScores.Length){cintTestScores[i] = int.Parse(studentStreamReader.ReadLine( ));i ++; //Increment subscript by one

}else{

MessageBox.Show (“Array Size Exceeded”); 

 break; //Get of out of loop; Array is full.}

}cintNumberOfStudents = i; //Save how many students were loadedstudentFile.Close( ); //Close file

}

cs12ex.txt

50

40100

30

10

20

Page 16: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 16/2416

Loaded Arrays

Position Address Index Value1 1010 [0] 50

2 1014 [1] 40

3 1018 [2] 1004 1022 [3] 30

5 1026 [4] 10

6 1030 [5] 207 1034 [6] 0

…  …  …  … 

20 1086 [19] 0

Page 17: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 17/2417

Process Array –  Individual Elements

 private void btnProcessArray_Click( )

{int i;int intSum = 0;

for (i = 0; i <= cintTestScores.GetUpperBound(0); i++){

intSum += cintTestScores[i];

}

txtSum.Text = intSum.ToString(“N0”); 

}

Page 18: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 18/2418

For Each - Example

 private void btnProcessArray_Click( )

{int i; //subscript not neededint intSum = 0;

foreach (int intTestScore in cintTestScores){

intSum += intTestScore;

}

txtSum.Text = intSum.ToString(“N0”); 

}

Page 19: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 19/2419

Individual Elements as Arguments private void btnProcessArray_Click( )

{int i;decimal decPercent;

for (i = 0; i <= cintTestScores.GetUpperBound(0); i++)

{decPercent = calcPercent(cintTestScores[i]);

txtPercent.Text = decPercent.ToString(“N0”); 

}

}

 private decimal calcPercent(int intScore)

{return (intScore / 100);

}

Page 20: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 20/2420

Partially Filled Arrays

In the for loop on the prior slide it was assumed that the arrayswere filled by going up to GetUpperBound(0).

Up to 20 scores could be loaded, but in the example only 6scores were actually loaded.

When the array is not full, it is considered a partially filledarray.

The for loops need to be modified to only process the numberscores loaded.

The number of scores loaded are counted in the load routine,and the count should then be saved in a variable likecintNumberOfStudents.

This variable should then be used when processing the arrays.

Page 21: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 21/2421

Load Array –  Partially Filled//Loads Array with scores saved in a data file.

 private void btnLoadArray_Click( )

{ FileStream studentFile = new FileStream("cs12ex.txt", FileMode.Open);

StreamReader studentStreamReader = new StreamReader(studentFile);int i = 0; //subscript initialized to zero

while (studentStreamReader.Peek() != -1){

if (i < cintTestScores.Length){cintTestScores[i] = int.Parse(studentStreamReader.ReadLine( ));i ++; //Increment subscript by one

}else{

MessageBox.Show (“Array Size Exceeded”);  break; //Get of out of loop; Array is full.

}}cintNumberOfStudents = i; //Save how many students were loadedstudentFile.Close( ); //Close file

}

Page 22: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 22/24

22

Processing Partially Filled Arrays

 private void btnProcessArray_Click( )

{int i;int intSum;

//for (i = 0; i <= cintTestScores.GetUpperBound(0); i++) //process entire array

for (i = 0; i < cintNumberOfStudents; i++) // process partially filled array {

intSum += cintTestScores[i];

}

txtAverage.Text = (intSum / cintNumberOfStudents).ToString(“N0”); }

Page 23: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 23/24

23

Declare and Load Constant Arrays

Arrays that will hold constants or some initial values can beloaded at declaration.

When the values are provided at declaration, do not include thesize. The size is determined by the number of values provided.

The values are enclosed in braces and not parenthesis.

decimal[ ] cdecPERCENT_RANGE = new decimal[ ]{90D, 80D, 70D, 60D, 0D};

string[ ] cstrLETTER_GRADE = new string[ ]

{"A", "B", "C", "D", "F"};

C# does NOT allow const for arrays.

Page 24: 12 Arrays Loading

8/13/2019 12 Arrays Loading

http://slidepdf.com/reader/full/12-arrays-loading 24/24

24

Summary

Declaring Arrays

Loading Arrays

Partially Filled ArraysArrays Elements as Arguments

Declaring and Loading Constant Arrays