C# Array Demonstration (.Net)

This example shows the declaration and assignment of all of the elements in a String array in a single statement. We declare an int array and make each assignment after validating the input from the user. This demo introduces the foreach keyword.

using System;

namespace console_array
  static class Program
    public static void Main(string[] args)
      int[] Rainfall = new int[12];
      String[] MonthNames = new String[12]{"January", "February", "March", "April",
                                           "May", "June", "July",  "August",
                                           "September", "October", "November", "December"};
      int currentRainfall;
      Boolean accepted = false;
      int monthNo = 0;
      foreach (String month in MonthNames)
        String strInput = "";
          accepted = false;
          Console.Write("Please enter the rainfall for " + month + " ");
          strInput = Console.ReadLine();
          accepted = int.TryParse(strInput, out currentRainfall);
          if (accepted) 
            Rainfall[monthNo] = currentRainfall;
            Console.WriteLine("Not an integer!");
       while (!accepted);
      Console.WriteLine("You entered these values:");
      foreach (int rain in Rainfall)
      Console.Write(rain.ToString() + " ");

Programming - a skill for life!

C# Demonstrations of I/O, arrays, methods, classes, loops, enums, pointers, file handling, Firebird databases, LINQ and drawing on a form