Thread: Understanding String Functions

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    108

    Unhappy Understanding String Functions

    Hey everyone,

    I'm trying to practice strings and I need you're help.
    I tried to build a code by myself where i'm sorting my strings in lexicographic order but i had to peak at the solution .

    I have a few questions to ask because i really need to master that subject.

    so first here's the code:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main()
    {
        char names[100][50], temp[100][100];
        int num,i,j = 0;
        int k = 0;
        
        printf("Enter number of names: ");
        scanf("%d", &num);
        printf("Enter names:\n");
        
        for (i=0; i<num; i++)
        {
            scanf("%s", names[i]);
        }
        
        for (i=0; i<num; i++)
        {
            for (j=0; j<num-1; j++)
            {
                if (strcmp(names[j], names[j+1])>0)
                {
                    strcpy(temp[k], names[j]);
                    strcpy(names[j], names[j+1]);
                    strcpy(names[j+1], temp[k]);
                }
            }
        }
        
        for (i=0; i<num; i++)
        {
            printf("%s", names[i]);
        }
        
    }
    So here are my questions:
    1- on the for loops where i make my calculation of the strings. What does j represent?
    Correct me if i'm wrong:
    num = 3 (for example) and I'm inputting 'yann' so j[0] = yann, j[1] = ann j[2] = nn and j[3] = n ??

    2- why on the second for loop i have to declare j<num-1?

    3- can someone explain to me the if statement? what does strcmp(names[j], names[j+1]) mean? and why does it have to be >0??

    4- please explain to me the rest of the if statement.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    1. You should look up bubblesort.
    2. Ditto.
    3. You should look up strcmp.
    4. Do you mean the statements that are in the "true" part of the if statement? They just swap two words. You should look up bubblesort.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. understanding void functions
    By jtieu in forum C++ Programming
    Replies: 7
    Last Post: 03-02-2011, 12:01 PM
  2. Help understanding functions
    By nafix in forum C Programming
    Replies: 3
    Last Post: 10-13-2007, 07:18 PM
  3. Understanding functions
    By kryonik in forum C Programming
    Replies: 13
    Last Post: 08-31-2005, 05:04 PM
  4. FUNCTIONS....i need a better understanding
    By math in forum C++ Programming
    Replies: 4
    Last Post: 12-09-2001, 01:25 PM
  5. understanding functions
    By desperate in forum C Programming
    Replies: 8
    Last Post: 09-09-2001, 10:57 PM