wingman007

C#_IntroArrayExample

Sep 3rd, 2015
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.12 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace FirstConsoleApp
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             int n = 5;
  14.             do
  15.             {
  16.                 n = InputInt("Please enter the size of the array (unsigned integer): ");
  17.             } while (n < 1);
  18.  
  19.             Console.WriteLine("The size of the array is {0}", n);
  20.             int[] myArray = new int[n];
  21.             InputArray(myArray);
  22.             PrintOddsGreaterThan7(myArray);
  23.             Console.WriteLine("The average is {0}.", GetAverage(myArray));
  24.         }
  25.  
  26.         static void InputArray(int[] myArray) {
  27.             int value = 0;
  28.             for (int i = 0; i < myArray.Length; i++) {
  29.                 value = InputInt("Please enter element #" + i + ": ");
  30.                 myArray[i] = value;
  31.             }
  32.         }
  33.  
  34.         static void PrintOddsGreaterThan7(int[] myArray)
  35.         {
  36.             for (int i = 0; i < myArray.Length; i++) {
  37.                 if (myArray[i] % 2 != 0 && myArray[i] > 7) Console.WriteLine(myArray[i]);
  38.             }
  39.         }
  40.  
  41.         static double GetAverage(int[] myArray)
  42.         {
  43.             int sum = 0;
  44.             for (int i = 0; i < myArray.Length; i++)
  45.             {
  46.                 sum += myArray[i];
  47.             }
  48.             return sum / myArray.Length;
  49.         }
  50.  
  51.         // This method belongs to View (Presentation Layer)
  52.         static int InputInt(string message)
  53.         {
  54.             int n = 0;
  55.             bool flag = false;
  56.             do
  57.             {
  58.                 Console.Write(message);
  59.                 try
  60.                 {
  61.                     n = Int32.Parse(Console.ReadLine());
  62.                     flag = false;
  63.                 }
  64.                 catch (System.FormatException e)
  65.                 {
  66.                     Console.WriteLine("Please, enter a valid integer number (e.g. 5). Exception {0}", e.Message);
  67.                     flag = true;
  68.                 }
  69.             } while (flag);
  70.             return n;
  71.         }
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment