Home » .Net

Single dimensional arrays in C#

Learn: Single dimensional array in C#.Net, how to declare, read and print the elements of an array?

Just like other programming languages, in C# arrays are also used to hold similar type of data elements, they are user defined data types.

In C# arrays are also references.

Syntax of single dimensional array:

<data_type>[] variable_name = new <data_type>[SIZE]; 

Example:

int[] X = new int[100]; 

Here, new operator is used to allocate memory space for the array.

Initialization of single dimensional array:

int[] X = {1,2,3,4,5}; 

Here, X contains 5 elements. Indexing of array is starting from 0 to size-1.

We can access of X like this, X[0] contains value 1, X[1] contains value 2 and so on.

Consider the program:

using System;

namespace arrayEx
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            int[] X;

            X = new int[5];

            Console.Write("Enter Elements : \n");
            for (i = 0; i < 5; i++)
            {
                Console.Write("\tElement[" + i + "]: ");
                X[i] = Convert.ToInt32(Console.ReadLine());
            }

            Console.Write("\n\nElements are: \n");
            for (i = 0; i < 5; i++)
            {
                Console.WriteLine("\tElement[" + i + "]: "+X[i]);
            }      
        }
    }
}

Output

Output:
Enter Elements :      
        Element[0]: 10
        Element[1]: 20
        Element[2]: 30
        Element[3]: 40
        Element[4]: 50
                      
Elements are:         
        Element[0]: 10
        Element[1]: 20
        Element[2]: 30
        Element[3]: 40
        Element[4]: 50    
Press any key to continue . . .





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL








Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.