C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING
Find Common Elements in Two Arrays
Learn how to find common elements in two arrays using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
5 1 2 3 4 5 5 3 4 4 5 6
Sample output
Common: 3 4 5
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int firstSize, secondSize, first[100], second[100];
scanf("%d", &firstSize);
if (firstSize < 0 || firstSize > 100) return 1;
for (int index = 0; index < firstSize; index++) scanf("%d", &first[index]);
scanf("%d", &secondSize);
if (secondSize < 0 || secondSize > 100) return 1;
for (int index = 0; index < secondSize; index++) scanf("%d", &second[index]);
printf("Common: ");
for (int index = 0; index < firstSize; index++) {
int alreadyPrinted = 0;
for (int previous = 0; previous < index; previous++)
if (first[previous] == first[index]) alreadyPrinted = 1;
if (alreadyPrinted) continue;
for (int next = 0; next < secondSize; next++) {
if (first[index] == second[next]) { printf("%d ", first[index]); break; }
}
}
printf("\n");
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Common: 3 4 5
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Search each distinct element of the first array inside the second array.
- Display the computed result.
Search each distinct element of the first array inside the second array.
EFFICIENCY
Time and space complexity
Time complexity
O(nm)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
