Escape Sequence

Let’s take a scenario where we need to print "Hello" in first line and "World" in the next line.

Example

Hello

World


Example

#include<stdio.h>

int main()
{
    printf("Hello");
    printf("World");

    return 0;
}

Do you think the above program will print our expected output? No, it will print HelloWorld in the same line as an output.

So, how to deal with it. This kind of situation we should go for the escape sequence.

To print a new line, we should use \n escape sequence.


Like below,


Example

#include<stdio.h>

int main()
{
    printf("Hello\nWorld");
    return 0;
}





What is escape sequence?

The sequence of character which has indirect meaning when it placed within double quotes.

It will optimize some the repetitive tasks while programming.

Example

While printing some statement, if you want to give horizontal tab (usually four spaces) in between every word like below,


Example

#include<stdio.h>

int main()
{
    printf("Happy    New    Year");
    return 0;
}

Here, we manually gave four space between each word. This can be achieved easily with \t escape sequence.

Like below,


Example

#include<stdio.h>

int main()
{
    printf("Happy\tNew\tYear");
    return 0;
}

Useful Escape Sequences

Escape sequence

Description

Example

Output

\n

New line

printf("Hello \n World");

Hello
World

\t

Horizontal tab

printf("Hello \t World");

Hello      World

\'

Single quote

printf("Hello \'World\' ");

Hello 'World'

\"

Double quote

printf("Hello \"World\" ");

Hello "World"

\\

Backslash

printf("Hello \\World");

Hello \World




Useful Resources

https://en.wikipedia.org/wiki/Escape_sequences_in_C

Topics You Might Like