Formatting
The obvious wrong thing with your code is the indentation (I don't know if it is because of the copy on CodeReview.SE).
Also, the lines breaks seem to be used randomly. They should be used to divide the different logical parts of your function/program.
You could use more spaces to make your code easier to go through.
Finally (but this is a tiny detail), you have loads of trailing whitespace making things a bit more painful to edit. You can easily remove them automatically.
Activate warnings in your compiler
It is usually a good idea to enable all warnings in your compiler and to take them into account. In your case, gcc
complains about the return value for main
.
Once this is fixed, your code looks like :
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("\n Enter a string");
scanf("%s",str);
int len = strlen(str);
int i,flag = 1;
for(i=0; i < len - 1; i++)
{
if (str[i+1] >= str[i])
continue;
else
{
flag = 0 ;
break;
}
}
if(flag == 0)
printf("\n String is not Abecedarian ");
else
printf("\n Is abecedarian");
return 0;
}
Logic
Your code seems OK but there is a way to improve how the logic is written. For instance, you could get rid of the continue
by rewriting the condition. The inside of the loop becomes :
if (str[i+1] < str[i])
{
flag = 0 ;
break;
}
In the same kind of spirit, I'd inverse the conditions for the printing as I find it easier to read something like :
if(abcdarian)
printf("\n Is abecedarian");
else
printf("\n String is not Abecedarian ");
More style
It is usually a good idea to try to move your variables in the smallest possible scope. In your case, using c99
, you can move i
into the for
loop : for(int i=0; i < len - 1; i++)
.
In the same kind of spirit, it could be a good idea to create a function to handle the logic currently in the loop. Then you'd be able to just call if (isAbecedarian(str))
.
About scanf
You'll find online a few problems with scanf
and details about what you should be doing like using fgets
.