Skip to main content

C# - Arrays

An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays

To declare an array in C#, you can use the following syntax −
datatype[] arrayName;
where,
  • datatype is used to specify the type of elements in the array.
  • [ ] specifies the rank of the array. The rank specifies the size of the array.
  • arrayName specifies the name of the array.
For example,
double[] balance;

Initializing an Array

Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array. For example,
double[] balance = new double[10];

Assigning Values to an Array

You can assign values to individual array elements, by using the index number, like −
double[] balance = new double[10];
balance[0] = 4500.0;
You can assign values to the array at the time of declaration, as shown −
double[] balance = { 2340.0, 4523.69, 3421.0};
You can also create and initialize an array, as shown −
int [] marks = new int[5]  { 99,  98, 92, 97, 95};
You may also omit the size of the array, as shown −
int [] marks = new int[]  { 99,  98, 92, 97, 95};
You can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location −
int [] marks = new int[]  { 99,  98, 92, 97, 95};
int[] score = marks;
When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example,
double salary = balance[9];
The following example, demonstrates the above-mentioned concepts declaration, assignment, and accessing arrays −
using System;

namespace ArrayApplication {

   class MyArray {
   
      static void Main(string[] args) {
         int []  n = new int[10]; /* n is an array of 10 integers */
         int i,j;

         /* initialize elements of array n */
         for ( i = 0; i < 10; i++ ) {
            n[ i ] = i + 100;
         }
         
         /* output each array element's value */
         for (j = 0; j < 10; j++ ) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Using the foreach Loop

In the previous example, we used a for loop for accessing each array element. You can also use a foreach statement to iterate through an array.
using System;

namespace ArrayApplication {

   class MyArray {
   
      static void Main(string[] args) {
         int []  n = new int[10]; /* n is an array of 10 integers */
         
         /* initialize elements of array n */
         for ( int i = 0; i < 10; i++ ) {
            n[i] = i + 100;
         }
         
         /* output each array element's value */
         foreach (int j in n ) {
            int i = j-100;
            Console.WriteLine("Element[{0}] = {1}", i, j);
            
         }
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Comments

Popular posts from this blog

C# Methods

A strategy is a gathering of articulations that together play out an errand. Each C# program has no less than one class with a strategy named Main.  To utilize a strategy, you have to:  Characterize the strategy  Call the strategy Methods Defining Methods in C# When you characterize a strategy, you essentially proclaim the components of its structure. The linguistic structure for characterizing a strategy in C# is as per the following: <Access Specifier > <Return Type > <Method Name > (Parameter List) { Method Body } Following are the different components of a technique:  Access Specifier : This decides the perceivability of a variable or a technique from another class.  Return type : A technique may restore an esteem. The arrival sort is the information kind of the esteem the technique returns. On the off chance that the strategy is not restoring any esteems, at that point the arrival sort is void.  Method name : Method name

C# - Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable. The basic value types provided in C# can be categorized as: Type Example Integral types sbyte, byte, short, ushort, int, uint, long, ulong, and char Floating point types float and double Decimal types decimal Boolean types true or false values, as assigned Nullable types Nullable data types C# also allows defining other value types of variable such as  enum  and reference types of variables such as  class , which we will cover in subsequent chapters. Defining Variables Syntax for variable definition in C# is: <data_type> <variable_list> ; Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined da

C# - Environment

In this chapter, we will discuss the tools required for creating C# programming. We have already mentioned that C# is part of .Net framework and is used for writing .Net applications. Therefore, before discussing the available tools for running a C# program, let us understand how C# relates to the .Net framework. The .Net Framework The .Net framework is a revolutionary platform that helps you to write the following types of applications: Windows applications Web applications Web services The .Net framework applications are multi-platform applications. The framework has been designed in such a way that it can be used from any of the following languages: C#, C++, Visual Basic, Jscript, COBOL, etc. All these languages can access the framework as well as communicate with each other. The .Net framework consists of an enormous library of codes used by the client languages such as C#. Following are some of the components of the .Net framework:  More Info:  C Sharp (programming l