Advertisement
Klaxon

[C# Arrays] Array Comparison

Jul 15th, 2013
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.34 KB | None | 0 0
  1. // 2. Write a program that reads two arrays from the console and compares them element by element.
  2.  
  3. using System;
  4.  
  5. class ArrayComparison
  6. {
  7.     static void Main()
  8.     {
  9.         // Get the array size
  10.         Console.Write("Size of the arrays: ");
  11.         int length = int.Parse(Console.ReadLine());
  12.  
  13.         int[] firstArray = new int[length];
  14.         int[] secondArray = new int[length];
  15.  
  16.         for (int i = 0; i < length; i++)
  17.         {
  18.             // Read numbers for each array
  19.             Console.Write("firstArray[{0}]: ", i);
  20.             firstArray[i] = int.Parse(Console.ReadLine());
  21.             Console.Write("secondArray[{0}]: ", i);
  22.             secondArray[i] = int.Parse(Console.ReadLine());
  23.         }
  24.  
  25.         // Sort the arrays
  26.         Array.Sort(firstArray);
  27.         Array.Sort(secondArray);
  28.         bool equal = true;
  29.  
  30.         for (int i = 0; i < length; i++)
  31.         {
  32.             // Check the arrays are equal
  33.             if (firstArray[i] != secondArray[i])
  34.             {
  35.                 equal = false;
  36.                 break;
  37.             }
  38.         }
  39.         Console.WriteLine();
  40.  
  41.         // Print the result
  42.         if (equal)
  43.         {
  44.             Console.WriteLine("firstArray == secondArray");
  45.         }
  46.         else
  47.         {
  48.             Console.WriteLine("firstArray != secondArray");
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement