Loading...

Arrays in C#

Arrays in C#:

Single Dimension Arrays are Simple in Computer Programming. Array is —a group of elements, which are of the same size, same name and have the same Data Type. Arrays are simply boxes in memory in which the data is stored. Think arrays as a chain or sequence of boxes in which the same type of data is stored in sequence.

Why we Use Arrays:

If we want to store big amount of same type of data such as Students Marks, we have to declare a lot of variables for each students marks and have to read and write all the data individually. So the solution is Arrays. Here you can once declare the array name, type and size and then you can read write data easily using loops.

Starting Arrays:

Arrays have definite number and we have to declare the size at the time of initialization. Arrays are allocated by new, manipulated by reference. Example: 

  int [ ] marks = new int [100];  // By this code Array is initialized of data type = int , name = marks and size = 100

  • Arrays can be initialized[Dense Array]
  int [ ] smallPrimes = {2,3,5,7,11,13}; // here the size is not given but the data is given, it is called Dense Array
The Arrays are are indexed in sequence and have lower bound and upper bound, index starts from 0 and end on (size - 1) . index number are given in square brackets, for example from the above example smallprimes[1] will have the value = 3.
You can change the data type if you want to store another type of data.

Example:

Here is the code example in which we are calculating Average.

staticvoid Main(string[] args)
        {
int[] amount = new int[5]; // initialization of array
int totalamount=0;
double Average;
           
for (int i = 0; i< 5; i++) // for loop to store elements by using one statement
                {
Console.WriteLine("Please enter the number :");
amount[i] = Convert.ToInt32(Console.ReadLine()); // [i] is the index number and I will iterate with the for loop, it means on first iteration of loop the I will be 0 to number will be stored in index number 0 , then on 1 in next iteration of loop and so on.
totalamount += amount[i];  // adding all numbers in a single variable

                }
                Average = totalamount / 5;  // calculating average
Console.WriteLine("The total amount is {0} and the avg is {1}", totalamount, Average);           
        }

Output:



Learn 2 D Array

Thank you for Reading, Like this it you Understood. It helps a lot to keep us motivated

0 comments:

Post a Comment

Google+

 
TOP