Thread: Final project- Sorting words alphabetically

  1. #1
    Registered User
    Join Date
    Dec 2014
    Posts
    5

    Final project- Sorting words alphabetically

    Hey guys

    I posted a c file of what I have so far but I'm fresh off the boat with programming. I'm taking a intro c programming class and I just can't get the logic in this project. Can anyone tell me if I'm at least on the right track? lol

    I've tried searching for answers around the web but everyone is using syntax that We haven't been taught before in class yet. I understand that the string library is probably the most efficient way of doing this but is there a way without using that library? Like using if, for, while etc. instead?

    I've been told that using anything else other than the string syntax is far to complex but I think the more complex it is the more I will understand it, if that makes any sense lol. I guess I like to see the easy basic steps.

    Any help would greatly be appreciated.

    Thank you,
    Alvin Chang

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    I don't see any code. You will need to post your code and ask more specific questions if you need more specific help. Just make your best, honest attempt. Usually, we prefer you post your code directly in the thread, instead of as an attachment. Make sure you post your code in [code][/code] tags, that it's neatly formatted and indented, and that you paste as plain text.

    As for the other questions: It all can be done without the string library -- otherwise there could be no string library (it's just a bunch of functions that somebody else wrote, kind of like the ones you're writing, so obviously they didn't have any functions to use initially). Many of the string functions are actually fairly basic, so I wouldn't say it's "far too complex". Some basic loops and if/else should cover most of them.

  3. #3
    Registered User
    Join Date
    Dec 2014
    Posts
    5
    I could've swore I attached the file lol but oh well, but yea heres what I have so far and that's good news about it being able to be done without the string library.
    Basically what I'm trying to do is assign the letter to numbers and sort them that way, but im not sure if im doing it right.
    insert
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    int x,i;
    
    printf("How many words do you want alphabetized?\n");
        scanf("%d", &x);
    
    char Words[x];
    
    
    for (i=0; i<x; i++) {
        printf("\nEnter a word:");
            scanf ("\n%s" , Words[i]);
    }
    printf("\nThese are all the words:");
    for (i=0; i<x; i++) {
        printf ("\n%s" , Words[i]);
    }
    
    int A;
     for(A=1;A<=(x-1);A++){
                for(i=1;i<x;i++){
    a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10, k=11, l=12, m=13, n=14, o=15, p=16, q=17, r=18, s=19, t=20, u=21, v=22, w=23, x=24, y=25, z=26;
    
                    if(Words[i-1]<Words[i]);
                        {store=Words[i-1];
                        Words[i-1]=Words[i];
                        Words[i]=store;}
                }
    
    }
    
    printf("\nThese are all the words sorted alphabetically:");
    for (i=0; i<x; i++) {
        printf ("\n%s" , Words[i]);
    }
    
    printf("\n");
    
    
    
    
    }

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    I've tried searching for answers around the web but everyone is using syntax that We haven't been taught before in class yet.
    There's your first problem. If you're taking an introductory course, there is practically no value in looking for answers online. You need to read your notes, do the exercises, and understand the material - then attempt to write the assignments yourself. This is the only way you're going to learn how to program.

    Next, you need to make sure your code is neatly formatted. This includes consistent indentation, brace placement, and vertical spacing. This is closer to what your code should look like:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    int main()
    {
        int x,i;
     
        printf("How many words do you want alphabetized?\n");
        scanf("%d", &x);
     
        char Words[x];
     
        for (i=0; i<x; i++) {
            printf("\nEnter a word:");
            scanf ("\n%s" , Words[i]);
        }
    
        printf("\nThese are all the words:");
    
        for (i=0; i<x; i++) {
            printf ("\n%s" , Words[i]);
        }
     
        int A;
        
        for(A=1;A<=(x-1);A++){
            for(i=1;i<x;i++){
                a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10, k=11, l=12, m=13, n=14, o=15, p=16, q=17, r=18, s=19, t=20, u=21, v=22, w=23, x=24, y=25, z=26;
                if(Words[i-1]<Words[i]);
                {
                    store=Words[i-1];
                    Words[i-1]=Words[i];
                    Words[i]=store;
                }
            }
        }
     
        printf("\nThese are all the words sorted alphabetically:");
    
        for (i=0; i<x; i++) {
            printf ("\n%s" , Words[i]);
        }
     
        printf("\n");
    }
    Finally, you need to be clear about your problem. In this case, your code is riddled with errors and will not even compile. Let's go through it. Note I'll be referencing the line numbers in the neatened version I posted.

    • Line 11: A string is a character array terminated with '\0'. Therefore, "Words" can hold a single string. If you're looking to sort various strings, a single character array will not be enough. A two-dimensional array might better suit your purposes.
    • Line 15: You're trying to "scanf()" a string into a single character - this is wrong. Additionally, you don't need '\n' in the "scanf()" format string. "scanf()" is also not the best way of reading a string from the user (see the FAQ for a good way of getting a line of text from the user).
    • Line 21: You're trying to print a string from a single character - again, this is wrong.
    • Lines 26/27: I have no idea what you're trying to accomplish here.
    • Line 28: None of these variables exist. You're trying to assign numbers to random letters, not variables. That's not how C works.
    • Line 29: Here you're trying to sort separate characters, not strings. Also, you have a semi-colon after the "if()", which is a mistake. If the "if()" is true, that stray semi-colon acts as a "null statement" (i.e. nothing will happen), and the following code will always be executed (it's not part of the "if()", even though it looks like it is) - this is a fairly common mistake.
    • Lines 31/33: The variable "store" does not exist. Nor can a single variable hold a string - this would have to be an array to hold a string. And you cannot copy strings with =, you need to use the string copy function from "string.h"
    • Line 41: Again you're trying to print a string from a single character, which as stated before, is wrong.
    • Random note: It's more usual, when printing output, to put the newline at the end of the string instead of the beginning. Not only does this not require an extra "printf("\n");" afterwards, but it ensures the output buffer is flushed on the spot.


    All of this code shows the hallmark of guesswork and a lack of understanding of the basics. You need to revisit your notes and make sure you understand the basics, one step at a time.

    Additionally, your general approach to sorting (assigning letters to numbers and sorting as numbers) is strange and likely incorrect. But no matter what approach you choose, you cannot implement it in code if you do not understand the basics.

    Considering that this is a school assignment, it stands to reason you should have learned what is necessary to complete it.

    I'd suggest reading about arrays, multi-dimensional arrays, and strings. And don't try to just slap an assignment together - work with the concepts and try to gain an understanding, in little practice programs, before trying to apply it to your assignment.

    One last thing - it is never a good idea to try to write an entire program before you even compile anything. This usually leads to a list of warnings and errors that can be overwhelming. Instead, write a little bit of code to do one single thing (e.g. read a string from the user and print it out). Compile, fix warnings/errors, and test. When you're sure that works, add a bit more code, compile, test. Grow the program in small, gradual steps (see here: a development process). And make sure you plan your program out before writing it, so you have a blueprint to follow.

  5. #5
    Registered User
    Join Date
    Dec 2014
    Posts
    5
    Yea I have to agree that it does show guesswork and lack of understanding, but that's how its been the entire semester for me lol. I came to the forums as a last resort actually. I went over my notes and asked the professor questions but I still couldn't quite wrap my head around the logic behind this project. I've done a number sorter before this and I was told it was similar so I just tried to apply things from there to here. I get what your saying about the strings and about the string library is probably the easiest approach to this but the problem is, we haven't learned anything about that yet, so I rather not use syntax from their to be honest. I'm starting to believe this is impossible to do without the string library, everywhere I've gone has practically told me the same thing. Oh well though, I suppose I'll do what my professor advised me to do, "Do your best." I really appreciate the time you all have taken to help but it's probably just me. Programming just isn't my thing lol.

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by Alvin Chang View Post
    I'm starting to believe this is impossible to do without the string library, everywhere I've gone has practically told me the same thing. Oh well though, I suppose I'll do what my professor advised me to do, "Do your best." I really appreciate the time you all have taken to help but it's probably just me. Programming just isn't my thing lol.
    I told you, it's not impossible. Also, there's no way to know that "programming just isn't your thing" based on this class alone. I did horribly in my first programming class. I tried again a later, and something had just clicked. Programming became fun and easy. Don't give up.

    Matticus made several good points, more "general advice" than specific to your assignment. I will re-state for emphasis
    1. You must understand the problem yourself and be able to solve it, before you can program a computer to solve it. Plan it out with paper and pencil, work through a few small examples. You're going for broad, logical steps here, not C-specific things. For example "Compare the first letters of word1 and word2; if they're equal do X, if they're not, do Y". You can think of programming as language translation, from human thought to C.
    2. Take it in small steps. Solve each little problem (read a string, compare two strings, swap two strings) on it's own, then combine those pieces to make your final program.

    Doing those two together not only makes it easier for you to get a working program, it almost always results in a better-designed program that's easy to modify, expand, debug, etc.

    So, with that in mind, let's start with some basic tasks. We'll start with a fresh program
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        return EXIT_SUCCESS;
    }
    First things first, we have to be able to read user input. This will make it easy to test later, as we can enter our own strings from the command line, instead of needing to hard-code them in the source file and recompile/re-run every time.

    1. Write a function to read in the number of strings the user want's to input. Read in a number and print it to the screen to test
    Code:
    #define MAX_STRINGS 10  // allow at most 10 strings for now
    
    int getNumStringsFromUser(void)
    {
        // fill in here, return the number of strings the user wants
        // we'll add error checking later, just make sure you enter values 0 < num_strings <= MAX_STRINGS when testing
    }
    
    int main(void)
    {
        int num_strings;
    
        num_strings = getNumStringsFromUser();
        printf("You want to enter %d strings\n", num_strings);
    
        return EXIT_SUCCESS;
    }
    2. Write a function that reads a string from the user. Use the technique in our FAQ to read a whole line and removes any newline character: FAQ > Get a line of text from the user/keyboard (C) - Cprogramming.com. Read in two strings from the user and print them back to the screen as a test (some pseudo code in there b/c im lazy):
    Code:
    // keep all code from #1
    #define MAX_STRING_LENGTH 100  // allow strings up to 99 chars (the 100th char is the null terminator)
    
    void getStringFromUser(char *s, int maxlen)
    {
        // you fill in this part
    }
    
    int main(void)
    {
        char s1[MAX_STRING_LENGTH];
        char s2[MAX_STRING_LENGTH];
    
        print "Enter string 1: "
        getStringFromUser(s1, sizeof(s1));
        print "Enter string 2: "
        getStringFromUser(s2, sizeof(s2));
        print "Your first string was: " s1
        print "Your first string was: " s2
    
        return EXIT_SUCCESS;
    }
    3. Write a function to read in N strings. This will use a loop (a for loop is good) to read in strings, using the getStringFromUser function you just wrote. You will need to declare

    Start with those 3 steps, one at a time. Remember to compile and test often, and make sure to fix all warnings/errors. Post back here when you're done, or when you get stuck, and we'll help you.
    Last edited by anduril462; 12-11-2014 at 02:19 PM.

  7. #7
    Registered User
    Join Date
    Dec 2014
    Posts
    5
    AM i doing this right so far?
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    
    // allow at most 10 strings for now
    
    
    int getNumStringsFromUser(void)
    {
        // fill in here, return the number of strings the user wants
        // we'll add error checking later, just make sure you enter values 0 < num_strings <= MAX_STRINGS when testing
    
    
    int num_strings;
    
    
    printf("How many words do you want alphabetized?\n");
        scanf("%d", num_strings);
    
    
    
    
    }
    
    
    int main(void)
    {
        int num_strings;
    
    
        num_strings = getNumStringsFromUser();
        printf("\nYou want to enter %d strings\n", num_strings);
    
    
    
    
        return EXIT_SUCCESS;
    }

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Good start, but you need to return the number of strings entered from getNumStringFromUser. Oh, and you forgot to define a constant for NUM_STRINGS, but that's not technically needed yet.

    Also, please fix up your formatting/indentation. Keeping your code neat and orderly is very helpful. If it's hard to read, it's easy to make a mistake, and hard to find or fix it.

  9. #9
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Code:
    scanf("%d", num_strings);
    "scanf()" expects a pointer to the variable being read into.

  10. #10
    Registered User
    Join Date
    Dec 2014
    Posts
    5
    I pretty much couldn't figure out a way to not use the string library. I went researching on the c-programming forums and all I could find was people telling me to use the string library, so I figured I just take the time to learn it and apply it instead. Here are the videos I learned about strings. I also explained in detail what is going on in the comments of my code as well, so you can see I do understand the logic of what is happening. In the end, I finally got it to work.


    Thank you,
    Alvin Chang

    Code:
    #include<stdio.h>
    #include<string.h>
    
    
    int main() {
    
    
    int x;
    //Ask the user how words they want to sort
       printf("How many words do you want alphabetized?\n");
            scanf("%d", &x);
    
    
    //Creates a array where x is the amount of words they want and 100 is the max amount of letters of a string being used
    //Also creates a destination array t in order to copy onto
       char Words[x][100], t[100];
    
    
    int i, j;
    
    
    /*Based on the number of elements specified beforehand, it will loops x amount of times,
    asking the user to input their words */
       printf("\nEnter your words:\n");
       for (i = 0; i < x; i++)
          scanf("%s", Words[i]);
    
    
    //Prints the user's words on the screen
        printf("\nThese are all the words:");
            for (i=0; i<x; i++) {
                printf ("\n%s" , Words[i]);
                                }
    /*-This will loop x amount of times based on the user's input beforehand.
      -It will compare each string, letter by letter with the syntax strcmp.
      -I set a if statement to execute it the command if the value is greater than 0 because strcmp will output a
    positive number if the letter comes after a certain letter in the alphabet.
      -If the number comes out positive, it means the letter comes first in the alphabet, which is what we want, so executing
    the command is not needed.
      -1. The command is basically copying the letters of the words inputed first into the destination array t[100]
       2. Then it is taking the words inputed after and copying it in the place of the first words
       3. Lastly taking the words inputed first and placing it in the spot after.
       4. Essentially swapping the words. */
       for (i = 1; i < x; i++) {
          for (j = 1; j < x; j++) {
             if (strcmp(Words[j - 1], Words[j]) > 0) {
                strcpy(t, Words[j - 1]);
                strcpy(Words[j - 1], Words[j]);
                strcpy(Words[j], t);
                                                     }
                                  }
                               }
        printf("\n---------------------------------------------------\n");
    
    
    //Prints the user's words alphabetically on the screen
       printf("\nThese are your words in alphabetical order : ");
       for (i = 0; i < x; i++)
          printf("\n%s", Words[i]);
    
    
       getch();
                 }
    https://www.youtube.com/watch?v=KWTbRDEAakI
    https://www.youtube.com/watch?v=NEbctgLEm50

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting Alphabetically problem
    By Random8 in forum C Programming
    Replies: 7
    Last Post: 10-16-2011, 02:54 PM
  2. Sorting 3 arrays alphabetically
    By Nephilim in forum C Programming
    Replies: 31
    Last Post: 03-28-2011, 09:23 AM
  3. sorting alphabetically
    By ahming in forum C Programming
    Replies: 8
    Last Post: 05-26-2005, 10:34 AM
  4. Sorting Alphabetically
    By orgy230 in forum C Programming
    Replies: 1
    Last Post: 12-04-2004, 02:28 PM

Tags for this Thread