Open In App

Newline in C

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

An escape sequence in C is a character or a sequence of characters that are used to represent characters that cannot be represented normally. One such character is the newline character that is represented by the newline ‘\n’ escape sequence.

In this article, we will discuss how the newline escape sequence is used to insert the newline in the string literal.

New Lines in C

In C language, the new line is a special character that is used to move the cursor at the start of the next line. It is represented as the ‘\n’ escape sequence and it can be used in string literals just like any other character. For example,

'\n'
"GeeksforGeeks\n"

When a newline is encountered in a string, the cursor moves to the next line at that point and the rest of the string is then printed.

Note: The ASCII code for newline is 10 (00001010).

Example

In this program, we will print two strings without using a newline or any other character in between. Let’s see the output:

C




// C Program to illustrate the output without newline
#include <stdio.h>
  
int main()
{
  
    // Print a string
    printf("hello ");
    printf("geek");
    return 0;
}


Output

hello geek

Now, we are going to use the ‘/n’ escape sequence to print the new line in the first printf() statement.

C




// C Program to illustrate the newline escape sequence
#include <stdio.h>
  
int main()
{
    // using newline at the end of first string
    printf("Hello \n");
    printf("Geek");
    return 0;
}


Output

Hello 
Geek

Explanation: In the above code inside the first string we have used “\n” new line escape sequence which moves the cursor or pointer to the next line and the second string is printed in the next line.

Conclusion

The newline character ‘\n’ is an escape sequence that is used to move the cursor to the next line. It may ineffective when defining the code but we can see its effect in text processing areas such as the output console, text files, etc.



Like Article
Suggest improvement
Share your thoughts in the comments