The program sorts numbers in ascending order. If the user enters a "-r" in the command line, the program sorts the numbers in descending order.

The problem I'm having is that I can't get the **** program to read the if/else condition correctly. Maybe something wrong with my syntax? :evil:

#include <stdio.h>

#define SIZE 100
#define FLAG "-r"

void sort_asc(int *);
void sort_des(int *);
void prn_list(int *, char *);

int i, j, temp;
int main(int argc, char *argv[])
{
	int list[] = {90, 70, 50, 60, 30, 100, 80};

	if (argv[1] == FLAG)
		sort_des(list);
	else
		sort_asc(list);

	return 0;
}

void sort_asc(int *list)
{
	char state[] = {"ascending"};

	for (i = 0; i < 7; i++)
		for (j = i + 1; j < 7; j++)
			if (list[i] < list[j])
			{
				temp = list[i];
				list[i] = list[j];
				list[j] = temp;
			}

	prn_list(list, state);

}

void sort_des(int *list)
{
	char state[] = {"descending"};

	for (i = 0; i < 7; i++)
		for (j = i + 1; j < 7; j++)
			if (list[i] > list[j])
			{
				temp = list[i];
				list[i] = list[j];
				list[j] = temp;
			}

	prn_list(list, state);
}

void prn_list(int *list, char *state)
{
	int cnt;

	printf("Your list in %s order:\n", state);

	for (cnt = 0; cnt < 7; cnt++)
		printf("%d\n", list[cnt]);
}

You compare the contents of two strings with the strcmp function in the <string.h> header. What you're actually doing with the == operator is comparing two memory addresses. Since the two strings are extremely unlikely to be located at the same address, your comparison will fail and the sort will always be in ascending order.

Include <string.h> and change this:

if (argv[1] == FLAG)

to this:

if (strcmp(argv[1], FLAG) == 0)
This article has been dead for over six months. Start a new discussion instead.