c# Array Part I
Submitted by jin29neci on Thursday, August 12, 2010 - 18:03.
This is my first post, this is intended for beginners, I just hope someone will benefit from this.
I'll be posting more tutorials on C#

- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ArraysPartOne
- {
- class Program
- {
- static void Main(string[] args)
- {
- /*
- * sometimes programmers needs to use
- * multiple objects of the same type(value types or reference types)
- * so we use arrays.
- * Definition of array -> is a data structure that contains a number of
- * elements of the same type. (Professional C# 2008 Wrox)
- */
- /*
- * how to declare an array?
- * so there are many ways on how to declare an array
- * just try to look below
- */
- int[] _FourthArray = { 6,7,8};
- // end of declaring or initilizing an array
- //start of our sample array
- try
- {
- Console.WriteLine("Array Sample Part I");
- int intInputNumber =0;
- int intCounter =0;
- Console.WriteLine("How many number to want to input");
- intInputNumber = int.Parse (Console.ReadLine());
- do
- {
- Console.WriteLine(
- string.Format
- ("Input numbers at index[{0}]",intCounter ));
- _UserArray[intCounter] = int.Parse(Console.ReadLine());
- intCounter++;
- }while (intCounter < intInputNumber);
- //iterate throught the elements in the array ,
- //i'll be using for and foreach loop
- Console.WriteLine("Iterate elements using for loop");
- for (int i = 0;
- i < _UserArray.Length; i++)
- {
- string strMessage =
- string.Format
- ("Array Index [{0}] = [{1}]", i, _UserArray[i]);
- Console.WriteLine(strMessage + Environment.NewLine);
- }
- Console.WriteLine("Iterate elements using foreach loop");
- foreach (int IndexValue in _UserArray)
- {
- result.Append(IndexValue);
- result.Append(",");
- }
- Console.WriteLine(result);
- Console.WriteLine("Do you want to sort the array?[y/n]");
- string ans = Console.ReadLine();
- if (ans.ToUpper().Equals("Y"))
- {
- Array.Sort(_UserArray);
- }
- //iterate throught the elements
- //in the array ,i'll be using for loop
- Console.WriteLine("Iterate elements using for loop");
- for (int i = 0; i < _UserArray.Length; i++)
- {
- string strMessage =
- string.Format
- ("Array Index [{0}] = [{1}]",
- i, _UserArray[i]);
- Console.WriteLine
- (strMessage + Environment.NewLine);
- }
- Console.ReadKey();
- }
- // a wrong index value,
- //IndexOutOfRangeException will be thrown
- catch (IndexOutOfRangeException ex)
- {
- Console.WriteLine(ex.Message);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- }
- }

Comments
Add new comment
- Add new comment
- 35 views