Advanced Programming Array.

Slides:



Advertisements
Similar presentations
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Arrays.
Advertisements

Arrays. Introduction Arrays –Structures of related data items –Static entity - same size throughout program A few types –C-like, pointer-based arrays.
4.1Introduction Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based arrays (C-like) –Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
 2002 Prentice Hall. All rights reserved. 1 Chapter 6 - Methods Outline Note: Inconsistent with textbook subsection numbering […] 6.14Recursion 6.15 Example.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 11P. 1Winter Quarter Arrays Lecture 11.
 2003 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Multiple subscripts –a[ i ][ j ] –Tables with rows and columns –Specify.
 2002 Prentice Hall. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 Pearson Education, Inc. All rights reserved Arrays.
1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
Advanced Programming LOOP.
1 CS1120: Recursion. 2 What is Recursion? A method is said to be recursive if the method definition contains a call to itself A recursive method is a.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
 Pearson Education, Inc. All rights reserved Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 Pearson Education, Inc. All rights reserved Arrays.
Chapter 7 Arrays. A 12-element array Declaring and Creating Arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[]
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Jozef Goetz,  Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify.
Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify –Array name –Position number Format: arrayname.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
1 Lecture 8 Arrays Part II Sorting Arrays Sorting data  Important computing application  Virtually every organization must sort some data Massive.
1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing Arrays to Functions 4.6Sorting Arrays 4.7Case.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Vectors.
Advanced Programming LOOP. 2 while Repetition Structure Repetition Structure –An action is to be repeated Continues while statement is true Ends when.
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
C Lecture Notes 1 Arrays (...cont.). C Lecture Notes 2 6.6Sorting Arrays Sorting data –Important computing application –Virtually every organization must.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 11P. 1Winter Quarter Arrays Lecture 11.
Jozef Goetz,  Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
Arrays in java Unit-1 Introduction to Java. Array There are situations where we might wish to store a group of similar type of values in a variable. Array.
C++ Programming Lecture 16 Arrays – Part III The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Advanced Programming Windows Applications. Create a new Project Select a C# Windows Application.
CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Arrays 3.Declaring Arrays 4.Examples Using Arrays 5.Multidimensional Arrays 6.Multidimensional.
 2005 Pearson Education, Inc. All rights reserved Arrays.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Consecutive group of memory locations –Same name and type To refer to an element, specify.
Lecture 03 Dr. Eng. Ibrahim El-Nahry Arrays. 2 Learning Objectives Introduction to Arrays Declaring and referencing arrays Initializing Arrays Arrays.
A DVANCED P ROGRAMMING C HAPTER 8: A RRAYS Dr Shahriar Bijani Spring 2016.
Arrays 1.
Chapter 7 - Methods Outline Note: Inconsistent with textbook subsection numbering […] 7.13 Recursion […]
Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays
Advanced Programming Chapter 8: Arrays
Multidimensional Arrays
Arrays Outline Introduction Arrays Declaring Arrays
C++ Programming Lecture 16 Arrays – Part III
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
4.9 Multiple-Subscripted Arrays
Introduction To Programming Information Technology , 1’st Semester
Arrays Kingdom of Saudi Arabia
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Dale Roberts, Lecturer IUPUI
Vectors.
4.9 Multiple-Subscripted Arrays
Presentation transcript:

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() month ?= 0 yes no PrintMonth(month, year) PrintYear(year)

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

A group of contiguous memory locations 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 ]

Arrays are reference types Derived from System.Array Zero-based 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

Arrays -45 6 72 1543 -89 62 -3 1 6453 -78 c[ 11 ] c[ 10 ] c[ 9 ] c[ 8] 72 1543 -89 62 -3 1 6453 -78 c[ 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)

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 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"; InitArray.cs

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

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 Histogram.cs

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 StudentPoll.cs

Iteration of user-defined collections 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 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

Multidimensional arrays 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 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;

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.

Declare and initialize a rectangular integer array named array1 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 public class 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 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 array 27 int[,] array1 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; 28 29 // declaration and initialization of jagged array 30 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 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

Initialize array grades to have 3 rows 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 public class DoubleArray : System.Windows.Forms.Form 11 { 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 code 19 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 DoubleArray.cs Initialize array grades to have 3 rows Initialize each element in array grades

Output each element of the 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 46 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_Click 62 Output each row DoubleArray.cs Output each element of the row Output the minimum and maximum grades Output the average for each row

Examine each element in grades array 63 // find minimum grade in grades array 64 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 array 79 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 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 93 // determine average grade for a particular student 94 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 DoubleArray.cs Program Output 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).

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

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

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.