Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++ Write a program, which will ask the user how many names (one word, no spa

ID: 3807119 • Letter: I

Question

In C++

Write a program, which will ask the user how many names (one word, no spaces) they wish to enter. The program will then read that many names, store them in a two dimensional array of characters (one row per name), print them in the order they were entered, then sort them in increasing alphabetical order, and print them in sorted order. The sort will be done without regard to the case of the letters (i.e. case insensitive sort). The printing of each name MUST be done with the characters as they were typed, you cannot change the case.

The maximum number of names to be handled will be 20.

The maximum number of printable characters in a name is 15.

Use a two dimensional array to store the names.

Create a function to read in all the names.

Create a function to do the sort (modify the bubble sort discussed in class and in the text book).

Explanation / Answer

// C++ code


#include <iostream>
#include <string>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
using namespace std;

#define MAXNAMELENGTH 15


char personName[20][MAXNAMELENGTH];
char *names[20];

void inputNames(int totalNames)
{
int i;
for (i=0; i<totalNames; i++) {
names[i] = &personName[i][0];
fgets(names[i], MAXNAMELENGTH, stdin);
}
}

void outputNames(const char* titleString, int totalNames)
{
int i;
printf("%s ", titleString);
for (i=0; i<totalNames; i++)
printf("%s", names[i]);
}

int comparison(const void*s1, const void*s2)
{
char *pointer1 = *(char**)s1;
char *pointer2 = *(char**)s2;
return strncasecmp(pointer1, pointer2, MAXNAMELENGTH);
}


int main(int argc, char* argv[])
{
char bf[20];
int numNames = 0;

printf("Enter total number of names: ");
fgets(bf, sizeof(bf), stdin);
numNames = atoi(bf);
if (numNames < 0 || numNames > 20)
printf("Number of names must not exceed 20 "),
exit(-1);

inputNames(numNames);
outputNames(" Original list of names", numNames);
qsort(names, numNames, sizeof(char*), comparison);
outputNames(" Sorted list of names", numNames);
return 0;
}

/*
output:

Enter total number of names: 5
james
andeson
henry
niols
kiyle

Original list of names
james
andeson
henry
niols
kiyle

Sorted list of names
andeson
henry
james
kiyle
niols

*/