How to declare/initialize arrays in C#

by Jagadish Pulakhandam on 10/18/2011 11:40:55 AM
Rated 0 from 0 votes
Brief: Demonstrates on declaring, initializing and traversing through arrays using C#. For this sample, we will identify all the primes in an array.
Posted to: Basics of .NET Programming
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Demonstrates the following:
  • How to declare an array
  • How to initialize an array
  • How to parse or traverse through all elements in an array
  • How to identify primes in an integer array
Source Code:

01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05. 
06.namespace PrimeNumbersToFindInAnArray
07.{
08.    class Program
09.    {
10.        static void Main(string[] args)
11.        {
12.            //some random numbers
13.            int[] a = { 34, 56, 78, 89, 43, 23, 7, 5, 99, 91, 97 };
14. 
15.            //traverses through each element in array 'a'
16.            foreach (int n in a)
17.            {
18.                if (isPrime(n)) Console.WriteLine(n);
19.            }
20. 
21.            //wait for enter key
22.            Console.ReadLine();
23.        }
24. 
25.        static bool isPrime(int n)
26.        {
27.            bool b = true;
28.            //1 is always a factor for every number (we start with 2)
29.            //there can never be a factor of a number which is above the half of the number.
30.            //ex:for a number 200, the highest factor is 100 (which is just half of 200).
31.            for (int i = 2; i <= (n / 2); i++)
32.            {
33.                //if a factor is found for 'n', it is no longer a prime
34.                if ((n % i) == 0)
35.                {
36.                    b = false;
37.                    break;
38.                }
39.            }
40.            return b;
41.        }
42.    }
43.}


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following