-
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
Code:
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
int i, j;
char str[30];
char temp;
clrscr();
printf("please enter a string: ");
gets(str);
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--)
printf("%c",str[i]);
getch();
}
-
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:
Code:
int len;
...
len = strlen();
for(j = 0; j < len; j++)
...
for(i = 0; i < len; i++)
--
Mats