%s and string

We can print the string using %s format specifier in printf function.

It will print the string from the given starting address to the null '\0' character.


String name itself the starting address of the string.

So, if we give string name it will print the entire string.




Printing string using %s format specifier

#include<stdio.h>

int main()
{
    char str[6] = "Hello";

    /*
     * it will print the string
     * from base address to null'\0'.
     */
    printf("%s",str);

    return 0;
}

What will be the output if we give str+1?

If we give str+1, the string address moved by 1 byte (which is the address of the second character)

So, it will print the string from the second character.

Similarly, if we give str+2, it will print the string from the third character.


Let's print the following pattern.

Hello

ello

llo

lo

o

Example

#include<stdio.h>

int main()
{
    char str[6] = "Hello";
    int i;

    /*
     * str+0 will print "Hello"
     * str+1 will print "ello"
     * str+2 will print "llo"
     * str+3 will print "lo"
     * str+4 will print "o"
     */
    for(i = 0; str[i]; i++)
        printf("%s\n",str+i);

    return 0;
}





Binary Dollar Question!

Write a program to print the following pattern.

o

lo

llo

ello

Hello