using the NULL character

Need some help over here.

I suppose to create a main function that is used to invoke a function that displays the first character of a string on line 1, the first two characters on line 2 and so on until the whole string is displayed. The function takes in a parameter i.e. a char pointer. It handles the parameter as a C-style string i.e. a NULL terminated char array. It does not make use of the string class or its associated functions. In other words, the function examines every char element in the array until it encounters the terminating NULL character.

This is the main function:

int main() {
char string1[] = "Application of C++";
printPattern(string1);
}

How do i start to write the printPattern function?
You could use the C idiom for working with null-termianted arrays of using *p++ as a loop condition:

1
2
3
4
5
void printPattern(const char* beg)
{
    for(const char* end = beg; *end++; )
        std::cout.write(beg, end-beg) << '\n';
}

Last edited on
Thanks for your help! Got a question.

Is there any way of a simplify version of writing this below?

"std::cout.write(beg, end-beg) << '\n';"
> Is there any way of a simplify version of writing this below?

It's not any simpler, but this is another way: write another loop to print those characters one by one:

1
2
3
4
5
6
7
8
void printPattern(const char* beg)
{
    for(const char* end = beg; *end++; )
    {
        for( const char* p = beg ; p != end ; ++p ) std::cout << *p ;
        std::cout << '\n' ;
    }
}
Topic archived. No new replies allowed.