Search an element in an Array using Linear Search concept in C++ (WITH EXPLANATION VIDEO)

#include<iostream>
#include<iomanip>
#include<time.h>
#include<stdlib.h>
using namespace std; 

void searchArray()
{
int i, n, ar[50], srch, flag=0;
cout<<"===============================\n";
cout<<"Search an Element in an array\n";
cout<<"===============================\n";
cout<<"Enter size of Array (Max. 50): ";
cin>>n;
srand((unsigned)time(NULL));
for(i=0;i<n;i++)
{
if(i%10==0)
cout<<endl;
ar[i]=rand()%41+10;
cout<<setw(4)<<ar[i];
}
cout<<"\nEnter Number to search in an array: ";
cin>>srch;
for(i=0;i<n;i++)
{
if(ar[i]==srch)
{
cout<<"Number "<<srch<<" found at index no. "<<i<<" of array...\n";
flag++;
}
}
if(!flag)
{
cout<<"Number: "<<srch<<" not found in array....\n";
}
}

int main()
{
searchArray();
}



void searchAndReplace()
{
int i, n, ar[50], srch, newNum, flag=0;
cout<<"===============================\n";
cout<<"Search an Element in an array\n";
cout<<"===============================\n";
cout<<"Enter size of Array (Max. 50): ";
cin>>n;
srand((unsigned)time(NULL));
for(i=0;i<n;i++)
{
if(i%10==0)
cout<<endl;
ar[i]=rand()%41+10; //range between 10 and 50
cout<<setw(4)<<ar[i];
}
cout<<"\nEnter Number to search in an array: ";
cin>>srch;
for(i=0;i<n;i++)
{
if(ar[i]==srch)
{
flag++;
}
}
if(flag)
{
cout<<"Enter New Number to replace: ";
cin>>newNum;
for(i=0;i<n;i++)
{
if(ar[i]==srch)
{
ar[i]=newNum;
}
}
cout<<"\nAfter replacing number "<<srch<<" with new number "
    <<newNum<<", array has following values...\n";
}
else
{
cout<<"Number: "<<srch<<" not found in array....\n";
cout<<"Array list remains same.....\n";
}
for(i=0;i<n;i++)
{
if(i%10==0)
cout<<endl;
cout<<setw(4)<<ar[i];
}
}













No comments

Post your comments

Powered by Blogger.