cwhile-loopiterationnull-character

Iterate through an array of characters in C


Recently I saw this while loop condition in C in the example below but I have no idea what the while condition really means and how the compiler knows when it is done. Could someone explain it to me?

This is what I believe it means: while loop iterates through the char array until the ending of the array since there is nothing else then the while loop ends, or am I wrong? I tried to use the same while loop but in another language such as Go, however, the compiler threw an error saying that I cannot use a non-bool.

// C program to demonstrate 
// example of tolower() function. 

#include <ctype.h> 
#include <stdio.h> 

int main() 
{ 
    int j = 0; 
    char str[] = "GEEKSFORGEEKS\n"; 

    // Character to be converted to lowercase 
    char ch = 'G'; 

    // convert ch to lowercase using toLower() 
    char ch; 

    while (str[j]) { // <- this part, how is this a condition?
        ch = str[j]; 

        // convert ch to lowercase using toLower() 
        putchar(tolower(ch)); 

        j++; 
    } 

    return 0; 
} 

Solution

  • the while loop can be understood as "while this string has characters" and as known in C strings or an array of chars contain a '\0' => Null character, in the end, once the while loop achieves it, it will stop the iteration.

    So yeap! you are right.