Search code examples
cstringpointersprintfsize

Why don’t we need for loop to print strings in C?


I don't understand Why don’t we have to print strings in for loop ? In normal cases we need to print arrays in for loop. For example, if we want to print the array of integers. It will be like this:

int a[n];

for (i = 0; i < n; i++){
    printf("%d", a[i]);
}

But for strings like:

char s[100] = " Hello ";
printf("%s\n", s);

it is enough to write the name of array. EDIT: It seems like I didnt ask my question properly as some of you wrote answers which is not related to my question.I edit my question.


Solution

  • Your example is far from analogous. %d refers to a single integer, while %s refers to an entire (but still single) string.

    You are not passing the size of the array n[] to printf either - rather you are calling printf n times. You are printing one int just as you are printing one string.

    The actual string length is not known a priori, rather printf iterates the string until it encounters the \0 terminator. Equivalent to:

    for( int i = 0; s[i] != '\0'; i++)
    {
        printf( "%c", s[i] ) ;
    }
    

    because

    char s[100] = " Hello ";
    

    is equivalent to:

    char s[100] = { ' ', 'H', 'e', 'l', 'l', 'o', ' ', '\0' } ;