Saturday, March 19, 2016

C# - All you need to know about arrays

C# allows us to use multiple types of arrays OR Collections (will be explained in future articles), array contains multiple variables in a single location (Variables must be of the same type if array is not generic).

All variables reside continuously and next to each other (By default the first array location will be configured with ID '0' and the last index will set to All items - 1).

Examples:

static void Main(string[] args)
        {
            bool[] BoolArray = new bool[1];
            double[] DoubleArray = new double[2];
            decimal[] DecimalArray = new decimal[3];
            string[] StringArray = new string[4];
            char[] CharArray = new char[5];
            int[] IntArray = new int[6];
        }

Array initialization:

·       Fixed Size - Array can be configured with specific size (max size of the array will be set on declaration and cannot be changed after creation).
       In code:
int[] FixedIntegerArray = new int[1];
·       Dynamic Size – The array is configured without any limitation (Will grow based on initialization).
In code:
int [] DaynamicIntArray = new int[]{1,2,3};

Arrays, Loops and methods

This section will demonstrate how to manipulate arrays using loops to reduce initialization and reading times.

Application Algorithm:

1.       User insert Minimum Number.
2.       User insert Maximum number.
3.       Calling Method that performs two operations:
       ·         Initializing a new array (Min-Max).
       ·         Printing the numbers range
4.    Calling a method that separates “even numbers” and “Odd numbers”.
Separation made with different colors:

Green = Even numbers
Red = Odd numbers

Note!
When moving array to function as a parameter,   the array sent as the original cell in memory and not as copy, therefore every change in method body will affect the original value in memory. 

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LoopsAndArrays
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get the  user range
            Console.WriteLine("Please insert range of numbers");
            Console.WriteLine("Min Number ? ");
            int MinNumber = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Max Number ? ");
            int MaxNumber = Convert.ToInt32(Console.ReadLine());

            //initialize the array and print all numbers
            int [] range =   InitializeANDprint(MinNumber, MaxNumber);

            //Calling a method that separates “even numbers” and “Odd numbers”
            PrintEvenNumbers(range);
        }

        private static void PrintEvenNumbers(int[] range)
        {
         Console.WriteLine("Numbers separation: ");  
  foreach (var item in range)
            {
                if ((item % 2)== 0 )
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine(item);
                    Console.ResetColor();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(item);
                    Console.ResetColor();
                }
            }
        }

        private static int[] InitializeANDprint(int Min, int Max)
        {
            //initialize a new array + Printing numbers
            int ArrayLength = (Max - Min) + 1;
            int[] InitializeNewArray = new int[ArrayLength];
            Console.WriteLine("Array range:");
            for (int i = 0; i < ArrayLength; i++)
            {               
                Console.WriteLine(Min);
                InitializeNewArray[i] = Min;
                Min++;             
            }
            Console.WriteLine();
            return InitializeNewArray;
        }
    }
}

Result: 























Extracting information from arrays 


This part will demonstrate how to extract information from arrays using default properties and methods.

Summery:

Method Name
Return Type
Array. Length
Return the array length
Array. Min
Return the MIN number in the array
Array. Max
Return the MAX number in the array
Array. Average
Return the Average value of all numbers in the array
Array. Sum
Return the aggregation value of all numbers in the array
Array. Type
Return the array type


Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArraysAndDefaultMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a new array
            int[] ArraysAndMethods = new int[20];

            //Initialize an Array with Random Numbers
            int[] ExampleArray = InitializeNewArray(ArraysAndMethods);

            //Print the Array after Initialization
            PrintArrayValues(ArraysAndMethods);

            //Extracting values from the array
            ExtractArrayValues(ArraysAndMethods);  
        }

        private static void ExtractArrayValues(int[] ArraysAndMethods)
        {
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Array Values : ");
            Console.ResetColor();
           
            //Extracting the array length
            Console.WriteLine("The Array length is : {0}" ,       ArraysAndMethods.Length);

            //Extracting the array lowest initialized number
            Console.WriteLine("The Array Minimum number is : {0}", ArraysAndMethods.Min());

            //Extracting the biggest number initialized in array
            Console.WriteLine("The Array Maximum number is : {0}", ArraysAndMethods.Max());

            //Calculating the average number of an array
            Console.WriteLine("The Array average value is : {0}", ArraysAndMethods.Average());

            //Extracting the array initialized type
            Console.WriteLine("The Array type is : {0}", ArraysAndMethods.GetType());

            //Calculating the total SUM numbers of an array
            Console.WriteLine("The total sum numbers of Array  is : {0}", ArraysAndMethods.Sum());
        }

        private static int[] InitializeNewArray(int[] ArraysAndMethods)
        {
            Random rnd = new Random();
            for (int i = 0; i < ArraysAndMethods.Length; i++)
            {
                ArraysAndMethods[i] = rnd.Next(1, 100);
            }
            return ArraysAndMethods;
        }

        private static void PrintArrayValues(int [] Array)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Array Numbers:");
            Console.ResetColor();
            foreach (var item in Array)
            {             
                Console.Write(item + ",");
            }
            Console.WriteLine();
        }   
    }
}

Result:



Arrays Class – Main methods

This part will examine the main methods that are existed in the ‘Array’ class.

Summary:

Method Name
Return Type
Array. Sort
Changing the array values Min to Max
Array. Reverse
Changing the array values Max to Min
Array. Clear
Clear values from an array (bool = false, number = 0….)

Example 1:
This code will demonstrate how to use the Sort and Reverse methods.

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArraysAndDefaultMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a new array
            int[] ArraysAndMethods = new int[10];
            //Initialize an Array with a Random Numbers
            int[] ExampleArray = InitializeNewArray(ArraysAndMethods);

            //Printing the Array default values:
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Array Default values : ");
            Console.ResetColor();
            PrintArrayValues(ExampleArray);
           
            //Sort array(Min - > Max) :
            ExampleArray = ManipulateArrayOrderMinToMax(ExampleArray);

            //Printing Array values after sorting(1):
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\nArray values after sorting : ");
            Console.ResetColor();
            PrintArrayValues(ExampleArray);

            //Sort array (Max -> Min):
            ExampleArray = ManipulateArrayOrderMaxToMin(ExampleArray);

            //Printing the Array values after sorting(2):
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\nArray values after sorting : ");
            Console.ResetColor();
            PrintArrayValues(ExampleArray);
        }
        private static int[] ManipulateArrayOrderMaxToMin(int[] ExampleArray)
        {
            Array.Reverse(ExampleArray);
            return ExampleArray;     
        }
        private static int[] ManipulateArrayOrderMinToMax(int[] ExampleArray)
        {
            Array.Sort(ExampleArray);
            return ExampleArray;
        }
        private static void PrintArrayValues(int[] ExampleArray)
        {
            foreach (var item in ExampleArray)
            {
                Console.WriteLine(item);
            }
        }
        private static int[] InitializeNewArray(int[] ArraysAndMethods)
        {
            Random rnd = new Random();
            for (int i = 0; i < ArraysAndMethods.Length; i++)
            {
                ArraysAndMethods[i] = rnd.Next(1, 100);
            }
            return ArraysAndMethods;
        }
    }
}

Result:
























Example 2:
This code will demonstrate how to use the ‘Clear’ method.

Code:

class Program
    {
        static void Main(string[] args)
        {
            //Create a new array
            int[] IntArray = new int[]{1,2,3,4,5};
            bool[] BoolArray = new bool[]{true,false};
            string[] StringsArray = new string[] {"My","Name","is","David"}; 
           
            //Print the Array default values:          
             PrintArrayValues(IntArray,BoolArray,StringsArray,0);

            //Clear the array values:
             ClearArrays(IntArray, BoolArray, StringsArray);

            //Print the  Array values after manipulations:
             PrintArrayValues(IntArray, BoolArray, StringsArray,1);
        }
        private static void ClearArrays(int[] Integers, bool[] Booleans, string[] strings)
        {
            Console.WriteLine();
            Array.Clear(Integers,0,Integers.Length);
            Array.Clear(Booleans,0,Booleans.Length);
            Array.Clear(strings, 0, strings.Length);
        }
        private static void PrintArrayValues(int[] Integers , bool [] Booleans , string [] strings,int index )
        {
            if (index == 0 )
            {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Integers Array :");
            Console.ResetColor();
            foreach (var item in Integers)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Booleans Array : ");
            Console.ResetColor();
            foreach (var item in Booleans)
            {
                Console.WriteLine(item);
            }
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Strings Array : ");
            Console.ResetColor();
            foreach (var item in strings)
            {
                Console.WriteLine(item);
            }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Integers Array after clearance :");
                Console.ResetColor();
                foreach (var item in Integers)
                {
                    Console.WriteLine(item);
                }
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Booleans Array after clearance: ");
                Console.ResetColor();
                foreach (var item in Booleans)
                {
                    Console.WriteLine(item);
                }
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Strings Array after clearance: ");
                Console.ResetColor();
                foreach (var item in strings)
                {
                    Console.WriteLine(item);
                }
            }    
        }

Result:












No comments:

Post a Comment

My Presentations