Escape Sequences ๐ช#
Escape sequences are a special sequence of characters beginning with \
that represent a single character. They are often used to write out untypeable characters, such as new lines, tabs, or double-quotation marks inside of a string.
Hereโs a list of common escape sequences:
Escape Sequence |
Inserted Character |
Description |
|
Inserts a newline. |
This escape sequence is needed because you canโt just hit enter to get a newline โ that would break Cโs syntax. |
|
Inserts a tab. |
This escape sequence is needed because often you canโt just hit tab to get a tab character โ that would break Cโs syntax. |
|
Inserts a |
This escape sequence is needed when writing format strings, because format specifiers start with %. (ie. |
|
Inserts a |
This escape sequence is needed when writing the single-quote character, as characters are surrounded by single-quotes. (ie. โaโ, โbโ, โ\โโ) |
|
Inserts a |
This escape sequence is needed when using double-quotes inside of a string, because strings are surrounded by double-quotes. (ie. โThis is an \โapple\โ.โ); |
|
Inserts a |
This sequence is needed because the start of every escape sequence is a backslash. |
Ex.
// Escape characters are needed here because double quotes are
// already used to denote the start and end of a string.
printf("My name is \"Bob\"");
// Add a tab between "I am" and " spaced out!"
printf("I am \t spaced out!");
Tasks ๐ฏ#
Add a tab between โappleโ and โbananaโ in print statement for the code below.
You should get the output:
apple banana
#include <stdio.h>
int main() {
printf("apple banana");
}
Solution โ
#include <stdio.h> int main() { printf("apples\tbananas"); }
Add a newline between the two sentences that are printed in code below.
You should get the output:
Hello there!
The weather's looking fine today.
#include <stdio.h>
int main() {
printf("Hello there! The weather's looking fine today.");
}
Solution โ
#include <stdio.h> int main() { printf("Hello there!\nThe weather's looking fine today."); }