Advertisements
Advertisements
प्रश्न
Write a program for the following.
Create two arrays TEC[ ] and TEH[ ], both of type int and size 8 and fill them with variables. Create a third array TIN[ ] that contains only the common elements of both the arrays.
For example:
| Input | TEC[ ] | 17 | 54 | 36 | 87 | 44 | 92 | 28 | 77 |
| Input | TEH[ ] | 72 | 94 | 44 | 33 | 77 | 87 | 17 | 37 |
| Output | TIN[ ] | 17 | 87 | 44 | 77 |
कोड लेखन
Advertisements
उत्तर
import java.util.Scanner;
public class CommonElements
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int TEC[] = new int;
int TEH[] = new int;
System.out.println("Enter 8 integers for array TEC:");
for (int j = 0; j < 8; j++)
{
TEC[j] = sc.nextInt();
}
System.out.println("Enter 8 integers for array TEH:");
for (int j = 0; j < 8; j++)
{
TEH[j] = sc.nextInt();
}
int temp[] = new int;
int commonCount = 0;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (TEC[i] == TEH[j])
{
boolean isDuplicate = false;
for (int k = 0; k < commonCount; k++)
{
if (temp[k] == TEC[i])
{
isDuplicate = true;
break;
}
}
if (!isDuplicate)
{
temp[commonCount] = TEC[i];
commonCount++;
}
break;
}
}
}
int TIN[] = new int[commonCount];
for (int j = 0; j < commonCount; j++)
{
TIN[j] = temp[j];
}
System.out.print("\nTIN[ ]\t");
for (int j = 0; j < TIN.length; j++)
{
System.out.print(TIN[j] + "\t");
}
sc.close();
}
}shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 7: Arrays - One Dimension - Exercises [पृष्ठ १७७]
