Reputation: 395
#include<conio.h>
#include<stdio.h>
int main(void)
{
int i,j,temp;
char str[]="geeksforgeeks";
for(i=1;str[i];i++)
{
for(j=0;str[j]!='\0';j++)
{
if(str[j]>str[j+1])
{
temp=str[j];
str[j]=str[j+1];
str[j+1]=temp;
}
}
}
for(i=0;str[i]!='\0';i++)
{
printf("%c",str[i]);
}
}
I want it to be done without calculating the length of the string.As i know that the bug is in the condition statement of for loop then tell me what it should be?
Upvotes: 0
Views: 118
Reputation: 1126
As Weather Vane has pointed out already, error is at str[j]>str[j+1]
. This will switch the second last character with the NULL terminator (and thus cause you to miss your end condition for the for loop).
To fix this change the for loop end condition to str[j+1]!='\0'
and add a check at the beginning to make sure the first character in the array is not '\0'! I also suggest researching Bubble search because this code has a lot of extra iterations!
Upvotes: 1