Given two arrays, find the number from first array which not present in second array.
class Program
{
//method for dislpaying the array
public void displayMatrix(List<int> arry)
{
for (int i = 0; i < arry.Count; i++)
{
Console.Write(arry[i] + " ");
}
Console.WriteLine();
Console.WriteLine();
}
//method for searching a number from first array which is not present in second array
public void ValueSearch(List<int> first, List<int> second)
{
List<int> distinct = new List<int>();
for (int i = 0; i < first.Count; i++)
{
for (int j = 0; j < second.Count; j++)
{
//check each value in first array is equal to any of the value in second array
if (first[i] == second[j])
{
//if any value is equal, then change that value to zero or null in first array
first[i] = 0;
break;
}
}
}
//finding the values in first array
for (int i = 0; i < first.Count; i++)
{
//check for values not equal to zero or null
if (first[i] != 0)
{
// if not equal move that value to new array.
//so that new array contain only those values which are not in second array
distinct.Add(first[i]);
}
}
Console.Write("The numbers not in second array: ");
//display new array with values that are only in first array
displayMatrix(distinct);
}
static void Main(string[] args)
{
//Initialise two list for represting values in first array and second array
List<int> firstArr = new List<int>();
List<int> secndArr = new List<int>();
//add values to first array
firstArr.Add(2);
firstArr.Add(3);
firstArr.Add(4);
firstArr.Add(6);
firstArr.Add(1);
//add values to second array
secndArr.Add(8);
secndArr.Add(2);
secndArr.Add(5);
secndArr.Add(4);
secndArr.Add(7);
Program pgm = new Program();
Console.Write("The First Array: ");
//display first array
pgm.displayMatrix(firstArr);
Console.Write("The Second Array: ");
//display second array
pgm.displayMatrix(secndArr);
//call the method for value search
pgm.ValueSearch(firstArr, secndArr);
}
}
Output:
The First Array: 2 3 4 6 1
The Second Array: 8 2 5 4 7
The numbers not in second array: 3 6 1
No comments:
Post a Comment