Csharp/CSharp Tutorial/Data Type/int array

Материал из .Net Framework эксперт
Версия от 12:18, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Get the Max Value in an array

using System;
using System.Collections.Generic;
using System.Text;
class Program {
    static int MaxValue(int[] intArray) {
        int maxVal = intArray[0];
        for (int i = 1; i < intArray.Length; i++) {
            if (intArray[i] > maxVal)
                maxVal = intArray[i];
        }
        return maxVal;
    }
    static void Main(string[] args) {
        int[] myArray = {
            1, 8, 3, 6, 2, 5, 9, 3, 0, 2
         };
        int maxVal = MaxValue(myArray);
        Console.WriteLine("The maximum value in myArray is {0}", maxVal);
    }
}

Initialize int arrays

using System;
class MainClass
{
  public static void Main()
  {
    
    int[] intArray = new int[5] {10, 20, 30, 40, 50};
    for (int counter = 0; counter < intArray.Length; counter++)
    {
      Console.WriteLine("intArray[" + counter + "] = " +
        intArray[counter]);
    }
  }
}
intArray[0] = 10
intArray[1] = 20
intArray[2] = 30
intArray[3] = 40
intArray[4] = 50

int arrays

using System;
class MainClass
{
  public static void Main()
  {
    
    int[] intArray = new int[10];
    int arrayLength = intArray.Length;
    Console.WriteLine("arrayLength = " + arrayLength);
    for (int counter = 0; counter < arrayLength; counter++)
    {
      intArray[counter] = counter;
      Console.WriteLine("intArray[" + counter + "] = " + intArray[counter]);
    }
  }
}
arrayLength = 10
intArray[0] = 0
intArray[1] = 1
intArray[2] = 2
intArray[3] = 3
intArray[4] = 4
intArray[5] = 5
intArray[6] = 6
intArray[7] = 7
intArray[8] = 8
intArray[9] = 9

int array with for loop

using System;
class Program {
    static int MaxValue(int[] intArray) {
        int maxVal = intArray[0];
        for (int i = 1; i < intArray.Length; i++) {
            if (intArray[i] > maxVal)
                maxVal = intArray[i];
        }
        return maxVal;
    }
    static void Main(string[] args) {
        int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };
        int maxVal = MaxValue(myArray);
        Console.WriteLine("The maximum value in myArray is {0}", maxVal);
    }
}

Use a foreach loop through an int array

class MainClass
{
  public static void Main()
  {
    int [] myValues = {2, 4, 3, 5, 1};
    foreach (int counter in myValues)
    {
      System.Console.WriteLine("counter = " + counter);
    }
  }
}
counter = 2
counter = 4
counter = 3
counter = 5
counter = 1