Wednesday, 25 May 2016

TRAVERSING IN AN ARRAY- LINEAR SEARCH EXAMPLE

TRAVERSING AN ARRAY SIMPLY MEANS TO GO OVER THE ENTIRE DATA AT LEAST ONCE. SUPPOSE YOU ARE SEARCHING FOR A CHAPTER IN TEXTBOOK.....WHAT YOU DO IS GO TO INDEX AND SEARCH FOR THE CHAPTER.....SUPPOSE YOU FOUND THE CHAPTER AT 5TH ENTRY YOU'LL NOT GO FURTHER.......
HOWEVER THIS ISN'T THE CASE OF TRAVERSING. IN TRAVERSING ALL THE ENTRIES ARE CHECKED EVEN THOUGH YOU DON'T WANT THE REST....
THIS IS HOW THE CONCEPT OF TRAVERSING WORKS...................


NOW A QUICK PROGRAM FOR LINEAR SEARCH A NUMBER.


#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int arr[10]; \\THIS WILL CREATE AN ARRAY VARIABLE 'arr' containing 10 digits in

data type integer

int search;

for(int a=0;a<10;a++) \\for loop for accepting 10 numbers from the user

{

cout<<"Enter the"<<(a+1)<<" numer \t"; \\here (a+1) means 1

cin>>arr[a];

}

cout<<"Enter the number to be searched";

cin>>search;

for(int i=0;i<10;i++)

{

if(arr[i]==search) \\ in c++ == means equals to
{

cout<<"The number is"<<arr[i]<<"found at"<<(i+1)<<"th position";

                    \\here we used (i+1)th position because the index of the array starts from 0

}

else

{

cout<<"The number you are searching is not found";

}

getch();

}

}

No comments:

Post a Comment