SlideShare a Scribd company logo
Evelyn
Program to implement telephone lookup both by names and numbers
Program plan:
 Declare a new Data type typeint of integer type to store phone numbers.
 Declare five functions Search_number() with parameter Name of string type to
show the number corresponding to the name entered by user, Search_name() with
parameter Number of typeint type to show the name corresponding to the number,
sortByName() to sort the data in vector by names, sortByNumber() to sort the
data in vector by numbers and Traverse_Name_Number() function to read name
and number in an particular order from the file and insert them in vector.
 Define a structure Person to store the name and numbers together, so that the values
will be read in such a way that first name will be read first, and then the phone number.
 Define function Traverse_Name_Number() to open a file, read values and by
using a while loop, insert data from it into vector person.
 Define function Search_number() which will return the number of the person
from the file when name is passed as parameter.
 Define function Search_name() to return the name of the person when number is
provided as parameter.
 Define function sortByName() which will sort the data contained in vector Person
by names.
 Define function sortByNumber() which will sort the data contained in vector
Person by numbers.
 Define function binarySearch_Name(). This function is responsible for binary
search for names in vector person and it is implemented recursively.
 Define function binarySearch_Number(). This function is responsible for
binary search for numbers in vector Person and it is implemented recursively.
 In the main() function, declare the variable name to store the name entered by a user,
number to store the number entered by the user, and choice to provide an option to
the user for the search.
 Call the function Traverse_Name_Number() to read the numbers and names in a
particular order stored in a file and insert it in vector person.
 Use do-while to take input from user until user wants to exit.
 Display Menu to the User for entering the choice of operation it wants to perform.
 Use switch to take user choices and accordingly execute the choice entered by user.
Program:
/**********************************************************
* Program to implement telephone lookup where lookup can*
*be handled both from numbers and names. *
**********************************************************/
/**********************************************************
*User-defined functions: *
*Search_number():to search a number when name is provided.*
*search_name(): to search a name when number is provided. *
*sortByName(): to sort the data contained by names. *
*sortByNumber(): to sort data contained by numbers. *
*binarySearch_Name():to binary search for name in vector *
*person. *
*binarySearch_Number(): to binary search for a number in*
*vector person. *
*traverse_Name_Number():to traverse data in file and *
*insert it in vector person. *
**********************************************************/
//Header file section
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include <map>
#include<conio.h>
using namespace std;
//use typedef for making PNum to store integers
//Defining new data Type
typedef int typeint;
Declaring Search_number(string Name) function which takes a parameter
Name of string type and will return the number of the person.
/**
Function to search the number when name is provided as
input.
@param Name for which number is to be searched.
@return Number which was to be searched.
**/
typeint Search_number(string Name);
Declaring Search_name(typeint Number) function which takes a parameter
Number of typeint type to return the name of person.
/**
Function to search the name when number is provided as
input.
@param Number for which name is to be searched.
@return Name which was to be searched.
**/
string Search_name(typeint Number);
Declaring Traverse_Name_Number() function to read name and number in an
particular order from the file and insert it in vector person.
Evelyn
/**
Function to read the names and numbers in file and place it
in vector.
**/
void Traverse_Name_Number();
Declaring a structure Person to store name and number of persons, so that the values
will be read in such a way that first name will be read and then its phone number and so
on.
struct Person
{
string name;
int number;
}temp;
Creating a vector person of Person type to store data for numbers of persons.
vector<Person> person;
Declaring sortByName() function to sort the data contained by names.
/**
Function to sort the data contained in vector person by
names.
@paarm person the vector to be sorted.
@return the sorted vector by names.
**/
void sortByName( vector<Person>& person);
Declaring sortByNumber() function to sort the data contained by telephone
numbers.
/**
Function to sort the data contained in vector person by
numbers.
@paarm person the vector to be sorted.
@return the sorted vector by numbers.
**/
void sortByNumber( vector<Person>& person);
Declaring an integer type variable pos that will contain the position of name and
number of person found during binary search operation.
int pos;
Defining function Traverse_Name_number() to open a file, read values and by
using a while loop insert data from file to vector person.
//Function Definition
void Traverse_Name_Number()
{
ifstream in;
string Name;
typeint Number;
Opening file containing numbers and names.
in.open("data.txt");
Inserting the names and numbers from the file in vector person using a while loop.
while (in.good())
{
in >> Name >> Number;
temp.name=Name;
temp.number=Number;
person.push_back(temp);
}
}
Defining function sortByName() which will sort the data contained in vector person
by names.
void sortByName( vector<Person>& person)
{
bool swap=true;
int j=0;
Person temp;
while(swap)
{
swap = false;
Using for loop checking in the vector if the name of person at a position is greater than
name of person at position after it if it is so then the positions of the persons are swapped.
for(int x=1; x<person.size()-j; ++x )
if( person[x-1].name > person[x].name ) // swap
{
temp = person[x];
person[x] = person[x-1];
person[x-1] = temp;
swap = true;
}
Evelyn
++j;
}
}
Defining function sortByNumber() which will sort the data contained in vector
person by numbers.
void sortByNumber( vector<Person>& person)
{
bool swap=true;
int j=0;
Person temp;
while(swap)
{
swap = false;
Using for loop checking in the vector if the number of person at a position is greater
than number of person at position after it if it is so then the positions of the persons are
swapped.
for(int x=1; x<person.size()-j; ++x )
if( person[x-1].number > person[x].number ) //swap
{
temp = person[x];
person[x] = person[x-1];
person[x-1] = temp;
swap = true;
}
++j;
}
}
Defining function binarySearch_Name().
This function is responsible for binary search for names in vector person and it is
implemented recursively.
It splits the array into two and continues searching in the part in which the name is
expected to reside.
/**
Function to binary search for a name in the vector.
@param person vector in which name is to be searched, value
the name to be searched and size which is size of vector
person.
@return mtach Boolean value which tells whether name is
found or not.
**/
bool binarySearch_Name(vector<Person>& person,string
value,int size)
//function heading
{
Declaring integer type variables first, last and mid to store first element, last
element and middle element in sub-list which is being traversed.
Initializing value of first, last and mid.
int first = 0;
int last = size;
int mid;
pos=0;
// variable containing the current
int position = -1;
Declaring a Boolean type variable match that will return false if match is not found
with name being searched otherwise returns true.
Initializing value of match.
bool match = false;
Using while that will execute until name to be searched is found or all positions in
vector get traversed.
while (!match && first <= last)
{
mid = (last + first) / 2;
If the name at mid is the name to be searched then reset the value for match as true
as name is found.
Set position that stores position of name to be searched to mid.
Return the value of match to show that search is successful.
if (person[mid].name == value)
{
match = true;
position = mid;
pos = position;
return match;
}
If the name at mid is not the value to be searched then if its value is less than value at
mid update value of last to point to vector index before mid as name must be in first
half of array as its value is less than person[mid].
else if (person[mid].name > value)
Evelyn
last = mid - 1;
/* toss out the second remaining half of the array and
search the first */
If the name at mid is not the value to be searched then if its value is greater than value at
mid update value of first to point to vector index after mid as name must be in
second half of array as its value is greater than person[mid].
else
first = mid + 1;
/* toss out the first remaining half of the array and
search the second*/
}
match = false;
return match;
}
Defining function binarySearch_Number().
This function is responsible for binary search for numbers in vector person and it is
implemented recursively.
It splits the array into two and continues searching in the part in which the number is
expected to reside.
/**
Function to binary search for a number in the vector.
@param person vector in which number is to be searched,
value the number to be searched and size which is size of
vector person.
@return mtach Boolean value which tells whether number is
found or not.
**/
bool binarySearch_Number(vector<Person>& person,int
value,int size)
//function heading
{
Declaring integer type variables first, last and mid to store first element, last
element and middle element in sub-list which is being traversed.
Initializing value of first, last and mid.
int first = 0;
int last = size;
int mid;
pos=0;
// variable containing the current
int position = -1;
Declaring a Boolean type variable match that will return false if match is not found
with name being searched otherwise returns true.
Initializing value of match.
bool match = false;
Using while that will execute until number to be searched is found or all positions in
vector get traversed.
while (!match && first <= last)
{
mid = (last + first) / 2;
If the number at mid is the name to be searched then reset the value for match as true
as name is found.
Set position that stores position of number to be searched to mid.
Return the value of match to show that search is successful.
if (person[mid].number == value)
{
match = true;
position = mid;
pos = position;
return match;
}
If the number at mid is not the value to be searched then if its value is less than value at
mid update value of last to point to vector index before mid as number must be in first
half of array as its value is less than person[mid].
else if (person[mid].number > value)
last = mid - 1;
/* toss out the second remaining half of the array and
search the first */
If the number at mid is not the value to be searched then if its value is greater than value
at mid update value of first to point to vector index after mid as number must be in
second half of array as its value is greater than person[mid].
else
first = mid + 1;
/* toss out the first remaining half of the array and
search the second*/
}
match = false;
return match;
}
Evelyn
Defining function Search_number() with parameter Name of string type to return
the position where number of the person is found by calling binarysearch_Name()
function.
//Function Definition
typeint Search_number(string Name)
{
if(binarySearch_Name(person,Name,person.size()))
return person[pos].number;
return 0;
}
Defining function Search_name() with parameter Number to return the position
where number of the person is found by calling binarysearch_Number() function.
//Function Definition
string Search_name(typeint Number)
{
if(binarySearch_Number(person,Number,person.size()))
return person[pos].name;
return "Not found";
}
//Main Function
main()
{
Declaring variables name to store name entered by user, number to store number
entered by user and choice to provide an option to the user to which lookup it want to
search.
//Variable Declaration
string name;
int number;
int choice;
Calling the function Traverse_Name_Number() to read the numbers and names in a
particular order stored in a file.
//Calling the function
Traverse_Name_Number();
Using do-while to take input from user until user wants to exit.
do
{
Displaying Menu to the User for entering the choice of operation it wants to perform.
//Display Menu to the User
cout<<"*********MENU*********";
cout<<"nPress 1 to look up by Name";
cout<<"nPress 2 to look up by Phone Number";
cout<<"nPress 3 to exit";
cout<<"nEnter your Choice:";
cin>>choice;
Using switch to take user choices.
//Providing option's to User
switch(choice)
{
If the user wants to lookup the data by name, then case 1 will be executed by making a
call to sortByName() and Search_number().
case 1: cout << "Input the name: ";
cin >> name;
sortByName(person);
cout << name << "'s number is: "
<< Search_number(name) << endl;
break;
If the user wants to lookup the data by number, then case 2 will be executed by
making a call to sortByNumber() and Search_name().
case 2: cout<<"Enter Phone Number:";
cin>>number;
sortByNumber(person);
cout<<number<<"'s name is: "
<< Search_name(number) << endl;
break;
If the user wants to exit from the program, then case 3 will be executed by making a
call to exit().
case 3: exit(0);
default: cout<<"n Wrong Entry... ";
}
cout<<endl<<endl;
Evelyn
}while(true);
return 0;
}
File Data.txt:
Sample Output:
*********MENU*********
Press 1 to look up by Name
Press 2 to look up by Phone Number
Press 3 to exit
Enter your Choice:1
Input the name: Robbert
Robbert's number is: 110458796
*********MENU*********
Press 1 to look up by Name
Press 2 to look up by Phone Number
Press 3 to exit
Enter your Choice:2
Enter Phone Number:457458756
457458756's name is: Lee
*********MENU*********
Press 1 to look up by Name
Press 2 to look up by Phone Number
Press 3 to exit
Enter your Choice:3
Output Explanation:
The program displays a menu to the User for entering the choice of operation required.
When the user enters 1 for looking up data by name, then case 1 is executed by
making a call to sortByName() and Search_number(). The data will initially be
sorted in a vector by names, then the number for that name will be returned.
When the user enters 2 for looking up data by number, then case 2 is executed by
making a call to sortByNumber() and Search_name(). The data will initially be
sorted in a vector by numbers, then the name for that number will be returned.
When the user enters 3, and want to exit from the program, then case 3 will is executed
by making a call to exit().

More Related Content

PDF
Unit 4 qba
DOCX
Unit 4 qba
PDF
‘go-to’ general-purpose sequential collections - from Java To Scala
PPT
C1320prespost
PDF
E2
KEY
Programming with Python - Week 3
PDF
Java chapter 6 - Arrays -syntax and use
PDF
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Unit 4 qba
Unit 4 qba
‘go-to’ general-purpose sequential collections - from Java To Scala
C1320prespost
E2
Programming with Python - Week 3
Java chapter 6 - Arrays -syntax and use
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1

What's hot (19)

DOCX
Java execise
PPTX
Programming in C sesion 2
PDF
Programming in C Session 1
PPTX
Data Structures in Python
PDF
Linked Lists: The Role of Locking : The Art of Multiprocessor Programming : N...
PPTX
Data types in python
PPT
Chapter2pp
PPT
M C6java7
PDF
computer notes - Linked list inside computer memory
PPTX
PPTX
Chapter 16 Dictionaries
PPTX
Python Lecture 6
PPTX
Lecture 7
PPT
Structures
PDF
The Expression Problem - Part 1
PPTX
Arrays in Data Structure and Algorithm
PPTX
Python dictionary
PDF
Structure In C
Java execise
Programming in C sesion 2
Programming in C Session 1
Data Structures in Python
Linked Lists: The Role of Locking : The Art of Multiprocessor Programming : N...
Data types in python
Chapter2pp
M C6java7
computer notes - Linked list inside computer memory
Chapter 16 Dictionaries
Python Lecture 6
Lecture 7
Structures
The Expression Problem - Part 1
Arrays in Data Structure and Algorithm
Python dictionary
Structure In C
Ad

Similar to Computer science solution - programming - big c plus plus (20)

DOCX
Lab # 9Q.6Q.7Header section#include iost ream#incl.docx
DOCX
UNIT V.docx
PDF
Searching
DOCX
Data Structure Project File
DOCX
PPS 5.5.BASIC ALGORITHMS SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...
PDF
PLEASE HELP IN C++For this test, you will need to create the follo.pdf
PDF
Data Structure & Algorithms - Operations
PPTX
Data structures and algorithms
DOCX
lab 2 in microprocessior and coontrolew.docx
PDF
UNIT IV -Data Structures.pdf
PPTX
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
DOCX
Write a program to find the number of comparisons using the binary se.docx
PPT
Searching.ppt
DOCX
1 Summer2017Assignment4IndividualAssignment-Due.docx
PPT
searching via traversal. binary search tree
PPT
cs1311lecture15wdljjjjjjjjjjjjjjjjjjjjjjj.ppt
PDF
I have the following code and I need to know why I am receiving the .pdf
PPT
4.2 bst
PPTX
Data Structures Unit 2 FINAL presentation.pptx
Lab # 9Q.6Q.7Header section#include iost ream#incl.docx
UNIT V.docx
Searching
Data Structure Project File
PPS 5.5.BASIC ALGORITHMS SEARCHING (LINEAR SEARCH, BINARY SEARCH ETC.), BASI...
PLEASE HELP IN C++For this test, you will need to create the follo.pdf
Data Structure & Algorithms - Operations
Data structures and algorithms
lab 2 in microprocessior and coontrolew.docx
UNIT IV -Data Structures.pdf
DATA STRUCTURE CLASS 12 COMPUTER SCIENCE
Write a program to find the number of comparisons using the binary se.docx
Searching.ppt
1 Summer2017Assignment4IndividualAssignment-Due.docx
searching via traversal. binary search tree
cs1311lecture15wdljjjjjjjjjjjjjjjjjjjjjjj.ppt
I have the following code and I need to know why I am receiving the .pdf
4.2 bst
Data Structures Unit 2 FINAL presentation.pptx
Ad

More from Praveen Tyagi (9)

DOCX
S5 pre reading percentage_final
DOCX
S2 authors purpose and perspective pre-reading_final
PDF
Ccss.math.content.6.ee.c.9 sample question
PDF
Adobe in design cs6 unit 4 creating books, table of contents, indexes and p...
PDF
Engineering chemistry textbook chapter 1 chemical bonding
PDF
College textbook business math and statistics - section b - business mathem...
PDF
Ccss.math.content.8.ee.c.8b sample question
PDF
Gre sample questions
PDF
Iit foundation grades 9 &amp; 10 - sample questions
S5 pre reading percentage_final
S2 authors purpose and perspective pre-reading_final
Ccss.math.content.6.ee.c.9 sample question
Adobe in design cs6 unit 4 creating books, table of contents, indexes and p...
Engineering chemistry textbook chapter 1 chemical bonding
College textbook business math and statistics - section b - business mathem...
Ccss.math.content.8.ee.c.8b sample question
Gre sample questions
Iit foundation grades 9 &amp; 10 - sample questions

Recently uploaded (20)

PDF
Tata consultancy services case study shri Sharda college, basrur
PDF
Digital Marketing & E-commerce Certificate Glossary.pdf.................
PDF
COST SHEET- Tender and Quotation unit 2.pdf
PPTX
svnfcksanfskjcsnvvjknsnvsdscnsncxasxa saccacxsax
PDF
A Brief Introduction About Julia Allison
PPTX
HR Introduction Slide (1).pptx on hr intro
PDF
Nidhal Samdaie CV - International Business Consultant
PPTX
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
PPTX
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
PDF
Chapter 5_Foreign Exchange Market in .pdf
PDF
How to Get Funding for Your Trucking Business
DOCX
unit 2 cost accounting- Tender and Quotation & Reconciliation Statement
PDF
Reconciliation AND MEMORANDUM RECONCILATION
PDF
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
PPTX
CkgxkgxydkydyldylydlydyldlyddolydyoyyU2.pptx
PDF
Types of control:Qualitative vs Quantitative
PDF
Solara Labs: Empowering Health through Innovative Nutraceutical Solutions
PDF
Laughter Yoga Basic Learning Workshop Manual
PPTX
New Microsoft PowerPoint Presentation - Copy.pptx
PDF
NISM Series V-A MFD Workbook v December 2024.khhhjtgvwevoypdnew one must use ...
Tata consultancy services case study shri Sharda college, basrur
Digital Marketing & E-commerce Certificate Glossary.pdf.................
COST SHEET- Tender and Quotation unit 2.pdf
svnfcksanfskjcsnvvjknsnvsdscnsncxasxa saccacxsax
A Brief Introduction About Julia Allison
HR Introduction Slide (1).pptx on hr intro
Nidhal Samdaie CV - International Business Consultant
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
Chapter 5_Foreign Exchange Market in .pdf
How to Get Funding for Your Trucking Business
unit 2 cost accounting- Tender and Quotation & Reconciliation Statement
Reconciliation AND MEMORANDUM RECONCILATION
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
CkgxkgxydkydyldylydlydyldlyddolydyoyyU2.pptx
Types of control:Qualitative vs Quantitative
Solara Labs: Empowering Health through Innovative Nutraceutical Solutions
Laughter Yoga Basic Learning Workshop Manual
New Microsoft PowerPoint Presentation - Copy.pptx
NISM Series V-A MFD Workbook v December 2024.khhhjtgvwevoypdnew one must use ...

Computer science solution - programming - big c plus plus

  • 1. Evelyn Program to implement telephone lookup both by names and numbers Program plan:  Declare a new Data type typeint of integer type to store phone numbers.  Declare five functions Search_number() with parameter Name of string type to show the number corresponding to the name entered by user, Search_name() with parameter Number of typeint type to show the name corresponding to the number, sortByName() to sort the data in vector by names, sortByNumber() to sort the data in vector by numbers and Traverse_Name_Number() function to read name and number in an particular order from the file and insert them in vector.  Define a structure Person to store the name and numbers together, so that the values will be read in such a way that first name will be read first, and then the phone number.  Define function Traverse_Name_Number() to open a file, read values and by using a while loop, insert data from it into vector person.  Define function Search_number() which will return the number of the person from the file when name is passed as parameter.  Define function Search_name() to return the name of the person when number is provided as parameter.  Define function sortByName() which will sort the data contained in vector Person by names.  Define function sortByNumber() which will sort the data contained in vector Person by numbers.  Define function binarySearch_Name(). This function is responsible for binary search for names in vector person and it is implemented recursively.  Define function binarySearch_Number(). This function is responsible for binary search for numbers in vector Person and it is implemented recursively.  In the main() function, declare the variable name to store the name entered by a user, number to store the number entered by the user, and choice to provide an option to the user for the search.  Call the function Traverse_Name_Number() to read the numbers and names in a particular order stored in a file and insert it in vector person.  Use do-while to take input from user until user wants to exit.  Display Menu to the User for entering the choice of operation it wants to perform.  Use switch to take user choices and accordingly execute the choice entered by user. Program: /********************************************************** * Program to implement telephone lookup where lookup can* *be handled both from numbers and names. * **********************************************************/ /********************************************************** *User-defined functions: * *Search_number():to search a number when name is provided.* *search_name(): to search a name when number is provided. * *sortByName(): to sort the data contained by names. * *sortByNumber(): to sort data contained by numbers. * *binarySearch_Name():to binary search for name in vector * *person. * *binarySearch_Number(): to binary search for a number in* *vector person. * *traverse_Name_Number():to traverse data in file and * *insert it in vector person. * **********************************************************/ //Header file section #include <iostream> #include <cstdlib> #include <string> #include <fstream> #include <map> #include<conio.h> using namespace std; //use typedef for making PNum to store integers //Defining new data Type typedef int typeint; Declaring Search_number(string Name) function which takes a parameter Name of string type and will return the number of the person. /** Function to search the number when name is provided as input. @param Name for which number is to be searched. @return Number which was to be searched. **/ typeint Search_number(string Name); Declaring Search_name(typeint Number) function which takes a parameter Number of typeint type to return the name of person. /** Function to search the name when number is provided as input. @param Number for which name is to be searched. @return Name which was to be searched. **/ string Search_name(typeint Number); Declaring Traverse_Name_Number() function to read name and number in an particular order from the file and insert it in vector person.
  • 2. Evelyn /** Function to read the names and numbers in file and place it in vector. **/ void Traverse_Name_Number(); Declaring a structure Person to store name and number of persons, so that the values will be read in such a way that first name will be read and then its phone number and so on. struct Person { string name; int number; }temp; Creating a vector person of Person type to store data for numbers of persons. vector<Person> person; Declaring sortByName() function to sort the data contained by names. /** Function to sort the data contained in vector person by names. @paarm person the vector to be sorted. @return the sorted vector by names. **/ void sortByName( vector<Person>& person); Declaring sortByNumber() function to sort the data contained by telephone numbers. /** Function to sort the data contained in vector person by numbers. @paarm person the vector to be sorted. @return the sorted vector by numbers. **/ void sortByNumber( vector<Person>& person); Declaring an integer type variable pos that will contain the position of name and number of person found during binary search operation. int pos; Defining function Traverse_Name_number() to open a file, read values and by using a while loop insert data from file to vector person. //Function Definition void Traverse_Name_Number() { ifstream in; string Name; typeint Number; Opening file containing numbers and names. in.open("data.txt"); Inserting the names and numbers from the file in vector person using a while loop. while (in.good()) { in >> Name >> Number; temp.name=Name; temp.number=Number; person.push_back(temp); } } Defining function sortByName() which will sort the data contained in vector person by names. void sortByName( vector<Person>& person) { bool swap=true; int j=0; Person temp; while(swap) { swap = false; Using for loop checking in the vector if the name of person at a position is greater than name of person at position after it if it is so then the positions of the persons are swapped. for(int x=1; x<person.size()-j; ++x ) if( person[x-1].name > person[x].name ) // swap { temp = person[x]; person[x] = person[x-1]; person[x-1] = temp; swap = true; }
  • 3. Evelyn ++j; } } Defining function sortByNumber() which will sort the data contained in vector person by numbers. void sortByNumber( vector<Person>& person) { bool swap=true; int j=0; Person temp; while(swap) { swap = false; Using for loop checking in the vector if the number of person at a position is greater than number of person at position after it if it is so then the positions of the persons are swapped. for(int x=1; x<person.size()-j; ++x ) if( person[x-1].number > person[x].number ) //swap { temp = person[x]; person[x] = person[x-1]; person[x-1] = temp; swap = true; } ++j; } } Defining function binarySearch_Name(). This function is responsible for binary search for names in vector person and it is implemented recursively. It splits the array into two and continues searching in the part in which the name is expected to reside. /** Function to binary search for a name in the vector. @param person vector in which name is to be searched, value the name to be searched and size which is size of vector person. @return mtach Boolean value which tells whether name is found or not. **/ bool binarySearch_Name(vector<Person>& person,string value,int size) //function heading { Declaring integer type variables first, last and mid to store first element, last element and middle element in sub-list which is being traversed. Initializing value of first, last and mid. int first = 0; int last = size; int mid; pos=0; // variable containing the current int position = -1; Declaring a Boolean type variable match that will return false if match is not found with name being searched otherwise returns true. Initializing value of match. bool match = false; Using while that will execute until name to be searched is found or all positions in vector get traversed. while (!match && first <= last) { mid = (last + first) / 2; If the name at mid is the name to be searched then reset the value for match as true as name is found. Set position that stores position of name to be searched to mid. Return the value of match to show that search is successful. if (person[mid].name == value) { match = true; position = mid; pos = position; return match; } If the name at mid is not the value to be searched then if its value is less than value at mid update value of last to point to vector index before mid as name must be in first half of array as its value is less than person[mid]. else if (person[mid].name > value)
  • 4. Evelyn last = mid - 1; /* toss out the second remaining half of the array and search the first */ If the name at mid is not the value to be searched then if its value is greater than value at mid update value of first to point to vector index after mid as name must be in second half of array as its value is greater than person[mid]. else first = mid + 1; /* toss out the first remaining half of the array and search the second*/ } match = false; return match; } Defining function binarySearch_Number(). This function is responsible for binary search for numbers in vector person and it is implemented recursively. It splits the array into two and continues searching in the part in which the number is expected to reside. /** Function to binary search for a number in the vector. @param person vector in which number is to be searched, value the number to be searched and size which is size of vector person. @return mtach Boolean value which tells whether number is found or not. **/ bool binarySearch_Number(vector<Person>& person,int value,int size) //function heading { Declaring integer type variables first, last and mid to store first element, last element and middle element in sub-list which is being traversed. Initializing value of first, last and mid. int first = 0; int last = size; int mid; pos=0; // variable containing the current int position = -1; Declaring a Boolean type variable match that will return false if match is not found with name being searched otherwise returns true. Initializing value of match. bool match = false; Using while that will execute until number to be searched is found or all positions in vector get traversed. while (!match && first <= last) { mid = (last + first) / 2; If the number at mid is the name to be searched then reset the value for match as true as name is found. Set position that stores position of number to be searched to mid. Return the value of match to show that search is successful. if (person[mid].number == value) { match = true; position = mid; pos = position; return match; } If the number at mid is not the value to be searched then if its value is less than value at mid update value of last to point to vector index before mid as number must be in first half of array as its value is less than person[mid]. else if (person[mid].number > value) last = mid - 1; /* toss out the second remaining half of the array and search the first */ If the number at mid is not the value to be searched then if its value is greater than value at mid update value of first to point to vector index after mid as number must be in second half of array as its value is greater than person[mid]. else first = mid + 1; /* toss out the first remaining half of the array and search the second*/ } match = false; return match; }
  • 5. Evelyn Defining function Search_number() with parameter Name of string type to return the position where number of the person is found by calling binarysearch_Name() function. //Function Definition typeint Search_number(string Name) { if(binarySearch_Name(person,Name,person.size())) return person[pos].number; return 0; } Defining function Search_name() with parameter Number to return the position where number of the person is found by calling binarysearch_Number() function. //Function Definition string Search_name(typeint Number) { if(binarySearch_Number(person,Number,person.size())) return person[pos].name; return "Not found"; } //Main Function main() { Declaring variables name to store name entered by user, number to store number entered by user and choice to provide an option to the user to which lookup it want to search. //Variable Declaration string name; int number; int choice; Calling the function Traverse_Name_Number() to read the numbers and names in a particular order stored in a file. //Calling the function Traverse_Name_Number(); Using do-while to take input from user until user wants to exit. do { Displaying Menu to the User for entering the choice of operation it wants to perform. //Display Menu to the User cout<<"*********MENU*********"; cout<<"nPress 1 to look up by Name"; cout<<"nPress 2 to look up by Phone Number"; cout<<"nPress 3 to exit"; cout<<"nEnter your Choice:"; cin>>choice; Using switch to take user choices. //Providing option's to User switch(choice) { If the user wants to lookup the data by name, then case 1 will be executed by making a call to sortByName() and Search_number(). case 1: cout << "Input the name: "; cin >> name; sortByName(person); cout << name << "'s number is: " << Search_number(name) << endl; break; If the user wants to lookup the data by number, then case 2 will be executed by making a call to sortByNumber() and Search_name(). case 2: cout<<"Enter Phone Number:"; cin>>number; sortByNumber(person); cout<<number<<"'s name is: " << Search_name(number) << endl; break; If the user wants to exit from the program, then case 3 will be executed by making a call to exit(). case 3: exit(0); default: cout<<"n Wrong Entry... "; } cout<<endl<<endl;
  • 6. Evelyn }while(true); return 0; } File Data.txt: Sample Output: *********MENU********* Press 1 to look up by Name Press 2 to look up by Phone Number Press 3 to exit Enter your Choice:1 Input the name: Robbert Robbert's number is: 110458796 *********MENU********* Press 1 to look up by Name Press 2 to look up by Phone Number Press 3 to exit Enter your Choice:2 Enter Phone Number:457458756 457458756's name is: Lee *********MENU********* Press 1 to look up by Name Press 2 to look up by Phone Number Press 3 to exit Enter your Choice:3 Output Explanation: The program displays a menu to the User for entering the choice of operation required. When the user enters 1 for looking up data by name, then case 1 is executed by making a call to sortByName() and Search_number(). The data will initially be sorted in a vector by names, then the number for that name will be returned. When the user enters 2 for looking up data by number, then case 2 is executed by making a call to sortByNumber() and Search_name(). The data will initially be sorted in a vector by numbers, then the name for that number will be returned. When the user enters 3, and want to exit from the program, then case 3 will is executed by making a call to exit().