+ 1
c language - question about while loop
how this loop know when to stop i dont understand the stop condition in this code #include <ctype.h> int main() { // counter for the loop int i = 0; // word to convert to uppercase char word[] = "edUcaTivE\n"; char chr; // Loop while (word[i]) { chr = word[i]; printf("%c", toupper(chr)); i++; } return 0; }
7 Answers
+ 7
saso yoo in short the while loop ends when it finds the end of the word as if \0 terminated the while loop
https://www.sololearn.com/discuss/1946398/?ref=app
https://www.sololearn.com/discuss/2111320/?ref=app
https://www.sololearn.com/discuss/1252328/?ref=app
https://www.sololearn.com/discuss/1936849/?ref=app
input any word in the code below.
https://code.sololearn.com/cYIKl9Q8xhG4/?ref=app
+ 3
So word is a string with the type of char array, each of characters have their own ASCII number, every assigned string (line 9) will be ended with a string terminator which is the character '\0', the character itself have the ASCII of 0 or NULL (as macro). Remember that in C/C++, any number other than 0 converted to boolean value will be "true", otherwise it's "false".
That's why in `while (word[i]) {...; i++}` it will traverse every single character in the string, i.e `while ('e')` i.e `while (101)` (101 is the ASCII of character e) which is not 0 so it's evaluated as while (true) (the condition is true because it's not 0), and then i++ so it's now `while ('d')` or `while (100)`. The loop will keep doing that, note that \n will be counted as 1 character, not '\' and 'n'. When it meets i = 10, it will be `while ('\0')` which is the same as while (0) or while (NULL) or while (false).
+ 2
Jayakrishnađźđł
LastSecond959
BroFar
Thanks guys now I get it
Can this way work for integer arrays?
+ 1
saso yoo
In c/c++, for in string initialization, the null charecter \0 will be automatically appended at end. So on reaching word[i] =='\0' it will terminate loop..
Edit :
"
0 is equivalent to '\0'
Yet 0 is not the same as '0'. "
Yes. But 0 cannot be added to string, if you add, then it will become '0'.
Additional info :
Check this string..
char word[] ="educate\n0educate\0educate";
This will print only
educate
0educate
It will not print 3rd time educate. On encounter '\0' it ends reading..
It's true 0 is equlent to \0 but
0 is Integer zero where as \0 is byte 0.
+ 1
saso yoo The general concept works the same (ASCII treated as integers), but if you use toupper() for ints, that's useless lmao.
0
String termination char has a value of 0.
0
i modified the code to try with int arrays
#include <stdio.h>
int main()
{
// counter for the loop
int i = 0;
int word[66] = {1,2,3,4,5,6};
int chr;
// Loop
while (word[i]) {
chr = word[i];
printf("%d", chr);
i++;
}
return 0;
}