C# Arrays and Classes: Defining, Using, and Manipulating Simple Values and Objects, Slides of C programming

An overview of arrays in c# programming language, focusing on their declaration, instantiation, initialization, and usage. It covers both arrays of simple values and arrays of objects, as well as the concept of classes and their relationship with arrays. The document also discusses the use of operators with arrays and the importance of avoiding off-by-one errors.

Typology: Slides

2010/2011

Uploaded on 10/05/2011

christina
christina 🇺🇸

4.6

(23)

393 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CS 112 Introduction to
Programming
Lecture #20:
Arrays
http://flint.cs.yale.edu/cs112/
2
Outline
rAdmin. and review
rArrays
3
Review: Defining and Using Classes
rUsing class to generate objects
mDeclare a variable as a type of a class
mCreate an object
mAssociate the object with a variable,
the variable is a reference to the object
e.g., Coin coin1;
coin1 = new Coin();
Coin coin2 = coin1;
rDefining class according to encapsulation
rSome other details
mobject life cycle
mstatic members
mreadonly and this
coin1
coin2
object
4
Outline
rAdmin. and review
ØArrays
ØDeclaration, instantiation and initialization of
arrays
mExamples
command line
strings as arrays
using array elements as counters
5
Arrays
rAn array stores multiple elements of the same type
mthat type can be simple (value) types or objects
for arrays of simple types, each element contains one value of
the declared type
for arrays of reference types (e.g., objects), every element of
the array is a reference to an object of the data type of the
array
rRefer to particular element in the array by position
number
mthe name of the array followed by the position number
(subscript) of the element in square brackets ([])
[ ] is considered as an operator
6
Arrays: Declaration and Instantiation
rAn array can be allocated using the keyword new to specify how many elements
the array should hold
bool[] flags; // declare flags
flags = new bool[20]; // create an array and make flags a ref.
// now flags is reference to another array
flags = new bool[10];
// declare variable grades; create an array; make grades a
// reference of the array
int[] grades = new int[12];
float[] prices = new float[500];
string[] codes = new string[26];
Time1[] times;
times = new Time1[10];
pf3
pf4
pf5

Partial preview of the text

Download C# Arrays and Classes: Defining, Using, and Manipulating Simple Values and Objects and more Slides C programming in PDF only on Docsity!

CS 112 Introduction to

Programming

Lecture #20:

Arrays

http://flint.cs.yale.edu/cs112/

Outline

r Admin. and review

r Arrays

Review: Defining and Using Classes

r Using class to generate objects

m Declare a variable as a type of a class

m Create an object

m Associate the object with a variable,

the variable is a reference to the object

e.g., Coin coin1;

coin1 = new Coin();

Coin coin2 = coin1;

r Defining class according to encapsulation

r Some other details

m object life cycle

m static members

m readonly and this

coin

coin

object

Outline

r Admin. and review

ÿ Arrays

ÿ Declaration, instantiation and initialization of

arrays

m Examples

• command line

• strings as arrays

• using array elements as counters

Arrays

r An array stores multiple elements of the same type

m that type can be simple (value) types or objects

  • for arrays of simple types, each element contains one value of

the declared type

  • for arrays of reference types (e.g., objects), every element of

the array is a reference to an object of the data type of the

array

r Refer to particular element in the array by position

number

m the name of the array followed by the position number

( subscript ) of the element in square brackets ([])

  • [ ] is considered as an operator

Arrays: Declaration and Instantiation

r An array can be allocated using the keyword new to specify how many elements

the array should hold

bool[] flags; // declare flags

flags = new bool[20]; // create an array and make flags a ref.

// now flags is reference to another array

flags = new bool[10];

// declare variable grades; create an array; make grades a

// reference of the array

int[] grades = new int[12];

float[] prices = new float[500];

string[] codes = new string[26];

Time1[] times;

times = new Time1[10];

Array: An Array of Simple Values

A 12-element array of values.

grades[ 11 ] -

grades[ 10 ]

grades[ 9 ]

grades[ 8]

grades[ 7 ]

grades[ 4 ]

grades[ 3 ]

grades[ 2 ]

grades[ 1 ]

grades[ 0 ]

grades[ 6 ]

grades[ 5 ]

position number (index

or subscript) of the

element within array

grades

grades

Array: An Array of Objects

A 10-element array of objects

ref to obj 0

ref to obj 1

ref to obj 2

ref to obj 3

ref to obj 4

ref to obj 5

ref to obj 6

ref to obj 7

ref to obj 8

times[ 9 ] ref to obj 9

times[ 8]

times[ 7 ]

times[ 4 ]

times[ 3 ]

times[ 2 ]

times[ 1 ]

times[ 0 ]

times[ 6 ]

times[ 5 ]

position number (index

or subscript) of the

element within array

times

times

Summary of Operators

Operators Associativity Type

() []. ++ -- left to right highest (unary postfix)

++ -- + -! ( type) right to left unary (unary prefix)

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

& left to right boolean logical AND

^ left to right boolean logical exclusive OR

| left to right boolean logical inclusive OR

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %= right to left assignment

Precedence and associativity of the operators discussed so far.

Arrays as Objects

r In C#, an array behaves very much like an

object

m declaration and instantiation are like objects

• declare an array variable

• create an array using new

• make a variable a reference of an array

m parameter passing is similar to objects

• we will discuss the detail later.

m an array has the Length property

Array: Length

r Each array has a public property called

Length that stores the size of the array

m once an array is created, it has a fixed size

r It is referenced using the array name (just like

any other object):

grades.Length

r Note that Length holds the number of

elements, not the largest index

Array and Bound

r An index used in an array reference must specify a

valid element

m That is, the index value must be in bounds (0 to N-1), where

N is the length

r For example, if the array grades can hold 12 values,

it can only be indexed using the numbers 0 to 11

for (int index=0; index <= grades.Length; index++)

scores[index] = index*50 + epsilon;

problem

It’s common to introduce off-by-one errors when using arrays

Outline

r Admin. and review

r Arrays

m Declaration and initialization of arrays

m Examples

• command line array

• strings as arrays

• using array elements as counters

Example 1: Command-Line Arguments

r The signature of the Main method indicates that it

takes an array of string as parameter

r These values come from command-line arguments

that are provided when the program is invoked

r For example, the following invocation of the

interpreter passes an array of three string objects

into Main:

C:> Calculator 2 + 3

r These strings are stored at positions 0-2 of the

parameter

r See Calculator.cs

Example 2: strings as Arrays

r You can use a string as an array

m You can access the length of a string using the

Length property

m You can access each character of a string using [

], e.g.,

string resp = Console.ReadLine().ToUpper();

for (int i = 0; i < resp.Length; i++)

Console.Write( resp[i] );

Example 3: Using the Elements

of an Array as Counters

r Use array elements to keep

track of number of

occurrences

r Example – Die Rolling

Program

m Use the value of rolling the

dice as the subscript for the

array

m Increment the

corresponding array

element when a die value is

rolled

Outline

RollDie.cs

1 // RollDie.cs 2 // Rolling 12 dice. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 using System.IO; 11 12 public class RollDie : System.Windows.Forms.Form 13 { 14 private System.Windows.Forms.Button rollButton; 15 16 private System.Windows.Forms.RichTextBox displayTextBox; 17 18 private System.Windows.Forms.Label dieLabel1; 19 private System.Windows.Forms.Label dieLabel2; 20 private System.Windows.Forms.Label dieLabel3; 21 private System.Windows.Forms.Label dieLabel4; 22 private System.Windows.Forms.Label dieLabel5; 23 private System.Windows.Forms.Label dieLabel6; 24 private System.Windows.Forms.Label dieLabel7; 25 private System.Windows.Forms.Label dieLabel8; 26 private System.Windows.Forms.Label dieLabel9; 27 private System.Windows.Forms.Label dieLabel10; 28 private System.Windows.Forms.Label dieLabel11; 29 private System.Windows.Forms.Label dieLabel12; 30 31 private System.ComponentModel.Container components = null; 32 33 Random randomNumber = new Random(); 34 int[] frequency = new int[ 7 ]; 35

Create a Random object

Declare an integer array

frequency and allocate it

enough memory to hold

7 integers

Outline

RollDie.cs

36 public RollDie() 37 { 38 InitializeComponent(); 39 } 40 41 // Visual Studio .NET generated code 42 43 [STAThread] 44 static void Main() 45 { 46 Application.Run( new RollDie() ); 47 } 48 49 private void rollButton_Click( 50 object sender, System.EventArgs e ) 51 { 52 // pass the labels to a method that will 53 // randomly assign a face to each die 54 DisplayDie( dieLabel1 ); 55 DisplayDie( dieLabel2 ); 56 DisplayDie( dieLabel3 ); 57 DisplayDie( dieLabel4 ); 58 DisplayDie( dieLabel5 ); 59 DisplayDie( dieLabel6 ); 60 DisplayDie( dieLabel7 ); 61 DisplayDie( dieLabel8 ); 62 DisplayDie( dieLabel9 ); 63 DisplayDie( dieLabel10 ); 64 DisplayDie( dieLabel11 ); 65 DisplayDie( dieLabel12 ); 66 67 double total = 0; 68 69 for ( int i = 1; i < 7; i++ ) 70 total += frequency[ i ];

Event handler for the

rollButton Click event

Call method DisplayDie once

for each Label

Total the number of

times the dice have

been rolled

Outline

RollDie.cs

72 displayTextBox.Text = "Face\tFrequency\tPercent\n"; 73 74 // output frequency values 75 for ( int x = 1; x < frequency.Length; x++ ) 76 { 77 displayTextBox.Text += x + "\t" + 78 frequency[ x ] + "\t\t" + String.Format( "{0:N}", 79 frequency[ x ] / total * 100 ) + "%\n"; 80 } 81 82 } // end Main 83 84 // simulates roll, display proper 85 // image and increment frequency 86 public void DisplayDie( Label dieLabel ) 87 { 88 int face = randomNumber.Next( 1, 7 ); 89 90 dieLabel.Image = Image.FromFile( 91 Directory.GetCurrentDirectory() + 92 "\images\die" + face + ".gif" ); 93 94 frequency[ face ]++; 95 } 96 97 } // end class RollDie

Output the frequency of each

die value

Get a random number

from 1 to 6

Display die image corresponding

to the number rolls

Outline

RollDie.cs

Program Output

Outline

StudentPoll.cs

1 // StudentPoll.cs 2 // A student poll program. 3 4 using System; 5 using System.Windows.Forms; 6 7 class StudentPoll 8 { 9 // main entry point for application 10 static void Main( string[] args ) 11 { 12 int[] responses = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 13 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 14 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 }; 15 16 int[] frequency = new int[ 11 ]; 17 string output = ""; 18 19 // increment the frequency for each response 20 for ( int answer = 0; answer < responses.Length; answer++ ) 21 ++frequency[ responses[ answer ] ]; 22 23 output += "Rating\tFrequency\n"; 24 25 // output results 26 for ( int rating = 1; rating < frequency.Length; rating++ ) 27 output += rating + "\t" + frequency[ rating ] + "\n"; 28 29 MessageBox.Show( output, "Student poll program", 30 MessageBoxButtons.OK, MessageBoxIcon.Information ); 31 32 } // end method Main 33 34 } // end class StudentPoll

Declare and initialize

integer array responses

Declare and allocate

integer array frequency

For every element in responses,

increment the frequency element

that corresponds to the answer

Output the number of times each

response appeared

Outline

r Admin. and review

r Examples

• command line array

• strings as arrays

• using array elements as counters

ÿ Parameter passing

Recall: Two Types of Variables

r A variable represents a cell in memory

r Value type

m int, char, byte, float, double, string

A value type variable stores a value of the

type of the variable in the memory

int x = 45;

double y = 45.12;

r Reference type

m A variable that “stores” object or array

actually stores a reference to an object

or array, e.g.,

m A reference is a location in computer’s

memory where the object or array itself

is stored

Time3 t1;

t1 = new Time3(11, 45, 59);

x 45

y 45.

t

Implications of the Two Types of Variables:

Assignment

r An assignment of one value variable to

another value variable copies the value, e.g.,

int x = 45;

double y = 45.12;

int z;

z = x;

r An assignment of one reference variable to

another reference variable copies the reference, e.g.,

Time3 t1;

t1 = new Time3(11, 45, 59);

Time3 t2;

t2 = t1;

t

x 45

y 45.

z 45

t

Calling a Method: Reference

r Each time a method is called, the actual arguments in

the invocation are copied into the formal arguments

m If a value type, it is the value

m If a reference type, it is the reference

static void DoubleArray (int[] array)

for (int i = 0; i < array.Length; i++)

array[i] *= 2;

DoubleArray (array);

int[] array = {1, 2, 3}; array

array

Calling a Method: Side Effect of Reference

r If an argument is a reference type, then modifying the

content/state of the array/object through the

reference will have side effect

static void DoubleArray (int[] array)

for (int i = 0; i < array.Length; i++)

array[i] *= 2;

DoubleArray (array);

int[] array = {1, 2, 3}; array

array

i

Calling a Method: Side Effect

static void DoubleArray (int[] array)

DoubleArray( array );

int[] array = {1, 2, 3}; array

array

for (int i = 0; i < array.Length; i++)

array[i] *= 2;

i

r Each time a method is called, the actual arguments in the invocation

are copied into the formal arguments

m If a value type, then it is the value that is copied

m If a reference type, then it is the reference that is copied

r The formal argument and the actual argument are different variables,

with different memory locations.

array = new int[] {2, 4, 6, 8};

Arrays as Parameters: Summary

r If an argument of a method is an array, a

reference to a array is passed to the method

r Changing an array element in the method

changes the original

r An array element can be passed to a method

as well, and follow the parameter passing

rules of that element's type