This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Monday, March 13, 2023

Write a program with function printf() that takes string as argument and print that string on screen. Note that printf() is a user-defined function (not one defined under stdio.h header file of C library), so you have to write its definition yourself.

 Here is the code for the printf() function:

#include <iostream>
void printf(const char* str) {
    for(int i = 0; str[i] != '\0'; i++) {
        putchar(str[i]);
    }
}
int main() {
    printf("Hello, world!\n");
    printf("This is my custom printf function.\n");
    return 0;
}

In this program, we first define the printf() function, which takes a const char* argument named str. We then use a for loop to iterate over each character in the string pointed to by str, printing each character to the console using the putchar() function.

In the main() function, we call the printf() function twice with different strings as arguments. The output of this program will be:

Hello, world!
This is my custom printf function.

Note that while this function is similar to the printf() function in the standard library, it does not support formatting options, such as %d or %s, and should not be used as a replacement for the standard printf() function in production code.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget