35
1 Advanced Programming Array

1 Advanced Programming Array. 2 PrintMonth( month, year ) January 1900 Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Embed Size (px)

Citation preview

1

Advanced Programming

Array

2

PrintMonth( month, year )

January 1900Sun Mon Tue Wed Thu Fri Sat

1 2 3 4 5 6

7 8 9 10 11 12 13

14 15 16 17 18 19 20

21 22 23 24 25 26 27

28 29 30 31

3

Design

year = GetYearFromUser()

month = GetMonthFromUser()

month ?= 0

PrintMonth(month, year) PrintYear(year)

no

yes

4

Calendar: Requirements

• Get a year from the user, the earliest year should be 1900

• Get a month from the user, the input should be from 0 to 12– If 0, print calendar for all 12 months

– Otherwise, print the calendar of the month of the year

5

Random Number Generation

• Class Random – Within namespace System– Pseudo-random

• The numbers are generated using an equation with a seed– The seed is usually the exact time of day

– Random randomObject = new Random();– randomObject.Next()

• Returns a number from 0 to Int32.MaxValue– Int32.MaxValue = 2,147,483,647

– randomObject.Next( x )• Returns a value from 0 up to but not including x (scaling)

– randomObject.Next( x, y )• Returns a number between x (shift) and up to but not including

y (scaling)

using System;

using System.Windows.Forms;

class RandomInt {

static void Main( string[] args ) {

int value;

string output = "";

Random randomInteger = new Random();

for ( int i = 1; i <= 20; i++ ) {

// pick random integer between 1 and 6

value = randomInteger.Next( 1, 7 );

output += value + " ";

if ( i % 5 == 0 )

output += "\n";

} // end for structure

MessageBox.Show( output, "20 Random Numbers from 1

to 6",

MessageBoxButtons.OK, MessageBoxIcon.Information );

} // end Main

} // end class RandomInt

8

Arrays

• A group of contiguous memory locations – Same name

– Same type

• Refer to particular element in the array by position number

• Can refer to any element by giving the name of the array followed by the position number (subscript) of the element in square brackets ([])

• First element is the zeroth element– First element of array c is c[ 0 ]

Types Arrays

• Arrays allow a group of elements of a specific type to be stored in a contiguous block of memory

• Arrays are reference types• Derived from System.Array• Zero-based• Can be multidimensional

– Arrays know their length(s) and rank

• Bounds checking

10

Arrays-45

6

0

72

1543

-89

0

62

-3

1

6453

-78c[ 11 ]

c[ 10 ]

c[ 9 ]

c[ 8]

c[ 7 ]

c[ 4 ]

c[ 3 ]

c[ 2 ]

c[ 1 ]

c[ 0 ]

c[ 6 ]

c[ 5 ]

Position number (index or subscript) of the element within array c

Name of array (Note that all elements of this array have the same name, c)

11

Declaring and Allocating Arrays

• Programmer specifies the type of the

elements of the array

• new operator to allocate dynamically the

number of elements in the array

• In arrays of value types, each element

contains one value of the declared type

12

Allocating an Array and Initializing It

• Arrays can be allocated using the word new to specify how many elements the array should hold

• Arrays can be initialized with initializer lists– 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

int[] c = new int[12];

int[]c;

c = new int[12];

Types Arrays

• Declare

• Allocate

• Initialize

• Access and assign

• Enumerate

int[] primes;

int[] primes = new int[9];

int[] prime = new int[] {1,2,3,5,7,11,13,17,19};

int[] prime = {1,2,3,5,7,11,13,17,19};

prime2[i] = prime[i];

foreach (int i in prime) Console.WriteLine(i);

InitArray.cs

using System;

using System.Windows.Forms;

class InitArray {

static void Main( string[] args ) {

string output = "";

int[] x;

x = new int[ 10 ];

int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

const int ARRAY_SIZE = 10; int[] z;

z = new int[ ARRAY_SIZE ];

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

z[ i ] = 2 + 2 * i;

output += "Subscript Array x\tArray y\tArray z\n";

for ( int i = 0; i < ARRAY_SIZE; i++ )

output += i + "\t" + x[ i ] + "\t" + y[ i ] +

"\t" + z[ i ] + "\n";

MessageBox.Show( output,

"Initializing an array of int values",

MessageBoxButtons.OK,

MessageBoxIcon.Information ); } } // end class

Write application to output the following message?

Example

• Write a console application that generate 10

random numbers and stores them in an array

and then finds out how many times each of

these numbers occurs in this array

17

Histogram.cs

using System;

using System.Windows.Forms;

class Histogram {

static void Main( string[] args ) {

int[] n = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };

string output = "";

output += "Element\tvalue\tHistogram\n";

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

output += "\n" + i + "\t" + n[ i ] + "\t";

for ( int j = 1; j <= n[ i ]; j++ ) // print a bar

output += "*";

}

MessageBox.Show( output, "Histogram Printing Program",

MessageBoxButtons.OK, MessageBoxIcon.Information );

} } // end class Histogram

Write application to output the following message?

StudentPoll.cs

using System;

using System.Windows.Forms;

class StudentPoll {

// main entry point for application

static void Main( string[] args ) {

int[] responses = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1,

6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 };

int[] frequency = new int[ 11 ];

string output = "";

for ( int answer = 0; answer < responses.Length; answer++ )

++frequency[ responses[ answer ] ];

output += "Rating\tFrequency\n";

for ( int rating = 1; rating < frequency.Length; rating++ )

output += rating + "\t" + frequency[ rating ] + "\n";

MessageBox.Show( output, "Student poll program",

MessageBoxButtons.OK, MessageBoxIcon.Information );

} } // end class StudentPoll

foreach Statement

• Iteration of arrays

• Iteration of user-defined collections

Int[] X = {87, 68, 94, 100, 83, 78, 85, 91, 76, 87}Int[] X = {87, 68, 94, 100, 83, 78, 85, 91, 76, 87}Int sum = 0;Int sum = 0;

Foreach (int number in X)Foreach (int number in X)sum += number;sum += number;

public static void Main(string[] args) {public static void Main(string[] args) { foreach (string s in args) Console.WriteLine(s);foreach (string s in args) Console.WriteLine(s);}}

22

Two-Dimensional Arrays

• A one-dimensional array stores a list of values

• A two-dimensional array, also called double-subscripted array, can be thought of as a table of values, with rows and columns– a two-dimensional array element is referenced

using two index numbers

Types Arrays

• Multidimensional arrays– Rectangular

• int[,] matR = new int[2,3];• Can initialize declaratively

• int[,] matR = new int[2,3] { {1,2,3}, {4,5,6} };

– Jagged• An array of arrays

• int[][] matJ = new int[2][];• Must initialize procedurally

24

Two Types of Double-Subscripted Arrays

• rectangular arrays– often represent tables in which each row is the same size and each

column is the same size, e.g.,int[,] a1 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };int[,] a11 = new int[3,4];

• jagged arrays• arrays of arrays• arrays that compose jagged arrays can be of different lengths, e.g.,

int[][] array2 = new int[ 3 ][];array2[ 0 ] = new int[] { 1, 2 };array2[ 1 ] = new int[] { 3 };array2[ 2 ] = new int[] { 4, 5, 6 };array2[2][1] = 3;

25

Double-Subscripted Arrays

Double-subscripted array with three rows and four columns.

Row 0

Row 1

Row 2

Column 1

Column 0 Column 2 Column 3

a[0][0] a[0][3]a[0][1] a[0][2]

a[1][0] a[1][3]a[1][1] a[1][2]

a[2][0] a[2][3] a[2][2]

Column index (or subscript)

Row index (or subscript)

Array name

a[2][1]

Outline

TwoDimensionalArrays.cs

1 // Fig. 7.14: TwoDimensionalArrays.cs2 // Initializing two-dimensional arrays.3 using System;4 using System.Drawing;5 using System.Collections;6 using System.ComponentModel;7 using System.Windows.Forms;8 using System.Data;9 10 public class TwoDimensionalArrays : System.Windows.Forms.Form11 {12 private System.Windows.Forms.Button showOutputButton;13 private System.Windows.Forms.Label outputLabel;14 15 // Visual Studio .NET generated code16 17 [STAThread]18 static void Main() 19 {20 Application.Run( new TwoDimensionalArrays() );21 }22 23 private void showOutputButton_Click( object sender, 24 System.EventArgs e )25 {26 // declaration and initialization of rectangular array27 int[,] array1 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };28 29 // declaration and initialization of jagged array30 int[][] array2 = new int[ 3 ][];31 array2[ 0 ] = new int[] { 1, 2 };32 array2[ 1 ] = new int[] { 3 };33 array2[ 2 ] = new int[] { 4, 5, 6 };34 35 outputLabel.Text += "Values in array1 by row are\n";

Declare and initialize a rectangular integer array named array1

Declare a jagged array named array2 with 3 rows

Initialize the first element in array2 to be an array that contains two integers

Initialize the second element in array2 to be an array that contains 1 integer

Initialize the third element in array2 to be an array that contains 3 integers

Outline

TwoDimensionalArrays.cs

Program Output

36 37 // output values in array138 for ( int i = 0; i < array1.Length; i++ )39 {40 for ( int j = 0; j < array1[i].Length; j++ ) 41 outputLabel.Text += array1[ i, j ] + " ";42 43 outputLabel.Text += "\n";44 }45 46 outputLabel.Text += "\nValues in array2 by row are\n";47 48 // output values in array249 for ( int i = 0; i < array2.Length; i++ )50 {51 for ( int j = 0; j < array2[ i ].Length; j++ )52 outputLabel.Text += array2[ i ][ j ] + " ";53 54 outputLabel.Text += "\n";55 }56 57 } // end method showOutputButton_Click5859 } // end class TwoDimensionalArrays

Outline

DoubleArray.cs

1 // Fig. 7.15: DoubleArray.cs2 // Manipulating a double-subscripted array.3 using System;4 using System.Drawing;5 using System.Collections;6 using System.ComponentModel;7 using System.Windows.Forms;8 using System.Data;9 10 public class DoubleArray : System.Windows.Forms.Form11 {12 private System.Windows.Forms.Button showOutputButton;13 private System.Windows.Forms.Label outputLabel;14 15 private int[][] grades;16 private int students, exams;17 18 // Visual Studio .NET generated code19 20 [STAThread]21 static void Main() 22 {23 Application.Run( new DoubleArray() );24 }25 26 private void showOutputButton_Click( object sender, 27 System.EventArgs e )28 29 {30 grades = new int[ 3 ][];31 grades[ 0 ] = new int[]{ 77, 68, 86, 73 };32 grades[ 1 ] = new int[]{ 96, 87, 89, 81 };33 grades[ 2 ] = new int[]{ 70, 90, 86, 81 };34

Initialize array grades to have 3 rows

Initialize each element in array grades

Outline

DoubleArray.cs

35 students = grades.Length; // number of students36 exams = grades[ 0 ].Length; // number of exams37 38 // line up column headings39 outputLabel.Text += " ";40 41 // output the column headings42 for ( int i = 0; i < exams; i++ )43 outputLabel.Text += "[" + i + "] ";44 45 // output the rows46 for ( int i = 0; i < students; i++ )47 {48 outputLabel.Text += "\ngrades[" + i + "] ";49 50 for ( int j = 0; j < exams; j++ )51 outputLabel.Text += grades[ i ][ j ] + " ";52 }53 54 outputLabel.Text += "\n\nLowest grade: " + Minimum() +55 "\nHighest grade: " + Maximum() + "\n";56 57 for ( int i = 0; i < students; i++ )58 outputLabel.Text += "\nAverage for student " + i + " is " +59 Average( grades[ i ] );60 61 } // end method showOutputButton_Click62

Output each row

Output each element of the row

Output the minimum and maximum grades

Output the average for each row

Outline

DoubleArray.cs

63 // find minimum grade in grades array64 public int Minimum()65 {66 int lowGrade = 100;67 68 for ( int i = 0; i < students; i++ )69 70 for ( int j = 0; j < exams; j++ )71 72 if ( grades[ i ][ j ] < lowGrade )73 lowGrade = grades[ i ][ j ];74 75 return lowGrade;76 }77 78 // find maximum grade in grades array79 public int Maximum()80 {81 int highGrade = 0;82 83 for ( int i = 0; i < students; i++ )84 85 for ( int j = 0; j < exams; j++ )86 87 if ( grades[ i ][ j ] > highGrade )88 highGrade = grades[ i ][ j ];89 90 return highGrade;91 }92

Examine each element in grades array

If the current array element is less then the lowest grade, set the value of lowGrade to be the current element

Examine each element in grades array

If the current array element higher than the highest grade, set the value of highGrade to be the current element

Outline

DoubleArray.cs

Program Output

93 // determine average grade for a particular student94 public double Average( int[] setOfGrades )95 {96 int total = 0;97 98 for ( int i = 0; i < setOfGrades.Length; i++ )99 total += setOfGrades[ i ];100 101 return ( double ) total / setOfGrades.Length;102 }103 104 } // end class DoubleArray

Total the grades for the array

Divide the total by the number of grades

Example

• Construct C# console application to solve the

following problem. A football team plays n games

per year in its league. Given n and the scores of all

of the games the team played this year (both the

team’s score and its opponent’s score for each

game), compute the team’s margin of victory in

the games that it played (win = 3, tied = 1 and

ignore lost).

32

Example

• The main voltage supplied by a substation is measured at hourly intervals over a 72-hour period, and a report made. Write a program to read in the 72 reading array and determine:

• the mean voltage measured• the hours at which the recorded voltage varies

from the mean by more than 10%• any adjacent hours when the change from one

reading to the next is greater than 15% of the mean value

33

Example

• We wish to solve the following problem using C#. given an array A, print all permutations of A (print all values of A in every possible order). For example, A contained the strings “apple”, “banana”, and “coconut”, the desired output is:

• apple banana coconut• apple coconut banana• banana apple coconut• banana coconut apple• coconut apple banana• coconut banana apple

34

Example

• A sensitive drug cannot sustain a change in temperature of more than 30o C in a 24-hour period. The temperatures are monitored and recorded every two hours. Write console application the laboratory technician can use once a day to determine whether or not to throw the drug away.

35