Lesson 8.1

One Dimensional Array in C# with Programming Example


Objective

What is Single Dimensional Array?
How to declare One Dimensional Array?
Programming Example

What is One Dimensional Array in C#?

A one dimensional array is an array which has only one row to store value. This type of array is considered as simple array in C# which stores all data in a single row.

One Dimensional Array

How to declare One Dimensional Array?

You can declare this type of array is as follow

datatype[] arrayName = new datatye[size_of_array]

Programming Example

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

namespace One_Dimensional_Array
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declaring Array
            int[] arr=new int[5];
            Console.WriteLine("Enter 5 numbers to add");
            //Storing value
            for (int i = 0; i < 5; i++)
            {
                arr[i] = Convert.ToInt32(Console.ReadLine());
            }

            int result = 0;
            //Accessing Array
            for (int i = 0; i < 5; i++)
            {
                result = result + arr[i];                
            }

            Console.WriteLine("{0} + {1} + {2} + {3} + {4} = {5}", arr[0], arr[1], arr[2], arr[3], arr[4], result);
            Console.ReadKey();
        }
    }
}


Output

Enter 5 numbers to add
5
6
7
8
2
5 + 6 + 7 + 8 + 2 = 28
__

Explanation

In the above example we did following task:

  1. Created a one dimensional array with the size of 5 columns.

    int[] arr=new int[5];

  2. Asked users to enter 5 values and stored them array.

    arr[i] = Convert.ToInt32(Console.ReadLine());

  3. Accessed array values, add them and stored in result variable.

Summary

This chapter explained the single dimension array tutorial. In the next course you will learn multidimensional array.

BackNext