SlideShare una empresa de Scribd logo
1 de 14
Descargar para leer sin conexión
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 common
name. 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 are
integers 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 first
consider 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 of
integers, or a list of floats, or a list of char data type. E.g., we may use a one-dimensional array to store
the 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 that
comprises 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 by
size.
Generated by Foxit PDF Creator © Foxit Software
                                                    http://www.foxitsoftware.com For evaluation only.




Prof. Mukesh N. Tekwani (9869488356)                               Email: mukeshtekwani@hotmail.com
The 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 put
after the data type.

Example 1: Create a one-dimensional array called marks to store the marks obtained in 5 different
subjects. 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 and
allocating 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. Assign
appropriate 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 numbers
1, 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 of
the array will result in an error. This is completely different from C and C++ where there is no
boundary 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.com
Program 2:
The following example illustrates the concept of array boundaries. It generates the error and terminates
the 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 the
program is terminated.



Array Length:
In C#, all arrays are implemented as objects. The allocated size of the array is stored in a variable
called Length.
The length of an array (i.e., the size of the array, say x, can be accessed by using x.Length
The Length property makes certain operations easier and safer – e.g., by preventing underruns and
overruns.

Program 3:
The following program illustrates the use of the Length property. The program reverses the contents of
an 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 minimum
values 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.com
Two-Dimensional Arrays:
In a two-dimensional array, the position of any element is specified by two indices. A two dimensional
array 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. Then
the 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 4
5 6 7 8
9 10 11 12

Initializing 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 done
as 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 diagonal
elements 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.com
Output of the above program is:
1   0      0    0     0
0   1      0    0     0
0   0      1    0     0
0   0      0    1     0
0   0      0    0     1


Jagged 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 in
which 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, to
declare 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 is
sparsely 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 and
properties that can be used to manipulate the elements of an array. Some of the methods and properties
used 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 array


Program 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.com
Program 8
Write 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 Pascal's 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 1



Page 10 of 14                                                                                   Arrays
Generated by Foxit PDF Creator © Foxit Software
                                                  http://www.foxitsoftware.com For evaluation only.




                                                                                   4. Programming in C#
Program 9
Write 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    1

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

Explanation of the program logic:

If row number is even and column number is even, then the cell at the intersection is 1. If the row
number is odd and the column number is also odd, then the cell at the intersection is 0. We test for
even 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.com
Program 10:

Write a method that would take an array as input and check whether a given element is present in the
list 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 dynamically
sized 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 list

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


Example:
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.com

IMPORTANT QUESTIONS
1.   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 EXERCISES
1.   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

Más contenido relacionado

La actualidad más candente

C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kella
Manoj Kumar kothagulla
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
Mayank Jalotra
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 

La actualidad más candente (20)

Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
C basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kellaC basic questions&amp;ansrs by shiva kumar kella
C basic questions&amp;ansrs by shiva kumar kella
 
Intake 38 6
Intake 38 6Intake 38 6
Intake 38 6
 
Java execise
Java execiseJava execise
Java execise
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Resource wrappers in C++
Resource wrappers in C++Resource wrappers in C++
Resource wrappers in C++
 
The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210The Ring programming language version 1.9 book - Part 98 of 210
The Ring programming language version 1.9 book - Part 98 of 210
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
 
The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180 The Ring programming language version 1.5.1 book - Part 174 of 180
The Ring programming language version 1.5.1 book - Part 174 of 180
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
 
Computer Programming- Lecture 3
Computer Programming- Lecture 3Computer Programming- Lecture 3
Computer Programming- Lecture 3
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 

Similar a C sharp chap6

Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
Abdul Samee
 

Similar a C sharp chap6 (20)

C# p9
C# p9C# p9
C# p9
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
Lecture 1 mte 407
Lecture 1 mte 407Lecture 1 mte 407
Lecture 1 mte 407
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
Arrays
ArraysArrays
Arrays
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Lecture_01.2.pptx
Lecture_01.2.pptxLecture_01.2.pptx
Lecture_01.2.pptx
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
CP Handout#7
CP Handout#7CP Handout#7
CP Handout#7
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
VCE Unit 01 (2).pptx
VCE Unit 01 (2).pptxVCE Unit 01 (2).pptx
VCE Unit 01 (2).pptx
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 

Más de Mukesh Tekwani

Más de Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

C sharp chap6

  • 1. 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 common name. 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 are integers 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 first consider 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 of integers, or a list of floats, or a list of char data type. E.g., we may use a one-dimensional array to store the 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 that comprises 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 by size.
  • 2. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.com The 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 put after the data type. Example 1: Create a one-dimensional array called marks to store the marks obtained in 5 different subjects. 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 and allocating 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. Assign appropriate 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
  • 3. 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 numbers 1, 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 of the array will result in an error. This is completely different from C and C++ where there is no boundary 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
  • 4. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.com Program 2: The following example illustrates the concept of array boundaries. It generates the error and terminates the 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 the program is terminated. Array Length: In C#, all arrays are implemented as objects. The allocated size of the array is stored in a variable called Length. The length of an array (i.e., the size of the array, say x, can be accessed by using x.Length The Length property makes certain operations easier and safer – e.g., by preventing underruns and overruns. Program 3: The following program illustrates the use of the Length property. The program reverses the contents of an 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
  • 5. 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 minimum values 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
  • 6. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.com Two-Dimensional Arrays: In a two-dimensional array, the position of any element is specified by two indices. A two dimensional array 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. Then the 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 4 5 6 7 8 9 10 11 12 Initializing 2D arrays: Consider a two-dimensional array declared as follows: int [ , ] x = new int [2, 3]; Page 6 of 14 Arrays
  • 7. 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 done as 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 diagonal elements 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
  • 8. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.com Output of the above program is: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 Jagged 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 in which 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, to declare 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 is sparsely populated. Page 8 of 14 Arrays
  • 9. 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 and properties that can be used to manipulate the elements of an array. Some of the methods and properties used 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 array Program 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
  • 10. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.com Program 8 Write 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 Pascal's 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 1 Page 10 of 14 Arrays
  • 11. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 4. Programming in C# Program 9 Write 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 1 using 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 namespace Explanation of the program logic: If row number is even and column number is even, then the cell at the intersection is 1. If the row number is odd and the column number is also odd, then the cell at the intersection is 0. We test for even row or column number by usual test for divisibility by 2. Arrays Page 11 of 14
  • 12. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.com Program 10: Write a method that would take an array as input and check whether a given element is present in the list 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 dynamically sized 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 list Page 12 of 14 Arrays
  • 13. 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 list Example: 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
  • 14. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. Prof. Mukesh N. Tekwani (9869488356) Email: mukeshtekwani@hotmail.com IMPORTANT QUESTIONS 1. 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 EXERCISES 1. 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