CS 112 Introduction to Programming - PowerPoint PPT Presentation

1 / 36
About This Presentation
Title:

CS 112 Introduction to Programming

Description:

Array Instantiation and Initialization in One Step: Initializer List ... initializer list can be used to instantiate and initialize an array in one step ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 37
Provided by: Richar9
Category:

less

Transcript and Presenter's Notes

Title: CS 112 Introduction to Programming


1
CS 112 Introduction to Programming
  • Lecture 18
  • Arrays
  • Http//zoo.cs.yale.edu/classes/cs112/

2
Outline
  • Admin. and review
  • Arrays

3
Admin.
  • Assignment 3
  • due today 1159pm
  • office hours
  • 2-3 PM (AKW 202) 7-8 PM (DL 120) 8-1030 PM (DL
    120)
  • Assignment 4
  • due Oct. 22??
  • two programs one on defining class, one on array
  • Midterm 1
  • Oct. 20 7-9 PM
  • lectures 1-20 a list of topics is linked on the
    schedule page
  • open book, open notes, but no computer please
  • Office hours and feedback
  • Please come to office hours if you have any
    questions

4
Review Defining and Using Classes
  • Using class to generate objects
  • Declare a variable as a type of a class
  • Create an object
  • Associate the object with a variable,the
    variable is a reference to the objecte.g.,
    Coin coin1 coin1 new Coin() Coin
    coin2 coin1
  • Defining class according to encapsulation
  • Some other details
  • object life cycle
  • static members
  • readonly and this

coin1
object
coin2
5
Rational
  • How to represent rational numbers such as ½, ¾?
  • What services does a rational number provide?

See Rational.cs and RationalNumbers.cs
6
Preview
  • Arrays declaration and usage today
  • Parameter passing of arrays sorting and search
    Wednesday
  • Multi-dimensional arrays and dynamic arrays
    Friday

7
Outline
  • Admin. and review
  • Arrays
  • Declaration, instantiation and initialization of
    arrays
  • Examples
  • command line
  • strings as arrays
  • using array elements as counters

8
Arrays
  • An array stores multiple elements of the same
    type
  • 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
  • Refer to particular element in the array by
    position number
  • the name of the array followed by the position
    number (subscript) of the element in square
    brackets ()
  • is considered as an operator

9
Arrays Declaration and Instantiation
  • An array can be allocated using the keyword new
    to specify how many elements the array should
    hold
  • bool flags // declare flags
  • flags new bool20 // create an array and
    make flags a ref.
  • // now flags is reference to another array
  • flags new bool10
  • // declare variable grades create an array
    make grades a
  • // reference of the array
  • int grades new int12
  • float prices new float500
  • string codes new string26
  • Time1 times
  • times new Time110

10
Array An Array of Simple Values
grades 0
grades 1
grades 2
grades
grades 3
grades 4
grades 5
grades 6
grades 7
position number (index or subscript) of the
element within array grades
grades 8
grades 9
grades 10
grades 11
Fig. 7.1 A 12-element array of values.
11
Array An Array of Objects
ref to obj 0
times 0
ref to obj 1
times 1
ref to obj 2
times 2
times
ref to obj 3
times 3
ref to obj 4
times 4
ref to obj 5
times 5
ref to obj 6
times 6
ref to obj 7
times 7
position number (index or subscript) of the
element within array times
ref to obj 8
times 8
ref to obj 9
times 9
A 10-element array of objects
12
Summary of Operators
13
Arrays as Objects
  • In C, an array behaves very much like an object
  • declaration and instantiation are like objects
  • declare an array variable
  • create an array using new
  • make a variable a reference of an array
  • parameter passing is similar to objects
  • we will discuss the details Wed.
  • an array has the Length property

14
Array Length
  • Each array has a public property called Length
    that stores the size of the array
  • once an array is created, it has a fixed size
  • It is referenced using the array name (just like
    any other object)
  • grades.Length
  • Note that Length holds the number of elements,
    not the largest index

15
Array and Bound
  • An index used in an array reference must specify
    a valid element
  • That is, the index value must be in bounds (0 to
    N-1), where N is the length
  • For example, if the array grades can hold 12
    values, it can only be indexed using the numbers
    0 to 11

for (int index0 index lt grades.Length
index) scoresindex index50 epsilon
Its common to introduce off-by-one errors when
using arrays
16
Array Instantiation and Initialization in One
Step Initializer List
  • An initializer list can be used to instantiate
    and initialize an array in one step
  • The values are delimited by braces and separated
    by commas
  • Allocate space for the array number of elements
    in initializer list determines the size of array
  • Elements in array are initialized with the values
    in the initializer list
  • The new operator is not used
  • Examples
  • int units 147, 323, 89, 933, 540
  • char letterGrades 'A', 'B', 'C', 'D',
    'F'
  • string wordList cs112, computer",
    television"

17
InitArray.cs
  • 1 // Fig 7.3 InitArray.cs
  • 2 // Different ways of initializing arrays.
  • 3
  • 4 using System
  • 5 using System.Windows.Forms
  • 6
  • 7 class InitArray
  • 8
  • 9 // main entry point for application
  • 10 static void Main( string args )
  • 11
  • 12 string output ""
  • 13
  • 14 int x // declare
    reference to an array
  • 15 x new int 10 // dynamically
    allocate array and set
  • 16 // default values
  • 17
  • 18 // initializer list specifies number
    of elements
  • 19 // and value of each element

Declare an integer array variable x
Create an array of size 10 x is a ref. to it
Declare an integer array and initialize it with
values
Declare a constant ARRAY_SIZE
Declare z
Create an array of size ARRAY_SIZE z is a
reference to it.
Initialize the elements in z using a for loop
18
InitArray.cs Program Output
  • 34 // output values for each array
  • 35 for ( int i 0 i lt ARRAY_SIZE i )
  • 36 output i "\t" x i "\t"
    y i
  • 37 "\t" z i "\n"
  • 38
  • 39 MessageBox.Show( output,
  • 40 "Initializing an
    array of int values",
  • MessageBoxButtons.OK,
  • MessageBoxIcon.Informati
    on )
  • 42
  • 43 // end Main
  • 44
  • 45 // end class InitArray

19
SumArray.cs Program Output
  • 1 // Fig. 7.4 SumArray.cs
  • 2 // Computing the sum of the elements in an
    array.
  • 3
  • 4 using System
  • 5 using System.Windows.Forms
  • 6
  • 7 class SumArray
  • 8
  • 9 // main entry point for application
  • 10 static void Main( string args )
  • 11
  • 12 int a 1, 2, 3, 4, 5, 6, 7, 8, 9,
    10
  • 13 int total 0
  • 14
  • 15 for ( int i 0 i lt a.Length i )
  • 16 total a i
  • 17
  • 18 MessageBox.Show( "Total of array
    elements " total,
  • 19 "Sum the elements of
    an array",

20
Histogram.cs
  • 1 // Fig. 7.5 Histogram.cs
  • 2 // Using data to create a histogram.
  • 3
  • 4 using System
  • 5 using System.Windows.Forms
  • 6
  • 7 class Histogram
  • 8
  • 9 // main entry point for application
  • 10 static void Main( string args )
  • 11
  • 12 int n 19, 3, 15, 7, 11, 9, 13,
    5, 17, 1
  • 13 string output ""
  • 14
  • 15 output "Element\tvalue\tHistogram\n"
  • 16
  • 17 // build output
  • 18 for ( int i 0 i lt n.Length i )
  • 19

21
Histogram.cs Program Output
22
Outline
  • Admin. and review
  • Arrays
  • Declaration and initialization of arrays
  • Examples
  • command line array
  • strings as arrays
  • using array elements as counters

23
Example 1 Command-Line Arguments
  • The signature of the Main method indicates that
    it takes an array of string as parameter
  • These values come from command-line arguments
    that are provided when the program is invoked
  • For example, the following invocation of the
    interpreter passes an array of three string
    objects into Main
  • C\gt Calculator 2 3
  • These strings are stored at positions 0-2 of the
    parameter
  • See Calculator.cs

24
Example 2 strings as Arrays
  • You can use a string as an array
  • You can access the length of a string using the
    Length property
  • You can access each character of a string using
    , e.g.,string resp Console.ReadLine().ToUpper
    ()for (int i 0 i lt resp.Length i)
    Console.Write( respi )

25
Example 3 Using the Elements of an Array as
Counters
  • Use array elements to keep track of number of
    occurrences
  • Example Die Rolling Program
  • Use the value of rolling the dice as the
    subscript for the array
  • Increment the corresponding array element when a
    die value is rolled

26
RollDie.cs
  • 1 // Fig. 7.6 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.F
    orm
  • 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

Create a Random object
Declare an integer array frequency and allocate
it enough memory to hold 7 integers
27
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 )

28
RollDie.cs
  • 71
  • 72 displayTextBox.Text
    "Face\tFrequency\tPercent\n"
  • 73
  • 74 // output frequency values
  • 75 for ( int x 1 x lt frequency.Length
    x )
  • 76
  • 77 displayTextBox.Text x "\t"
  • 78 frequency x "\t\t"
    String.Format( "0N",
  • 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

Get a random number from 1 to 6
Display die image corresponding to the number
rolls
29
RollDie.cs Program Output
30
StudentPoll.cs
  • 1 // Fig. 7.7 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

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
31
Backup Slides
32
strings as Arrays
  • You can use a string as an array
  • You can access the length of a string using the
    Length property
  • You can access each character of a string using
  • You can convert between character arrays and
    strings easily
  • create a string from a character array using
    strings constructor
  • extract part of a string to a character array
    using strings CopyTo method

33
StringConstructor.cs
  • 1 // Fig. 15.1 StringConstructor.cs
  • 2 // Demonstrating String class constructors.
  • 3
  • 4 using System
  • 5 using System.Windows.Forms
  • 6
  • 7 // test several String class constructors
  • 8 class StringConstructor
  • 9
  • 10 // The main entry point for the
    application.
  • 11 STAThread
  • 12 static void Main( string args )
  • 13
  • 14 string output
  • 15 string originalString, string1,
    string2,
  • 16 string3, string4
  • 17
  • 18 char characterArray
  • 19 'b', 'i', 'r', 't', 'h', ' ',
    'd', 'a', 'y'

String declarations
Allocate char array characterArray to contain
nine characters
Set string1 to reference the same string literal
String constructor takes a character array as
argument
String constructor takes a char array and the
starting point of the array and the length
Using string constructed with a character and an
int specifying number of times to repeat
character in the string
34
StringConstructor.csProgram Output
  • 33 MessageBox.Show( output, "String Class
    Constructors",
  • 34 MessageBoxButtons.OK,
    MessageBoxIcon.Information )
  • 35
  • 36 // end method Main
  • 37
  • 38 // end class StringConstructor

35
StringMethods.cs
  • 1 // Fig. 15.2 StringMethods.cs
  • 2 // Using the indexer, property Length and
    method CopyTo
  • 3 // of class String.
  • 4
  • 5 using System
  • 6 using System.Windows.Forms
  • 7
  • 8 // creates string objects and displays
    results of using
  • 9 // indexer and methods Length and CopyTo
  • 10 class StringMethods
  • 11
  • 12 // The main entry point for the
    application.
  • 13 STAThread
  • 14 static void Main( string args )
  • 15
  • 16 string string1, output
  • 17 char characterArray
  • 18
  • 19 string1 "hello there"

36
StringMethods.csProgram Output
  • 36 // copy characters from string1 into
    characterArray
  • 37 string1.CopyTo( 0, characterArray, 0,
    5 )
  • 38 output "\nThe character array is
    "
  • 39
  • 40 for ( int i 0 i lt
    characterArray.Length i )
  • 41 output characterArray i
  • 42
  • 43 MessageBox.Show( output,
    "Demonstrating the string "
  • 44 "Indexer, Length Property and
    CopyTo method",
  • 45 MessageBoxButtons.OK,
    MessageBoxIcon.Information )
  • 46
  • 47 // end method Main
  • 48
  • 49 // end class StringMethods

Index of string to begin copying
Index of location to put into character array
Number of characters to copy from string
character array to copy to
Method Copyto called by string1
Write a Comment
User Comments (0)
About PowerShow.com