In: Computer Science
C++ programming language. Write a program that will read in id numbers and place them in an array.The array is dynamically allocated large enough to hold the number of id numbers given by the user. The program will then input an id and call a function to search for that id in the array. It will print whether the id is in the array or not.
Sample Run:
Please input the number of id numbers to be read
4
Please enter an id number
96
Please enter an id number
97
Please enter an id number
98
Please enter an id number
99
Please input an id number to be searched
67
67 is not in the array
If you have any problem with the code feel free to comment.
Program
#include <iostream>
using namespace std;
int main( )
{
//pointer to int
int* ar = NULL;
//getting the length of the array
int len;
cout<<"Please input the number of id numbers to be read"<<endl;
cin>>len;
//allocating space to the array according to len
ar = new int[len];
//taking id inputs
for(int i=0; i<len; i++){
cout<<"Please enter an id number"<<endl;
cin>>ar[i];
}
//taking the search variable input
int serach;
cout<<"Please input an id number to be searched"<<endl;
cin>>serach;
//checking if the id for search is present in the array or not
bool flag = false;
for(int i=0; i<len; i++){
if(serach == ar[i]){
flag = true;
break;
}
}
if(flag)
cout<<serach<<" is in the array"<<endl;
else
cout<<serach<<" is not in the array"<<endl;
//freeing up the allocated space
delete [] ar;
ar = NULL;
return 0;
}
Output