In: Computer Science
goal of this function will be to add an element to an already existing array in C/C++.
bool add(structure dir[], int& size, const char nm[], const char ph[]){
//code here
}
add = function name
structure = structure with two fields
{
char name[20];
char phone[13];
}
int& size = # of entries in dir
nm = name that's going to be added
ph = phone that's going to be added.
return true if entry was successfully added, false if there's no more room.
if entry was added, size will reflect the new number of entries in dir.
Please look at my code and in case of indentation issues check the screenshots.
---------------main.cpp---------------
#include <iostream>
#include <string.h>
using namespace std;
#define MAX 1000
struct phoneBook //structure with
two fields
{
char name[20];
char phone[13];
};
//to add an element to an already existing array
bool add(struct phoneBook dir[], int& size, const char nm[],
const char ph[]){
if(size == MAX)
//checks
if number of elements is equal to the max capacity
return false;
//returns
false, since new element cannot be added NO ROOM
strcpy(dir[size].name, nm);
//copy nm to array location at index size
strcpy(dir[size].phone, ph); //copy ph to
array location at index size
size++;
//increase size
return true;
//return
true since element is added successfully at the end
}
int main()
{
struct phoneBook dir[MAX];
//array of structure type, that can store 1000
name,phone numbers
int size = 0;
//# of
entries currently in dir
int val;
val = add(dir, size, "Watson",
"9999999999"); //add first
element
if(val){
cout << "Size is " <<
size << endl;
cout << "Entry added
successfully" << endl;
}
val = add(dir, size, "John",
"8888888888");
//add second element
if(val){
cout << "Size is " <<
size << endl;
cout << "Entry added
successfully" << endl;
}
val = add(dir, size, "Jim",
"7777777777");
//add third element
if(val){
cout << "Size is " <<
size << endl;
cout << "Entry added
successfully" << endl;
}
cout << "\nThe phoneBook has the
following entries:\n"; //print all elements
for(int i = 0; i < size; i++){
cout << dir[i].name
<< " " << dir[i].phone << endl;
}
return 0;
}
--------------Screenshots-------------------
------------------Output-----------------
------------------------------------------------------------------------------------------
Please give a thumbs up if you find this answer helpful.
If it doesn't help, please comment before giving a thumbs
down.
Please Do comment if you need any clarification.
I will surely help you.
Thankyou