VOOZH about

URL: https://www.geeksforgeeks.org/cpp/print-last-10-lines-of-a-given-file/

⇱ Program to print last 10 lines - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to print last 10 lines

Last Updated : 23 Jul, 2025

Given some text lines in one string, each line is separated by ā€˜\n’ character. Print the last ten lines. If number of lines is less than 10, then print all lines. Source: Microsoft Interview | Set 10 Following are the steps 

1) Find the last occurrence of DELIM or '\n' 

2) Initialize target position as last occurrence of '\n' and count as 0 , and do following while count < 10

2.a) Find the next instance of '\n' and update target position

2.b) Skip '\n' and increment count of '\n' and update target position 3) Print the sub-string from target position. 

Output:

str16
str17
str18
str19
str20
str21
str22
str23
str24
str25
-----------------
str1
str2
str3
str4
str5
str6
str7
-----------------

-----------------
ERROR: string doesn't contain '\n' character
-----------------

Time Complexity: O(n)

Auxiliary Space: O(1)

Note: Above program can be modified to print last N lines by passing N instead of 10. N can store any integer value. This article is compiled by Narendra Kangralkar.

Comment
Article Tags:
Article Tags: