Thread: Arrange letters of the string alphabetically

  1. #16
    Registered User
    Join Date
    Mar 2008
    finally I did it.. wheew im starting to love this programming thing.. maybe I should take on this... 2 days of learning this stuff... and I come up with this

    void main()
       int i, j;     
       char str[30]; 
       char temp;    
       printf("please enter a string: ");
       for(j = 0; j < strlen(str); j++)
          for(i = 0; i < strlen(str); i++)
    	 if(str[i] < str[i+1])
    	    temp = str[i+1];
    	    str[i+1] = str[i];
    	    str[i] = temp;
       printf("\noutput: ");
       for(i = strlen(str); i >= 0; i--)

  2. #17
    Kernel hacker
    Join Date
    Jul 2007
    Farncombe, Surrey, England
    clrscr() is very much non-portable, and gets() is a BAD function to use, but otherwise it looks ok to me.

    It's not very good to use strlen() in loops that modify the string, as strlen is direcetly proportional to the length of the string, and thus can take quite some time to execute if the string is long [if the string is not being modified inside the loop the compiler can optimize out calling strlen for every loop iteration, but in your case, if the string is 29 characters long, it iterates 29 times in each of the two loops, calling strlen() 841 (29 * 29 = 841) times - and if the string is 100 long it would take 3x longer to do strlen, and it would be done 10000 (100 * 100 = 10000) times, and a string of 1000 characters would be calling strlen a million times, each taking ten times longer than the 100 character strlen call].

    In your code, you could do:
    int len;
    len = strlen(); 
    for(j = 0; j < len; j++)
    for(i = 0; i < len; i++)

    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  3. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 01:45 PM
Website Security Test