In this tutorial we will see, Given two arrays 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.
Means in general in this tutorial, you will learn how to write C program to find the missing number in second array.
This program is very simple and easy. As we have fixed array so we are not going to take any array input from the user.
Just execute the program and you will find the missing element in the second array which is available in first array.
Our Logic behind this program is:
- We have already two array arr1 with elements 1, 2, 3, 4, and 5.
- arr2 with elements 2, 3, 1, 0, and 5.
- We will add the all elements of arr1 together.
- Similarly for arr2 we will add it.
- And at last we will subtract arr1 elements sum with arr2.
- And we will get the missing number of arr2.
How our program will behave?
Our program have already two array arr1 and arr2.
arr1 have 1, 2, 3, 4, 5 elements and arr2 have 2,3,1,0,5 elements.
So it should print 4 in output as in second array 4 is missing which is in array first.
Program to find missing number in second array which is in first array.
#include<stdio.h>
#include<conio.h>
void notPresent(int *arr1,int *arr2,int size){
int i, sum=0;
for(i=0;i<size;i++){
sum=sum+arr1[i]-arr2[i];
}
printf("missing element is %d",sum);
}
int main(){
int arr1[]={1,2,3,4,5};
int arr2[]={2,3,1,0,5};
int size=sizeof(arr1)/sizeof(arr1[0]);
notPresent(arr1,arr2,size);
getch();
}
Output:
Explanation of above program for finding missing element in second array
- In the above program we have taken two array arr1 of size 5 and arr2 also of size 5.
- arr1 have 5 elements 1, 2, 3, 4, and 5.
- arr2 array have 5 elements 2, 3, 1, 0 and 5.
- We ave first calculate the size of array.
- Here a method notPresent(arr1, arr2, size), all the logic is written in the body of its.
- Inside the notPresent(arr1, arr2, size) method we have two variable i and size.
- And one for loop to calculate the missing numbers.
- In for loop we are subtracting the element of similar index from arr1 to arr2 and then added it with the previous sum.
- And at last what is stored in sum variable, is our missing number.
This was the all logic behind finding the missing number in second array using C language.