I could not understand loop testcondition understanding| rest program runs fine
-
#include
void main()
{char name[40];
printf("Enter the string:");
gets(name);
char ch = ' ';
int i,count=0;
for(i=0;name[i];i++)
{if(name[i]==' ')
count++;
}
printf("Number of words is %d",(count)+1);
} -
#include
void main()
{char name[40];
printf("Enter the string:");
gets(name);
char ch = ' ';
int i,count=0;
for(i=0;name[i];i++)
{if(name[i]==' ')
count++;
}
printf("Number of words is %d",(count)+1);
}This is something I hate, but it's idiomatic. A C string ends with the character NUL, whose ASCII value is 0, which is equivalent to
false
. So the loop ends when the character NUL (usually written as'\0'
) is encountered. The check is equivalent toname[i] != '\0'
but some people hate typing so much that they write this kind of thing.
Robust Services Core | Software Techniques for Lemmings | Articles
-
#include
void main()
{char name[40];
printf("Enter the string:");
gets(name);
char ch = ' ';
int i,count=0;
for(i=0;name[i];i++)
{if(name[i]==' ')
count++;
}
printf("Number of words is %d",(count)+1);
}The for statement breaks down as three individual expressions:
for(set; while; do) :
//
// set : perform this or these expressions first: multiple expressions must be separated by commas
// while : repeat the loop while this expression equates to true
// do : perform this or these expressions at the end of each loopNote that any of these expressions (or indeed all of them) may be blank. In your code the expression in the while part is
name[i]
, which meanswhile name[i] is true
, or ratherwhile name[i] is not equal to zero
. Strings in C are (or should be) terminated with a zero character (NULL), so the expression will be true as long as the character in question is not the terminating NULL.