Advanced Programming Chapter 8: Arrays

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

4.1Introduction Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based arrays (C-like) –Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
 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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
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.
The University of Texas – Pan American
 2006 Pearson Education, Inc. All rights reserved Arrays.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
 Pearson Education, Inc. All rights reserved Arrays.
 Pearson Education, Inc. All rights reserved Arrays.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX 78539
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Jozef Goetz,  Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
Arrays Chapter 7. 2 Declaring and Creating Arrays Recall that an array is a collection of elements all of the _____________ Array objects in Java must.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
 2005 Pearson Education, Inc. All rights reserved Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
A DVANCED P ROGRAMMING C HAPTER 8: A RRAYS Dr Shahriar Bijani Spring 2016.
Lecture 4: Chapter 7 - Arrays Outline Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods.
4.1Introduction Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based arrays (C-like) –Arrays.
7.1 Introduction Arrays Arrays are data structures consisting of data items of the same type “Static” entities They remain the same size once they are.
Chapter 11 - JavaScript: Arrays
Arrays Chapter 7.
Chapter 7: User-Defined Functions II
© 2016 Pearson Education, Ltd. All rights reserved.
Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays
8 Arrays.
JavaScript: Functions.
The University of Texas – Pan American
Data Structures Array - Code.
Java How to Program, Late Objects Version, 10/e
Pass by Reference, const, readonly, struct
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
C Arrays.
7 Arrays.
Advanced Programming Lecture 02: Introduction to C# Apps
Advanced Programming Chapters 5 & 6: Control Structures
7 Arrays.
Arrays Kingdom of Saudi Arabia
8 Arrays.
Arrays Outline Introduction Arrays Declaring Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
7 Arrays.
Introduction To Programming Information Technology , 1’st Semester
Object Oriented Programming in java
Cs212: Data Structures Computer Science Department Lecture 2: Arrays.
Data Structures Array - Code.
MSIS 655 Advanced Business Applications Programming
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays
Arrays Chapter 7.
4.1 Introduction Arrays A few types Structures of related data items
Arrays Kingdom of Saudi Arabia
7 Arrays.
Object Oriented Programming
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays Arrays A few types Structures of related data items
Visual Programming COMP-315
4.1 Introduction Arrays A few types Structures of related data items
CSCI 3328 Object Oriented Programming in C# Chapter 7: Arrays – Exercises UTPA – Fall 2012 This set of slides is revised from lecture slides of Prof.
Presentation transcript:

Advanced Programming Chapter 8: Arrays Dr Shahriar Bijani Spring 2016

Reference Visual C# 2012 How to Program, Paul Deitel & Harvey Deitel, 5th Edition, Prentice Hall.

7.2 Arrays A group of neighboring memory locations Same name Same type Refer to an element in the array by position number (or subscript) First element is element zero First element of array c is c[ 0 ]

7.2 Arrays -45 6 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 in array c Name of array (Note that all elements of this array have the same name, c) Fig. 8.1 A 12-element array.

8.3 Declaring and Creating Arrays Arrays of value types: each element contains one value int[] c = new int[ 12 ]; Array declarations and initializations can be in 2 statements: int[] c; c = new int[ 12 ]; Arrays of reference types: each element of the array is a reference to an object of that type string[] s1 = new string[ 10 ], s2 = new string[ 50 ];

// Fig. 8.2: InitArray.cs Creating an array. using System; public class InitArray { public static void Main( string[] args ) int[] array; // declare array named array // create the space for array and initialize to zeros array = new int[ 5 ]; // 5 int elements Console.WriteLine( "{0}{1,8}", "Index", "Value" ); // output each array element's value for ( int counter = 0; counter < array.Length; ++counter ) Console.WriteLine( "{0,5}{1,8}", counter, array[ counter ] ); } // end Main } // end class InitArray

Resizing & Initializing an Array Arrays are fixed-length entities, but you can use the static Array method Resize int[] newArray = new int[ 5 ]; Array.Resize( ref newArray, 10 ); Copies the contents of the old array into the new array If the new array is smaller than the old array, it is cut without warning Initializing: Arrays can be initialized with initializer lists int[] n = { 10, 20, 30, 40, 50 }; number of elements in list = the size of array

Examples of Using Arrays // Fig. 8.4: InitArray.cs Calculating values as elements of an array. using System; public class InitArray { public static void Main( string[] args ) const int ARRAY_LENGTH = 10; // create a named constant int[] array = new int[ ARRAY_LENGTH ]; // create array // calculate value for each array element for ( int counter = 0; counter < array.Length; ++counter ) array[ counter ] = 2 + 2 * counter; Console.WriteLine( "{0}{1,8}", "Index", "Value" ); // headings // output each array element's value Console.WriteLine( "{0,5}{1,8}", counter, array[ counter ] ); } // end Main } // end class InitArray

// Fig. 8.6: BarChart.cs using System; public class BarChart { public static void Main( string[] args ) int[] array = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 }; // distribution Console.WriteLine( "Grade distribution:" ); // for each array element, output a bar of the chart for ( int counter = 0; counter < array.Length; ++counter ) // output bar labels ( "00-09: ", ..., "90-99: ", "100: " ) if ( counter == 10 ) Console.Write( " 100: " ); else Console.Write( "{0:D2}-{1:D2}: ", counter * 10, counter * 10 + 9 ); // display bar of asterisks for ( int stars = 0; stars < array[ counter ]; ++stars ) Console.Write( "*" ); Console.WriteLine(); // start a new line of output } // end outer for } // end Main } // end class BarChart

8.6 foreach Statement foreach iterates through all the elements of an array (or a collection) foreach ( type identifier in arrayName ) statement e.g. for (int counter = 0; counter < array.Length; ++counter) total += array[counter]; foreach ( int number in array ) total += number; It can be used in place of for whenever you do not need access to the counter (index of array elements)

// Fig. 8.12: ForEachTest.cs // Using the foreach statement to total integers in an array. using System; public class ForEachTest { public static void Main( string[] args ) int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // add each element's value to total foreach ( int number in array ) total += number; MessageBox.Show("Total of array elements: "+ total, "Output", MessageBoxButtons.OK, MessageBoxIcon.Information); } // end Main } // end class ForEachTest

Common Programming Error 8.4 The foreach statement’s iteration variable can be used only to access array elements It cannot be used to modify elements. Any attempt to change the value of the iteration variable in the body of a foreach statement will cause a compilation error.

8.7 Passing Arrays / Array Elements to Methods Arrays are passed by reference Array elements are passed by value

public class PassArray { // Main creates array and calls ModifyArray and ModifyElement public static void Main( string[] args ) int[] array = { 1, 2, 3, 4, 5 }; Console.WriteLine("Effects of passing reference to entire array:\n" + "The values of the original array are:" ); // output original array elements foreach ( int value in array ) Console.Write( " {0}", value ); ModifyArray( array ); // pass array reference Console.WriteLine( "\n\nThe values of the modified array are:" ); // output modified array elements Console.WriteLine("\n\nEffects of passing array element value:\n" + "array[3] before ModifyElement: {0}", array[ 3 ] ); ModifyElement( array[ 3 ] ); // attempt to modify array[ 3 ] Console.WriteLine( "array[3] after ModifyElement: {0}", array[ 3 ] ); } // end Main

// multiply each element of an array by 2 public static void ModifyArray( int[] array2 ) { for ( int counter = 0; counter < array2.Length; ++counter ) array2[ counter ] *= 2; } // end method ModifyArray // multiply argument by 2 public static void ModifyElement( int element ) element *= 2; Console.WriteLine( "Value of element in ModifyElement: {0}", element ); } // end method ModifyElement } // end class PassArray

8.8 Passing Arrays by Value and by Reference Passing value types to methods A copy of the variable is sent Any changes to variable in method do not effect the original variable Passing reference types to methods A copy of the reference to the object is sent Any changes to the contents of the object in the method, do effect the object outside the method Any changes to the reference in the method do not effect the original variable Keyword ref may be used to pass arguments to methods Value type variables are not copied References to objects are not copied: modifying the reference in the method will modify the reference outside the method Programmers have to be careful when using ref May lead to references being set to null

// Fig. 8. 14:ArrayReferenceTest // Fig.8.14:ArrayReferenceTest.cs Testing the effects of passing array references by value & by ref using System; public class ArrayReferenceTest { public static void Main( string[] args ) {// create and initialize firstArray int[] firstArray = { 1, 2, 3 }; // copy the reference in variable firstArray int[] firstArrayCopy = firstArray; Console.WriteLine("Test passing firstArray reference by value" ); Console.Write( "\nContents of firstArray " + "before calling FirstDouble:\n\t" ); for ( int i = 0; i < firstArray.Length; ++i ) // display contents of firstArray Console.Write( "{0} ", firstArray[ i ] ); FirstDouble( firstArray ); // pass variable firstArray by value to FirstDouble Console.Write( "\n\nContents of firstArray after " + "calling FirstDouble\n\t" ); if ( firstArray == firstArrayCopy ) // test whether reference was changed by FirstDouble Console.WriteLine("\n\nThe references refer to the same array" ); else Console.WriteLine( "\n\nThe references refer to different arrays" ); int[] secondArray = { 1, 2, 3 }; // create and initialize secondArray int[] secondArrayCopy = secondArray; // copy the reference in variable secondArray Console.WriteLine( "\nTest passing secondArray " + "reference by reference" ); Console.Write( "\nContents of secondArray " + "before calling SecondDouble:\n\t" );

for ( int i = 0; i < secondArray for ( int i = 0; i < secondArray.Length; ++i ) // display contents of secondArray before call Console.Write( "{0} ", secondArray[ i ] ); SecondDouble( ref secondArray ); // pass variable secondArray by reference to SecondDouble Console.Write( "\n\nContents of secondArray " + "after calling SecondDouble:\n\t" ); // display contents of secondArray after method call for ( int i = 0; i < secondArray.Length; ++i ) // test whether reference was changed by SecondDouble if ( secondArray == secondArrayCopy ) Console.WriteLine( "\n\nThe references refer to the same array" ); else Console.WriteLine("\n\nThe references refer to different arrays" ); } // end Main // modify elements of array and attempt to modify reference public static void FirstDouble( int[] array ){ for ( int i = 0; i < array.Length; ++i ) // double each element's value array[ i ] *= 2; array = new int[] { 11, 12, 13 }; // create new object and assign its reference to array } // end method FirstDouble // modify elements of array and change reference array to refer to a new array public static void SecondDouble( ref int[] array ) { // double each element's value for ( int i = 0; i < array.Length; ++i ) } // end method SecondDouble } // end class ArrayReferenceTest

8.10 Multidimensional Arrays Multidimensional arrays: Arrays that require 2 (or more) subscripts to identify an element Types of Two-dimensional arrays: Rectangular arrays represent tables in which each row is the same size and each column is the same size first subscript identifies the element’s row and the second subscript the element’s column Jagged Arrays Arrays of arrays Each row can be of different length

Two-Dimentional Rectangular Arrays 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]

Initializing Two-Dimensional Rectangular Array Nested array initializing: int[,] b = { { 1, 2, 3 }, { 4, 5, 6 } }; Creating Two-Dimensional Arrays int[,] b; b = new int[2, 3]; Number of initializers in each row must be the same int[,] b = { { 1, 2 , 3}, { 4, 5 } };// COMPILATION ERROR S

Initializing Two-Dimensional Jagged Array Nested array initializing: int[][] jagged = { new int[] { 1, 2 }, new int[] { 3 }, new int[] { 4, 5, 6 } }; Jagged array can not be defined in one expression: int[][] c = new int[ 2 ][ 5 ]; // COMPILATION ERROR Each one-dimensional array in the jagged array must be initialized separately int[][] c; c = new int[2][]; // create 2 rows c[0] = new int[5]; // create 5 columns for row 0 c[1] = new int[3]; // create 3 columns for row

8.11 Case Study GradeBook Using a Rectangular Array (Fig 8.20)

8.12 Variable-Length Argument Lists Allow you to create methods that receive an arbitrary number of arguments. the keyword params and one-dimensional array- type The params modifier can be used only with the last parameter of the parameter list

// Fig. 8. 22: Using variable-length argument lists // Fig. 8.22: Using variable-length argument lists. public class ParamArrayTest { // calculate average public static double Average( params double[] numbers ) { double total = 0.0; // initialize total // calculate total using the foreach statement foreach ( double d in numbers ) total += d; return total / numbers.Length; } // end method Average public static void Main( string[] args ) double d1 = 10.0, d2 = 20.0, d3 = 30.0, d4 = 40.0; Console.WriteLine("d1 = {0:F1}\nd2 = {1:F1}\nd3 = {2:F1}\nd4 = {3:F1}\n",d1, d2, d3, d4 ); Console.WriteLine( "Average of d1 and d2 is {0:F1}", Average( d1, d2 ) ); Console.WriteLine( "Average of d1, d2 and d3 is {0:F1}", Average( d1, d2, d3 ) ); Console.WriteLine( "Average of d1, d2, d3 and d4 is {0:F1}", Average( d1, d2, d3, d4 ) ); } // end Main } // end class ParamArrayTest

8.13 Using Command-Line Arguments It is possible to pass arguments from the command line to an app By including a parameter of type string[] in the parameter list of Main. By convention, this parameter is named args!

// Fig. 8. 23: Using command-line arguments to initialize an array // Fig. 8.23: Using command-line arguments to initialize an array. using System; public class InitArray { public static void Main( string[] args ){ if ( args.Length != 3 ) // check number of command-line arguments Console.WriteLine( "Error: Please re-enter the entire command, including\n" + "an array size, initial value and increment." ); else { int arrayLength = Convert.ToInt32( args[ 0 ] ); // get array size from 1st command-line arg int[] array = new int[ arrayLength ]; // create array // get initial value and increment from command-line argument int initialValue = Convert.ToInt32( args[ 1 ] ); int increment = Convert.ToInt32( args[ 2 ] ); // calculate value for each array element for ( int counter = 0; counter < array.Length; ++counter ) array[ counter ] = initialValue + increment * counter; Console.WriteLine( "{0}{1,8}", "Index", "Value" ); // display array index and value Console.WriteLine( "{0,5}{1,8}", counter, array[ counter ] ); } // end else } // end Main } // end class InitArray

Quiz 2 الف) خطاها را مشخص کنید. class Error { public Error(double pi){ PI = pi; ch = "A"; } public int M1(){ foreach(x in Code) { x *=2; string output += x; } const int Size = 100; readonly double PI; char ch; public char CH { set{ return ch; } ب) خروجی چیست؟   int c = 0; for (int i=0; i<10; i++) for(int j=1; j<=10; j++) for(int k=1; k<=j; k++) c++; Console.WriteLine(c);

class Exam3 { public Exam3() { char[] A={'A','C'}; char a='a', b = 'b'; float c= 3.4F; Console.Writeln(Change(A,out a,ref b,c)+" "+ A[0]+" "+ a +"‌‌‌ "+ b+" "+ c); } public int Change(char[] a, out char b, ref char c, float d ) { for(int A=0; A< a.Length ; ) Console.Writeln(A + " " + ++a[A++]); a = null; b='5'; c = (char)65; d = 1.2F; return (int)c; }

0 B 1 D 65 B 5 A 3.4