• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
C sharp chap6
 

C sharp chap6

on

  • 3,287 views

 

Statistics

Views

Total Views
3,287
Views on SlideShare
3,287
Embed Views
0

Actions

Likes
0
Downloads
101
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    C sharp chap6 C sharp chap6 Document Transcript

    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 6. Arrays in C#What is an array?Definition: An array is a collection of variables of the same type that are referred to by a commonname. Arrays provide a convenient way of grouping data which is of the same data type and is related.E.g., we can group roll numbers of all students in a class into an array called rollno since they all areintegers and represent similar quantity.Advantages of using an array:1. The main advantage of using an array is that it organizes data in such a way that it can be manipulated easily. E.g., if we have to declare 10 integer variables which represent the marks of students, it can be done in two ways: i) Declare the variables as int a, b, d, e, f, g, h, i, j; ii) Declare the collection of marks as an array and refer to the complete group with the common name marks. This is easier and more elegant than declaring 10 variables with 10 different names.2. When we declare a collection of similar data types as an array, it is easy to manipulate this collection as we just have to cycle through each element of the array.3. Arrays organize data in such a way that it can be easily sorted. Elements of an array are stored in successive memory locations.In C#, arrays are implemented as objects.Array Declaration:In C# we can declare arrays one dimension (like a list), or two dimensions (like a matrix), etc. We firstconsider one-dimensional arrays.One-Dimensional Arrays:A one-dimensional array is a list of related variables, all of the same data type. It can be a list ofintegers, or a list of floats, or a list of char data type. E.g., we may use a one-dimensional array to storethe marks obtained by a student in an examination consisting of 6 papers.How to declare a 1-D array?To declare a one-dimensional array, you will use this general form: type[ ] array-name = new type[size];Here,type declares the base type of the array. The base type determines the data type of each element thatcomprises the array. After the type, we put the square brackets. These brackets indicate that a one-dimensional array is being declared. The number of elements that the array will hold is determined bysize.
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.comThe creation of an array is a two step process as shown below: Step 1: Declare an array reference variable. Step 2: Allocate memory for the array.Thus, arrays are dynamically allocated using the new() operator.Note: In C and C++, the square brackets are put after the array name, but in C#, the square brackets are putafter the data type.Example 1: Create a one-dimensional array called marks to store the marks obtained in 5 differentsubjects. Assume int data type.Ans: int [] marks = new int[5];Example 2: Create an int array of 10 elements and link it to an array reference variable called prices.Ans: int [] prices = new int[10];We can also break up this declaration into two parts as shown below: int [] prices; prices = new int[10];Example 3: Create an float array of 20 elements and link it to an array reference variable called prices.Ans: float [] prices = new float[10];How to Create an Array?Creating an array involves three steps. We have already seen two of these steps, i.e., declaring andallocating memory. All the three steps are again shown below: Step 1: Declare an array reference variable. Step 2: Allocate memory for the array. Step 3: Put values into the memory locations.Example 4: Create an array of 5 integers and link it to an array reference variable called rollno. Assignappropriate values to these.Ans: int [] rollno = new int[5] {12, 23, 34, 58, 89};Note: In C# , the individual elements of an array are accessed by using an index inside the square brackets.Array indices start at 0. Thus, if an array contains 10 elements, the last element has an index of 9.Initializing an array:We can directly initialize an array as follows: type[ ] array-name = {val1, val2, val3, ..., valN };Page 2 of 14 Arrays
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C#There is no need to explicitly use the new operator.The following are also valid statements:Ex 1: int[] nums = new int[] { 99, 10, 100, 18, 78, 23, 63, 9, 87, 49 }; Here the keyword new is redundant.Ex 2: int[] nums; nums = new int[] { 99, 10, 100, 18, 78, 23, 63, 9, 87, 49 };Ex 3: int[] nums = new int[10] { 99, 10, 100, 18, 78, 23, 63, 9, 87, 49 }; We have specified the size and also initialized the array. But the size specified and the number of elements must be the same.Program 1: Write a program to create an array x of 10 integers. Initialize this array with the numbers1, 4, 9, 16, 25, ….. Display the elements of the array, one per line.using System;namespace Arrays2{ class Program { public static void Main() { int[] x = new int[10]; for (int i = 0; i <= 9; i++) { x[i] = (i + 1) * (i + 1); } //Now we display these values for (int i = 0; i <= 9; i++) { Console.WriteLine("x[{0}] = {1}", i, x[i]); } Console.ReadLine(); } }}Array Boundaries:C# protects arrays from under-runs or over-runs. Trying to access a member outside the boundaries ofthe array will result in an error. This is completely different from C and C++ where there is noboundary checking. In C#, if we try to access an element out of the predefined range, we get the error“IndexOutOfRangeException” and the program is terminated.Arrays Page 3 of 14
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.comProgram 2:The following example illustrates the concept of array boundaries. It generates the error and terminatesthe program.// Demonstrate an array overrun.using System;class ArrayBoundErr{ public static void Main() { int[] x = new int[10]; int i; // generate an array overrun for (i = 0; i < 20; i = i + 1) x[i] = i; }}In this program, as soon as i reaches 10, an IndexOutOfRangeException error is generated and theprogram is terminated.Array Length:In C#, all arrays are implemented as objects. The allocated size of the array is stored in a variablecalled Length.The length of an array (i.e., the size of the array, say x, can be accessed by using x.LengthThe Length property makes certain operations easier and safer – e.g., by preventing underruns andoverruns.Program 3:The following program illustrates the use of the Length property. The program reverses the contents ofan array by copying it back-to-front into another array.// Reverse an array.using System;class RevCopy{ public static void Main() { int i,j; int[] nums1 = new int[10]; int[] nums2 = new int[10]; for(i=0; i < nums1.Length; i++) nums1[i] = i; Console.Write("Original contents: "); for(i=0; i < nums1.Length; i++)Page 4 of 14 Arrays
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C# Console.Write(nums1[i] + " "); Console.WriteLine(); // reverse copy nums1 to nums2 if (nums2.Length >= nums1.Length) // make sure nums2 is long enough { for (i = 0, j = nums1.Length - 1; i < nums1.Length; i++, j--) { nums2[j] = nums1[i]; } } Console.Write("Reversed contents: "); for (i = 0; i < nums2.Length; i++) Console.Write(nums2[i] + " "); Console.WriteLine(); Console.ReadLine(); }}Program 4:Write a program that stores a list of numbers in an array and computes the maximum and minimumvalues in the list.using System;namespace ArrayMaxMin{ class Program { static void Main() { int[] x = { 21, 23, 78, 19, 8, -28, 56, 38, 99, 45}; int max, min; max = x[0]; min = x[0]; for (int i = 1; i <= 9; i++) { if (x[i] > max) max = x[i]; if (x[i] < min) min = x[i]; } Console.WriteLine("Max no is " + max); Console.WriteLine("Min no is " + min); Console.ReadLine(); } }}Arrays Page 5 of 14
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.comTwo-Dimensional Arrays:In a two-dimensional array, the position of any element is specified by two indices. A two dimensionalarray consists of a number of rows and columns.How to create and initialize a two-dimensional array:Ex 1: Create a 2D array of integers, consisting of 4 rows and 3 columns.int [ , ] x = new int [4, 3];We can access any element of the array by using the index for row and column as follows:x [2, 3] = 57;Program 5:The following example creates a two-dimensional array and fills it up with numbers from 1 to 12. Thenthe array elements are displayed.using System;namespace Arrays4{ class TwoD { public static void Main() { int r, c; int[,] x = new int[3, 4]; for (r = 0; r < 3; ++r) { for (c = 0; c < 4; ++c) { x[r, c] = (r * 4) + c + 1; Console.Write(x[r, c] + " "); } Console.WriteLine(); } Console.ReadLine(); } } }Output of the above program is:1 2 3 45 6 7 89 10 11 12Initializing 2D arrays:Consider a two-dimensional array declared as follows:int [ , ] x = new int [2, 3];Page 6 of 14 Arrays
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C#Suppose we want to initialize the first row of this array to 1 and the second row to 2. This can be doneas follows:int [ , ] x = { {1, 1, 1}, {2, 2, 2}};or,int [ , ] x = { {1, 1, 1}, {2, 2, 2} };Any element of the array is referred to as follows:x[0, 2] will refer to the element in row 0 and column 2.Program 6:Write a program to declare a two-dimensional array of dimension (5, 5). Initialise all diagonalelements to 1 and other elements to 0.using System;namespace Arrays6{ class Program { static void Main() { int[,] x = new int[5, 5]; //declare a 2D array for (int r = 0; r < 5; r++) { for (int c = 0; c < 5; c++) { if (r == c) // condition for checking for diagonal element x[r, c] = 1; else x[r, c] = 0; } } // Now print the array for (int r = 0; r < 5; r++) { for (int c = 0; c < 5; c++) { Console.Write("{0}t", x[r, c]); } Console.WriteLine(); } Console.Read(); } }}Arrays Page 7 of 14
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.comOutput of the above program is:1 0 0 0 00 1 0 0 00 0 1 0 00 0 0 1 00 0 0 0 1Jagged Arrays:A jagged array is an array in which each row may contain different number of elements (columns). C#treats a multidimensional array as an array of arrays. Thus, a jagged array is an array of arrays inwhich the length of each array can differ.How to declare a two-dimensional jagged array?Jagged arrays are declared by using sets of square brackets to indicate each dimension. For example, todeclare a two-dimensional jagged array, we will use this general form:type [][] arrayname = new type [size] [];Here, size indicates the number of rows in the array. The rows are allocated individually. Therefore,we can set each row to contain different number of elements.Ex: Consider the following declaration of a jagged array:int [][] x = new int [3][];x[0] = new int [4];x[1] = new int [3];x[2] = new int [5];After this allocation, the jagged array looks like this: x[0] [0] x[0] [1] x[0] [2] x[0] [3] x[1] [0] x[1] [1] x[1] [2] x[2] [0] x[2] [1] x[2] [2] x[2] [3] x[2] [4]How to store/access each element of a jagged array:To store the number 15 in x[0][1], we will write: x[0][1] = 15;Jagged arrays are useful in situations where we need a very large two-dimensional array that issparsely populated.Page 8 of 14 Arrays
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C#The System.Array Class:Every array is derived from the System.Array class. This class contains a number of methods andproperties that can be used to manipulate the elements of an array. Some of the methods and propertiesused with arrays are: Clear() Sets a range of elements to empty values CopyTo() Copy elements from a source array to a destination array Length Get the length of the array (no. of elements in array) Sort() Sort a one-dimensional array Reverse() Reverse the elements of a 1D arrayProgram 7:Write a program that illustrates the following methods/properties: Sort(), Reverse().using System;namespace Array6{ class Program { public static void Main() { //create an array int[] x = { 21, 34, 7, 15, 56}; Console.WriteLine("Original array:"); foreach(int i in x) Console.Write("{0}t", i); Console.WriteLine(); //Sort the array Array.Sort(x); Console.WriteLine("Sorted array:"); foreach (int i in x) Console.Write("{0}t", i); Console.WriteLine(); //Reverse the array Array.Reverse(x); Console.WriteLine("Reversed array:"); foreach (int i in x) Console.Write("{0}t", i); Console.WriteLine(); Console.Read(); } }}Arrays Page 9 of 14
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.comProgram 8Write a program to print the Pascal’s triangle with 8 rows.using System;namespace PascalTrg{ class Program { static void Main(string[] args) { int ROWS = 7, COLS = 7; int[,] x = new int[ROWS, COLS]; //declares a 2D array x[0, 0] = 1; //Create the Pascals triangle for (int r = 1; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { if (((r == 1) && (c == 0)) || (c == 0)) x[r, c] = 1; else x[r, c] = x[r - 1, c] + x[r - 1, c - 1]; } } //Now print the array for (int r = 0; r < ROWS; r++) { for (int j = 0; j < COLS; j++) { if(x[r, j] == 0) Console.Write(" "); else Console.Write(" " + x[r, j]); } Console.WriteLine("n"); } Console.Read(); } }}Output of this program is: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1Page 10 of 14 Arrays
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C#Program 9Write a program that initializes an array of size 5 x 5 as follows: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1using System;namespace Arrays7{ class Program { static void Main() { int[,] x = new int[5, 5]; for (int r = 0; r < 5; r++) { for (int c = 0; c < 5; c++) { if ((r % 2 == 0) && (c % 2 == 0)) x[r, c] = 1; if ((r % 2 == 1) && (c % 2 == 1)) x[r, c] = 1; } // end of inner for loop } // end of outer for loop //Now print the array for (int r = 0; r < 5; r++) { for (int c = 0; c < 5; c++) { Console.Write("{0}t", x[r, c]); } Console.WriteLine(); } Console.ReadLine(); } // end of Main() } // end of class} // end of namespaceExplanation of the program logic:If row number is even and column number is even, then the cell at the intersection is 1. If the rownumber is odd and the column number is also odd, then the cell at the intersection is 0. We test foreven row or column number by usual test for divisibility by 2.Arrays Page 11 of 14
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.comProgram 10:Write a method that would take an array as input and check whether a given element is present in thelist or not. The method must return true if it is present, otherwise return false.using System;namespace Arrays912{ class Program { public static bool Search(int[] x, int s) { int n = x.Length; for (int i = 0; i < n; i++) { if (x[i] == s) { return true; } } return false; } static void Main() { int s; int[] x = {21, 23, 45, 7, 82, 19, 45, 63,29, 30}; bool ans; s = 182; // we can accept this value from the user as input ans = Search(x, s); if (ans) Console.WriteLine("Element is found"); else Console.WriteLine("Element is found"); Console.Read(); } }}ArrayList:ArrayList is a class within the System.Collections namespace. This class can store a dynamicallysized array.Method and properties of ArrayList class are as follows: Method Purpose 1. Add() Adds an object to a list 2. Clear() Removes all elements from a listPage 12 of 14 Arrays
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C# Method Purpose 3. Contains() Determines if an element is in the list 4. Insert() Inserts an element into a list 5. Sort() Sorts the elements of a list 6. Count Counts the number of elements in the list 7. CopyTo() Copies a list to another list 8. Remove() Removes the first occurrence of an element 9. RemoveAt() Removes the element at the specified location 10. Capacity Gets or sets the number of elements in the listExample:The following example illustrates the use of the above methods/properties:1. Create an array list called subjects to store 30 objects. ArrayList subjects = new ArrayList(30);2. Add the subjects “CRM” and “TSCM” to this list. subjects.Add(“CRM”); subjects.Add(“TSCM”);3. Remove the object at position 1: subjects.RemoveAt(1);4. Modify the capacity of the list to hold 20 sujects: subjects.Capacity = 20;5. Find the number of objects actually stored in the above list int n = subjects.Count;Arrays Page 13 of 14
    • Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only.Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.comIMPORTANT QUESTIONS1. What is an array? What is the advantage of grouping similar data types together?2. Explain with a suitable example, how an array of one dimension is created and initialized?3. What is meant by the term “bound checking”? Give an example to explain your answer.4. Explain the use of the foreach statement to loop through an entire array.5. What happens if you access an element of an array with an index larger than the number of elements in the array?6. Explain how a two-dimensional array is created and initialized.7. What is a jagged array? How is such an array created and initialized? Give one example of a jagged array of type int and another example of a jagged array of type char.8. State and explain, with a program, the methods and properties of System.Array class.9. What is an ArrayList In what ways is it different froma normal array? Give 4 methods / properties associated with the ArrayList and explain these methods with appropriate examples.PROGRAMMING EXERCISES1. Write a program that calculates the sum of elements of a one-dimensional array of integers.2. Write a program that calculates the average of a set of values stored in an int array called sales.3. Write a program that initializes a two-dimensional array with numbers fro 1 to 10 and their squares.4. Using the concept of jagged arrays, show how the following three names would be stored in an array called cities: “Mumbai”, “Pune”, “Bangalore”, “Trivandrum”.5. Write a method called Dec2Bin that accepts an integer as a parameter and returns a string which is the binary equivalent of the parameter. Test your method with a program.6. Modify the above program to use a method calls Bin2Dec that accepts a string of 1s and 0s and returns the decimal equivalent of that string.7. A and B are two int type arrays of one-dimension each. Both these arrays are sorted in ascending order. Write a program to merge them into a single sorted array C.8. Write a method called matadd() that takes two-dimensional arrays A and B as inputs and calculates the sum of the two arrays in another array C. Print the three arrays using a method called printmat().9. Write a method called matmult() that takes two-dimensional arrays A and B as inputs and calculates the product of the two arrays in another array C. Print the three arrays using a method called printmat(). Assume that the arrays are conformable for multiplication.Page 14 of 14 Arrays