Write a program to read two names and print them in alphabetic order.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <string.h>
#define MAX 100

int main(int argc, char ** argv) {
    char c, name1[MAX], name2[MAX];
    int i;
    printf("Enter name 1: ");
    for (i = 0; (c = getchar()) != '\n'; i++)
        name1[i] = c;
    name1[i] = '\0';

    printf("Enter name 2: ");
    for (i = 0; (c = getchar()) != '\n'; i++)
        name2[i] = c;
    name2[i] = '\0';

    if (strcmp(name1, name2) < 0) {
        printf("%s\n", name1);
        printf("%s\n", name2);
    } else {
        printf("%s\n", name2);
        printf("%s\n", name1);
    }
    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Enter name 1: Fokwa Divine
Enter name 2: Bob Stone
Bob Stone
Fokwa Divine

Brief Explanation

  • The program starts by requesting the user to enter two names which are read into arrays name1 and name2.
  • The function getchar returns the next input character each time it is called, or EOF when it encounters end of file. The symbolic constant EOF is defined in <stdio.h>.
  • A null byte \0 is appended to each name to terminate it. \0 is a string termination character and marks the end of the string of characters.
  • The function strcmp(name1, name2) compares the character strings name1 and name2, and returns negative, zero or positive if name1 is lexicographically less than, equal to, or greater than name2. The value is obtained by subtracting the characters at the first position where name1 and name2 disagree.
  • strcmp is a function in standard library string.h, an example implementation is like below:
/* strcmp: return 0 if name1>name2 */
int strcmp(char *name1, char *name2)
{
	int i;
	for (i = 0; name1[i] == name2[i]; i++)
		if (name1[i] == '\0')
			return 0;
	return name1[i] - name2[i];
}

Add comment


Security code
Refresh