w3resource

C Exercises: Implement the printf() function


7. Variadic printf() Implementation Challenges

Write a C program to implement the printf() function using variadic functions.

Sample Solution:

C Code:

#include <stdio.h>

#include <stdarg.h>

void printValues(char * format, ...) {
  va_list argList;
  va_start(argList, format);

  printf("The values are: ");
  while ( * format != '\0') {
    if ( * format == 'd') {
      int val = va_arg(argList, int);
      printf("%d ", val);
    }
    format++;
  }
  printf("\n");
  va_end(argList);
}
int main() {
  int x = 10;
  int y = 20;
  int z = 30;
  printValues("ddd", x, y, z);
  return 0;
}

Sample Output:

The values are: 10 20 30

Explanation:

This above program defines the function printValues () that takes a string format and a variable number of arguments. Inside the function, we use the va_list, va_start(), va_arg(), and va_end() macros from the stdarg.h library to iterate over the variable arguments.

We then loop through each character in the format string and check if it is a % character. If it is, we use va_arg() to get the next argument as an integer and print it with printf(). If it is not a % character, we print it using printf().

Flowchart:

Flowchart: Implement the printf() function.

For more Practice: Solve these Related Problems:

  • Write a C program to implement a simplified version of printf() that supports %d and %s format specifiers using variadic functions.
  • Write a C program to create a custom printf() that handles %f conversions and prints floating-point numbers accurately.
  • Write a C program to implement a variadic function that mimics printf() by printing multiple integers separated by spaces.
  • Write a C program to develop a minimal printf()-like function using variadic arguments that supports a limited set of format specifiers with error checking.

Go to:


PREV : Variadic Average Function Challenges.
NEXT : Variadic Sorting Function Challenges.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.