Advertisement
TanyaPetkova

C# Part II Arrays Exercise 2

Dec 20th, 2013
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.97 KB | None | 0 0
  1. //Write a program that reads two arrays from the console and compares them element by element.
  2.  
  3. using System;
  4.  
  5. class ComparingArrays
  6. {
  7.     private static uint InputData(string message)
  8.     {
  9.         uint n;
  10.         Console.Write(message);
  11.  
  12.         while (!uint.TryParse(Console.ReadLine(), out n) || n < 0)
  13.         {
  14.             Console.Write("Invalid input. Enter a positive integer number: ");
  15.         }
  16.  
  17.         return n;
  18.     }
  19.  
  20.     private static void Initialisation(uint arrayLength, int[] array)
  21.     {
  22.         for (int i = 0; i < arrayLength; i++)
  23.         {
  24.             Console.Write("Enter the {0} element of the array: ", i);
  25.  
  26.             while (!int.TryParse(Console.ReadLine(), out array[i]))
  27.             {
  28.                 Console.Write("Invalid input. Enter an integer number: ");
  29.             }
  30.         }
  31.     }
  32.     static void Main()
  33.     {
  34.         uint firstArrayLength = InputData("Enter the first arrays`s length: ");
  35.         int[] firstArray = new int[firstArrayLength];
  36.         Initialisation(firstArrayLength, firstArray);
  37.  
  38.         uint secondArrayLength = InputData("Enter the second arrays`s length: ");
  39.         int[] secondArray = new int[secondArrayLength];
  40.         Initialisation(secondArrayLength, secondArray);
  41.  
  42.         bool areEqual = true;
  43.  
  44.         //Compare two arrays till the length of the shorter
  45.         for (int i = 0; i < Math.Min(firstArrayLength, secondArrayLength); i++)
  46.         {
  47.             if (firstArray[i] != secondArray[i])
  48.             {
  49.                 Console.WriteLine("The two arrays are NOT equal.");
  50.                 areEqual = false;
  51.                 break;
  52.             }
  53.         }
  54.  
  55.         if (areEqual && firstArrayLength == secondArrayLength)
  56.         {
  57.             Console.WriteLine("The two arrays are equal.");
  58.         }
  59.         else if (areEqual && firstArrayLength != secondArrayLength)
  60.         {
  61.             Console.WriteLine("The two arrays are equal till the length of the shorter.");
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement