VOOZH about

URL: https://www.geeksforgeeks.org/c/how-to-write-your-own-printf-in-c/

⇱ How to Write Your Own printf() in C? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Write Your Own printf() in C?

Last Updated : 23 Jul, 2025

In this article, we will learn how to implement your own custom printf() function in C language.

The printf() function is present in <stdio.h> header and uses a const char* and variable length arguments as its parameters. Hence we would be using <stdarg.h> header file which provides operations available on variable arguments passed to a function.

Prerequisites:Variadic Functions in C, Strings in C

Problem Statement: Write your own printf() function in C

Example Outputs:

Code 1: myprintf("Hello world %i",404);
Output: Hello world 404.
Code 2: char s[]="Multiverse is real";
myprintf("%s Hello %.3f",s,2.3);
Output: Multiverse is real Hello 2.30

Algorithm:

  1. Create a function int myprintf() with const char* and '...' as its parameters. ('. . .' enables the function to receive any number of arguments).
  2. Initialize a pointer of type va_list to work with variable arguments. Pass the pointer to va_start.
  3. Process the passed string with a delimiter as '%' or '\0', and store it in a token string.
  4. For every token starting with '%' check if its next characters are a format specifier defined in C. It can be 'i','s','lf'.
  5. Pass the token string and value retrieved from va_arg() to fprintf() in order to print the required value to the console.
  6. Once the whole string is processed, end the va_arg pointer.
  7. Return 0.

Code:


Output
Integer: 10
String: GeeksforGeeks
Float: 12.25

Time Complexity:

The time complexity of the above code is: O(n * L), where,

  • n: length of format specifier. For example, If %0.5f then n=3.
  • L: Length of the output.

In most practical cases, the time complexity is O(1).

Must Read - printf() in C

Comment