hi, I have a question in #c
I wrote a code but the printing is not correct. In the code there is an operation that receives two arrays of type int and returns a new array of type int whose values ??are all the values ??common to the two previous arrays
int[] one = new int[] { 4, 5, 6, 7 };
int[] two = new int[] { 4, 5, 7, 8 };
static int[] twoArrays(int[] one, int[] two)
{
int[] newArray = new int[one.Length];
int x = 0;
for (int i = 0; i < one.Length; i++)
{
for (int k = 0; k < two.Length; k++)
{
if (one[i] == two[i])
{
newArray[x] = one[i];
x++;
}
}
}
return newArray;
}
Console.WriteLine(twoArrays(one, two));
Amit MohantyPosted Apr 27, 2023, 6:35 AM
The issue with the code is in the comparison inside the second for loop.
To fix this, change
if (one[i] == two[i])toif (one[i] == two[k]).Naimish MakwanaPosted Apr 27, 2023, 4:28 AM
Hi! I noticed a couple of issues in your code. Here are some suggestions to fix them:
The size of the new array should be the minimum of the two input arrays, since the common elements cannot exceed that size. You can find the minimum using
Math.Min(one.Length, two.Length).In the inner loop, you need to compare
one[i]withtwo[k], nottwo[i]. This is becauseiis already used to indexone, and using it to indextwowould not compare the elements pairwise.The
Console.WriteLinestatement is incorrect, because you are trying to print an array instead of its elements. You can use a loop to print each element, or use thestring.Joinmethod to concatenate the elements with a delimiter.Here is the corrected code:
This should output:
4, 5, 7