Find a number not present in second array from given two arrays in C++

This C++ program is able to find which number is not present in the second array from given two arrays by comparing them. This is a question based on array and it utilizes a very basic concept i.e. nested for loop. This is very important in the application point of view for arrays.

How to find which number is not present in second array from the given two arrays

Problem statement 

There are two integer arrays of small length. These arrays contain the same elements in any order with one different value. You need to find this value which is present in first but not second one.

Find which number is not present in the second array from the arrays 1,2,3,4,5 and 2,0,1,3,5.

Problem approach

  • Declare two arrays.
  • Store values as given in the problem statement.
  • Analyze the values of first and second arrays then find the required value.
  • Print the value on the screen.

Program/Source code

Following is the complete C++ program for the required problem statement.

/* C++ program to find number which is not present in the second array but present in first array
 ***change the array values to get different result***
 */

#include <iostream>

using namespace std;

int main()
{
    int array1[]={1,2,3,4,5};         // array 1
    int array2[]={2,0,1,3,5};          // array 2

    int check=0;                    // check state of availability
    int num=0;

    for(int i=0;i<5;i++){                        // loop for array 1
        for(int j=0;j<5;j++){               // loop for array 2
            if(array1[i]==array2[j])
                check=1;                        // change availability state
        }
        if(check==0)                            // check availability of number
            num=array1[i];
        check=0;                                // reset availability variable
    }

    cout<<"Array 1: ";
    for(int i=0;i<5;i++)
        cout<<array1[i]<<"\t";

    cout<<"\nArray 2: ";
    for(int i=0;i<5;i++)
        cout<<array2[i]<<"\t";

    cout<<"\nThe number present int first array but not in second is "<<num;

    return 0;
}

Output

Array 1: 1 2 3 4 5
Array 2: 2 3 1 0 5
The number present int first array but not in second is 4
Process returned 0 (0x0) execution time : 0.141 s
Press any key to continue.

Program explanation

  • Declare two arrays viz. array1 and array1.
  • Store given values in respective array variables.
  • Declare a variable check to show the availability of a specific value in array1 and array2.
  • Use nested for loop to check the availability and change the value of check variable accordingly.
  • Store the required number in a variable and print it on the screen.

Also, read

How to print array’s mirror image of 2D array (3X3) in C++

Leave a Reply

Your email address will not be published. Required fields are marked *