Write a C++ program that declares an array list (a one-dimensional array) of 10 components of
type int. Initialize the array in a for loop by using rand() function with some random values
ranging from 0 to 250 and then display the components of array list horizontally by using another
for loop.
Take an integer as an input from user to be searched in the list by comparing the desired item with
each component of the array.
Program will display the index of component if searching is successful otherwise it should display an
appropriate message that “Searched item is not found!”.
Hint: Also include appropriate header files for predefined functions to be used.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int arr[10];
srand(static_cast<unsigned int>(time(0)));
for (int i = 0; i < 10; i++)
{
arr[i] = rand() % 250;
}
for (int i = 0; i < 10; i++)
{
cout<<arr[i]<<" ";
}
int srch;
cout << "\nPlease, enter a value to be searched in an array: ";
cin >> srch;
int i;
bool serched = false;
for (i = 0; i < 10; i++)
{
if (arr[i] == srch)
{
serched = true;
break;
}
}
if (serched == true)
{
cout << "Item " << srch << " was found at position " << i;
}
else
{
cout << "Searched item is not found!";
}
}
Comments
Leave a comment