Watching week 2 of the CS50 lectures (here: https://video.cs50.net/2016/fall/lectures/2?t=84m33s ) where he re-implements strlen
by running a while
loop over the characters of a string, with this loop (other code redacted):
string s = get_string();
int n = 0;
while (s[n] != '\0')
{
n++;
}
printf("%i",n);
My question is: can the above be stated in a for
loop?
I attempted to create one, but because of the way the for
loop is formatted, it seems to force output after each iteration, different from the while
loop that allows for one output of the loop, once a specific condition is met.
I'm curious as to whether a for
loop can achieve the same "one-time, conditional" output in a case such as this. If I recall correctly, while
is unique to C lang and others such as Python have for
loops exclusively (tell me if I'm wrong!).
The same can be written using a for loop. For example
string s = get_string();
int n = 0;
for ( ; s[n] != '\0'; n++ );
printf("%i",n);
However this for loop with an empty sub-statement can confuse the reader of the code even if it is written something like
for ( ; s[n] != '\0'; n++ ) /* empty body */;
or
for ( ; s[n] != '\0'; n++ ) { / *empty body */ }
Usually the same thing can be done in various ways. You should select a more expressive construction. For this task it is better to use the while loop.
Take into account that it would be more correctly to use type size_t
instead of the type int
for the variable n
.
For example
string s = get_string();
size_t n = 0;
for ( ; s[n] != '\0'; n++ );
printf("%zu",n);
This code will also work in this case:
int n=0;
for(;s[n];n++);
printf("%d ",n);
how this works:
String elements has ASCII values, so till the string has characters in it, condition part of for loop is true. As it reaches to end of string ie '\\0' (the integer value of '\\0' is zero), condition fails, loop exits.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.