Untitled
unknown
plain_text
2 years ago
3.6 kB
5
Indexable
Array implementation considered, It can be extended to dynamic arrays Code and output screen shot shared as follows #include <iostream> #include <cstdlib> #define MAX_CONTACTS 100 using namespace std; class Contact{ string name; string number; public: Contact(){ name = "Unknown"; number = "0"; } Contact(string contactName,string contactNumber){ name= contactName; number = contactNumber; } string getName(){ return name; } string getNumber(){ return number; } void setName(string n){ name = n; } void setNumber(string n){ number = n; } void print(string modeOfDisplay){ if(modeOfDisplay =="light") cout<<name<<" "<<number<<endl; else if(modeOfDisplay=="Headers") cout<<"Name: "<<name<<endl<<"Number: "<<number<<endl; else { cout<<"Not a valid argument to contacts print \n"; exit(-1); } } }; class AddressBook{ //In case of extending to dynamic array, MAX_CONTACTS will be removed and a contacts pointer is used Contact contacts[MAX_CONTACTS]; int noOfContacts; int search(string name){ // search the position where the contact is there for(int i=0;i<noOfContacts;i++) if(name==contacts[i].getName()) return i; // not there return -1; } public: AddressBook(){ noOfContacts = 0; } bool add(Contact contact){ // check it exists or not int pos = search(contact.getName()); if(pos==-1){ contacts[noOfContacts] = contact; noOfContacts++; return true; } // already exists else return false; } bool remove(string name){ // check it exists or not int pos = search(name); if(pos!=-1){ for(int i=pos;i<noOfContacts-1;i++) contacts[i] = contacts[i+1]; noOfContacts--; return true; } // not exists else return false; } void print(){ if(noOfContacts==0) cout<<"No contacts are available"<<endl; for(int i=0;i<noOfContacts;i++) cout<<contacts[i].getName()<<" "<<contacts[i].getNumber()<<endl; } }; int main(){ AddressBook addrBook1; string contactName, contactNumber; bool addStatus, removeStatus; Contact con; int choice; do { cout<<"1. Display AddressBook\n"; cout<<"2.Add new contact\n"; cout<<"3.Remove contact\n"; cout<<"4.Exit\n"; cout<<"Enter your choice: "; cin>>choice; switch(choice){ case 1 : addrBook1.print(); break; case 2 : cout<<"\nEnter name, number to add to contact"; cin>>contactName>>contactNumber; con.setName(contactName); con.setNumber(contactNumber); addStatus=addrBook1.add(con); if(addStatus==true) cout<<"\nAdded succesfully\n"; else cout<<"Add failed\n"; break; case 3 : cout<<"\n Enter name of the contact to remove"; cin>>contactName; removeStatus = addrBook1.remove(contactName); if( removeStatus== true) cout<<"\nremoved succesfully\n"; else cout<<"remove failed\n"; break; } } while(choice!=4); } hp En 1 (2:47,76%) )) 4:48 PM venky@venky:-/chegg venky@venky:-/chegg$ ./a.out 1. Display AddressBook 2. Add new contact 3. R Was this answer helpful?
Editor is loading...