Advanced Programming
Download
1 / 35

Advanced Programming - PowerPoint PPT Presentation


  • 207 Views
  • Uploaded on

Advanced Programming. Array. 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 21 22 23 24 25 26 27 28 29 30 31. Design. year = GetYearFromUser(). month = GetMonthFromUser().

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Advanced Programming' - genera


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Printmonth month year
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

21 22 23 24 25 26 27

28 29 30 31


Design
Design

year = GetYearFromUser()

month = GetMonthFromUser()

month ?= 0

yes

no

PrintMonth(month, year)

PrintYear(year)


Calendar requirements
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


Random number generation
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)


Advanced programming

using System;

using System.Windows.Forms;

class RandomInt {

staticvoid 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


Advanced programming

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

MessageBoxButtons.OK, MessageBoxIcon.Information );

} // end Main

} // end class RandomInt


Arrays
Arrays

  • A group of contiguous memory locations

    • Same name

    • Same type

  • Refer to particular element in the array by positionnumber

  • 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
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


Arrays1

c[ 0 ]

-45

c[ 1 ]

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

6

c[ 2 ]

0

c[ 3 ]

72

c[ 4 ]

1543

c[ 5 ]

-89

c[ 6 ]

0

c[ 7 ]

62

c[ 8]

-3

c[ 9 ]

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

1

c[ 10 ]

6453

c[ 11 ]

-78

Arrays


Declaring and allocating arrays
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


Allocating an array and initializing it
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 arrays1
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

InitArray.cs

using System;

using System.Windows.Forms;

class InitArray{

staticvoid Main( string[] args ) {

string output = "";

int[] x;

x = newint[ 10 ];

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

constintARRAY_SIZE = 10; int[] z;

z = newint[ ARRAY_SIZE ];

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

z[ i ] = 2 + 2 * i;

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


Advanced programming

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



Example
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


Histogram cs

Histogram.cs

using System;

using System.Windows.Forms;

class Histogram{

staticvoid 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



Studentpoll cs

StudentPoll.cs

using System;

using System.Windows.Forms;

class StudentPoll{

// main entry point for application

staticvoid 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 = newint[ 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
foreach Statement

  • Iteration of arrays

  • Iteration of user-defined collections

public static void Main(string[] args) {

foreach (string s in args) Console.WriteLine(s);

}

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

Int sum = 0;

Foreach (int number in X)

sum += number;


Two dimensional arrays
Two-Dimensional Arrays

  • A one-dimensional array stores a list of values

  • A two-dimensional array, also calleddouble-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 arrays2
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


Two types of double subscripted arrays
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 = newint[,] { { 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 = newint[ 3 ][];array2[ 0 ] = newint[] { 1, 2 };array2[ 1 ] = newint[] { 3 };array2[ 2 ] = newint[] { 4, 5, 6 };array2[2][1] = 3;


Double subscripted arrays
Double-Subscripted Arrays

Column 0

Column 1

Column 2

Column 3

Row 0

a[0][0]

a[0][1]

a[0][2]

a[0][3]

Row 1

a[1][0]

a[1][1]

a[1][2]

a[1][3]

Row 2

a[2][0]

a

[2][1]

a[2][2]

a[2][3]

Column index (or subscript)

Row index (or subscript)

Array name

Double-subscripted array with three rows and four columns.


Twodimensionalarrays cs

1 // Fig. 7.14: TwoDimensionalArrays.cs

2 // 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 publicclass TwoDimensionalArrays : System.Windows.Forms.Form

11 {

12 private System.Windows.Forms.Button showOutputButton;

13 private System.Windows.Forms.Label outputLabel;

14

15 // Visual Studio .NET generated code

16

17 [STAThread]

18 staticvoid Main()

19 {

20 Application.Run( new TwoDimensionalArrays() );

21 }

22

23 privatevoid showOutputButton_Click( object sender,

24 System.EventArgs e )

25 {

26 // declaration and initialization of rectangular array

27int[,] array1 = newint[,] { { 1, 2, 3 }, { 4, 5, 6 } };

28

29 // declaration and initialization of jagged array

30int[][] array2 = newint[ 3 ][];

31 array2[ 0 ] = newint[] { 1, 2 };

32 array2[ 1 ] = newint[] { 3 };

33 array2[ 2 ] = newint[] { 4, 5, 6 };

34

35 outputLabel.Text += "Values in array1 by row are\n";

Declare and initialize a rectangular integer array named array1

TwoDimensionalArrays.cs

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


Twodimensionalarrays cs program output

36

37 // output values in array1

38 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 array2

49 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_Click

58

59 } // end class TwoDimensionalArrays

TwoDimensionalArrays.cs Program Output


Doublearray cs

1 // Fig. 7.15: DoubleArray.cs

2 // 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 publicclass DoubleArray : System.Windows.Forms.Form

11 {

12 private System.Windows.Forms.Button showOutputButton;

13 private System.Windows.Forms.Label outputLabel;

14

15 privateint[][] grades;

16 privateint students, exams;

17

18 // Visual Studio .NET generated code

19

20 [STAThread]

21 staticvoid Main()

22 {

23 Application.Run( new DoubleArray() );

24 }

25

26 privatevoid showOutputButton_Click( object sender,

27 System.EventArgs e )

28

29 {

30 grades = newint[ 3 ][];

31 grades[ 0 ] = newint[]{ 77, 68, 86, 73 };

32 grades[ 1 ] = newint[]{ 96, 87, 89, 81 };

33 grades[ 2 ] = newint[]{ 70, 90, 86, 81 };

34

DoubleArray.cs

Initialize array grades to have 3 rows

Initialize each element in array grades


Doublearray cs1

Output each row

Output each element of the row

Output the minimum and maximum grades

Output the average for each row

35 students = grades.Length; // number of students

36 exams = grades[ 0 ].Length; // number of exams

37

38 // line up column headings

39 outputLabel.Text += " ";

40

41 // output the column headings

42 for ( int i = 0; i < exams; i++ )

43 outputLabel.Text += "[" + i + "] ";

44

45 // output the rows

46for ( int i = 0; i < students; i++ )

47 {

48 outputLabel.Text += "\ngrades[" + i + "] ";

49

50for ( 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

57for ( int i = 0; i < students; i++ )

58 outputLabel.Text += "\nAverage for student " + i + " is " +

59 Average( grades[ i ] );

60

61 } // end method showOutputButton_Click

62

DoubleArray.cs


Doublearray cs2

63 // find minimum grade in grades array

64 publicint Minimum()

65 {

66 int lowGrade = 100;

67

68for ( int i = 0; i < students; i++ )

69

70 for ( int j = 0; j < exams; j++ )

71

72if ( grades[ i ][ j ] < lowGrade )

73 lowGrade = grades[ i ][ j ];

74

75 return lowGrade;

76 }

77

78 // find maximum grade in grades array

79 publicint 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

90return highGrade;

91 }

92

DoubleArray.cs

Examine each element in grades array

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

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


Doublearray cs program output

Total the grades for the array

Divide the total by the number of grades

93 // determine average grade for a particular student

94 publicdouble Average( int[] setOfGrades )

95 {

96 int total = 0;

97

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

99 total += setOfGrades[ i ];

100

101return ( double ) total / setOfGrades.Length;

102 }

103

104 } // end class DoubleArray

DoubleArray.cs Program Output


Example1
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).


Example2
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


Example3
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


Example4
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.