For following program, please create functions for doing sort, search, display,
ID: 3549921 • Letter: F
Question
For following program, please create functions for doing sort, search, display, replace, delete, and add. You can use dynamic memory allocation for enlarge the size of pointer array for adding a new country.
#include<stdio.h>
int main()
{
inti;
char * country[5];
country[0]="India";
country[1]="America";
country[2]="China";
country[3]="Australia";
country[4]="England";
for(i=0;i<5;i++)
{
puts(country[i]);
}
}
India
America
China
Australia
England
Press any key to continue . . .
Explanation / Answer
#include<stdio.h>
#include<conio.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
int len;
static int _sort( const void* a, const void *b )
{
return strcmp( *( const char** )a, *( const char** )b );
}
void display(char **country)
{
int i=0;
for(i=0;i<len;i++)
{
if(strcmp(country[i],"")!=0)
cout<<country[i]<<endl;
}
}
void sorting(char **country)
{
qsort( country, len, sizeof( const char* ), _sort );
display(country);
}
int search(char **country,char *target)
{
int i=0;
for(i=0;i<len;i++)
{
if(strcmp(country[i],target) == 0)
{
//cout<<"Country found at index "<<i+1<<endl;
break;
}
}
if(i == len)
cout<<"country not found"<<endl;
if(i<len)
return i;
else
return -1;
}
void replace(char **country)
{
int i;
char previous[100],newcountry[100];
cout<<"enter old country to be replaced "<<endl;
cin>>previous;
cout<<"enter name of new country"<<endl;
cin>>newcountry;
i = search(country,previous);
country[i] = newcountry;
display(country);
}
void del(char **country)
{
int i;
char target[100];
cout<<"enter name of country to be deleted"<<endl;
cin>>target;
i = search(country,target);
country[i] = "";
display(country);
}
void add(char **country)
{
int i,j=-1;
char newcountry[100];
cout<<"enter name of new country"<<endl;
cin>>newcountry;
for(i=0;i<len;i++)
{
if(strcmp(country[i],"")==0)
j=i;
}
cout<<"adding new country"<<endl;
if(j!= -1)
{
country[j] = newcountry;
}
else
{
//country = realloc(country, (len+1) * sizeof(country[0]));
country[len] = newcountry;
len=len+1;
}
display(country);
}
int main()
{
int i;
char target[100],*country[500];
country[0]="India";
country[1]="America";
country[2]="China";
country[3]="Australia";
country[4]="England";
len = 5;
display(country);
sorting(country);
cout<<"enter country to search ";
cin>>target;
search(country,target);
replace(country);
del(country);
add(country);
system("pause");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.