I am just starting to lean C so I don't know it very well. The program we are given tells us to write an Insertion Sort program that takes 20 strings seperated by space and sorts then alphabetically and prints them out in order. This is confusing me greatly since C doesn't have a String data type (at least to my knowledge). Aren't Strings just character arrays? Here is what I got:
#include <stdio.h>
#include <string.h>
#define MAX_STRINGS 20
void InsertionSort(char list[]);
void main()
{
int index;
char strings[MAX_STRINGS];
/* Get input */
printf("Enter %s strings.\n", MAX_STRINGS);
for (index = 0; index < MAX_STRINGS; index++)
{
char tempString[100];
printf("Input string %d : ", index);
scanf("%s", &tempString[0]);
strings[index] = tempString;
}
InsertionSort(strings);
printf("\nThe input set, in alphabetical order:\n");
for (index = 0; index < MAX_STRINGS; index++)
{
printf("%s\n", strings[index]);
}
}
void InsertionSort(char list[])
{
int unsorted;
int sorted;
char unsortedItem;
for(unsorted = 1; unsorted < MAX_STRINGS; unsorted++)
{
unsortedItem = list[unsorted];
for (sorted = unsorted - 1; (sorted >= 0) && (list[sorted] > unsortedItem); sorted--)
{
list[sorted + 1] = list[sorted];
}
list[sorted + 1] = unsortedItem;
}
}
I am completely new to C and C syntax and I find it very confusing. This program is not working correctly. What it is doing is it allows me to enter 20 strings, but then nothing is sorted and it prints out nothing. Any idea on how to fix that? Also, is there any idea to how I can get it to where I type a single sentence and the each string is separated by white space? For example if I type, "I am learning how to program in C and right now I do not like it." that would give me 16 strings. "I", "am", "learning", etc. Thanks.