Programming examples of Array in C#


Objective

In this chapter you will learn about some programming examples of array in C#.


Qu 1:Write a program of sorting an array. Declare single dimensional array and accept 5 integer values from the user. Then sort the input in ascending order and display output.

Example:




using System;
 
namespace Example1
{
  class Program
   {
     static void printarray(int[] arr)
      {
        Console.WriteLine("\n\nElements of array are:\n");
        foreach (int i in arr)
         {
           Console.Write("\t{0}", i);
         }
      }
     static void Main(string[] args)
      {
        int[] arr = new int[5];
        int i;
        // loop for accepting values in array
        for (i = 0; i < 5; i++)
         {
           Console.Write("Enter number:\t");
           arr[i] = Convert.ToInt32(Console.ReadLine());
         }
        Program.printarray(arr); 
        //sorting array value;
        Array.Sort(arr); //use array's sort function
 
        Program.printarray(arr);
        Console.ReadLine();
      }
   }
}




Output

 

Enter number:      56
Enter number:      34
Enter number:      23
Enter number:      1
Enter number:      76


Elements of array are:

      56      34      23      1      76

Elements of array are:

      1       23      34      56      76



Qu2:Write a program to create two multidimensional arrays of same size. Accept value from user and store them in first array. Now copy all the elements of first array are second array and print output.

Example:


using System;
 
namespace example2
{
  class Program
   {
     static void Main(string[] args)
      {
        int[,] arr1 = new int[3, 3];
        int[,] arr2 = new int[3, 3];
        int i, j;
           
        // Storing user input in arr1
        for (i = 0; i < 3; i++)
         {
           for (j = 0; j < 3; j++)
            {
              Console.Write("Enter array value:\t");
              arr1[i, j] = Convert.ToInt32                               (Console.ReadLine());
            }
         }
        //copying value of arr1 to arr2
        for (i = 0; i < 3; i++)
         {
           for (j = 0; j < 3; j++)
            {
              arr2[i, j] = arr1[i, j];
            }
         }
 
        Console.WriteLine("\n\nElements of second array             are:\n\n");
        //Printing the arr2 value
        for (i = 0; i < 3; i++)
         {
           Console.WriteLine();
           for (j = 0; j < 3; j++)
            {
              Console.Write("\t{0}", arr2[i, j]);
            }
         }
        Console.ReadLine();
      }
   }
}




Output

 

Enter your option <1-7> for days. 1 for Monday: 9
Invalid option. Please try again




Enter your option <1-7> for days. 1 for Monday: 2
Tuesday



Summary

In this chapter you studied some programming examples of array. In next chapter you will get some programming exercises of array.


     

Previous Page Next Page