+ 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; }

16th Oct 2020, 8:13 PM
saso yoo
saso yoo - avatar
7 odpowiedzi
+ 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).
17th Oct 2020, 2:08 AM
LastSecond959
LastSecond959 - avatar
+ 2
Jayakrishna🇮🇳 LastSecond959 BroFar Thanks guys now I get it Can this way work for integer arrays?
17th Oct 2020, 5:11 AM
saso yoo
saso yoo - avatar
+ 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.
16th Oct 2020, 8:49 PM
Jayakrishna 🇮🇳
+ 1
saso yoo The general concept works the same (ASCII treated as integers), but if you use toupper() for ints, that's useless lmao.
17th Oct 2020, 5:36 AM
LastSecond959
LastSecond959 - avatar
0
String termination char has a value of 0.
17th Oct 2020, 8:06 AM
Sonic
Sonic - avatar
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; }
17th Oct 2020, 8:39 AM
saso yoo
saso yoo - avatar