Ad

Thursday, August 8, 2013

Reading a Values into an array through Foreach Loop

Overview:
                In this article i would like to publish an article Reading a Values into an array through Foreach Loop in c#.Net.



Description:
                Array can be defined as a collection of similar dataitems.In C#.Net array act as a ReferenceType.We can access the elements of an array using index values.

Syntax:

                    DataType[] NameOf The Array=new DataType[size];

E.g:
                   int[] a=new int[5];
                                (or)
                   int[] a=new int[]{12,10,1,3,5};
Note:
  1. If we Declare the size of the array it can take exactly that size number of values.
  2. If we are not declare the size of the array then we can accommodate n number of values.
Reading a Values Through For Each Loop:
Syntax:
Foreach(SourceDatatype variablename in Sourcevariablename)
{
-----------------------
}
Program:


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace arr123
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[5];
            Console.WriteLine("Enter {0} elements of AN Array",a.Length);
            int m = 0;
            foreach (int i in a)
            {
                if (m <=a.Length-1)
                {
                   
                        a[m] = Convert.ToInt32(Console.ReadLine());
                        m += 1;
            }
            }
            Console.WriteLine("Elements In An Array");
            foreach (int j in a)
            {
                Console.WriteLine(j);
            }
            Console.WriteLine("Keep Visiting this Blog.http://www.pv999.blogspot.com");
            Console.ReadLine();
        }
    }
}

 Output:
ForEach Loop
 

No comments: