puts() Function
The puts()
function in C stdio.h writes a string to the standard output and automatically appends a newline character at the end. It is a convenient way to print a string followed by a newline without manually adding the newline character.
Syntax of puts()
int puts(const char *str);
Parameters
Parameter | Description |
---|---|
str | C string to be printed. |
The puts()
function starts copying the string from the given address until it encounters the terminating null character ('\0'
), which is not copied to the output. Unlike fputs()
, it always writes to the standard output (stdout
) and appends a newline character automatically.
Return Value
On success, puts()
returns a non-negative value. On error, it returns EOF
and sets the error indicator (accessible via ferror()
).
Examples for puts()
Example 1: Basic Usage of puts()
This example demonstrates the simple usage of puts()
to print a string followed by a newline.
Program
#include <stdio.h>
int main() {
// Print a simple string using puts()
puts("Hello, World!");
return 0;
}
Explanation:
- The program includes the
stdio.h
header which contains the declaration forputs()
. - The
puts()
function is called with the string"Hello, World!"
to print it to the standard output. - A newline is automatically appended after the string is printed.
Program Output:
Hello, World!
Example 2: Printing Multiple Lines Using puts()
This example demonstrates how puts()
can be used to print multiple lines of text by calling the function repeatedly.
Program
#include <stdio.h>
int main() {
// Print multiple lines using puts()
puts("First line");
puts("Second line");
puts("Third line");
return 0;
}
Explanation:
- The program prints three separate strings, each on its own line.
- Each call to
puts()
writes the string and appends a newline automatically. - This approach simplifies printing multiple lines without needing to include newline characters in the strings.
Program Output:
First line
Second line
Third line
Example 3: Using puts() within a Function
This example demonstrates the use of puts()
within a custom function to encapsulate string printing functionality.
Program
#include <stdio.h>
void printMessage(const char *message) {
// Print the message using puts()
puts(message);
}
int main() {
// Call the custom function to print a message
printMessage("Custom function output using puts()");
return 0;
}
Explanation:
- A custom function
printMessage()
is defined to take a string and print it usingputs()
. - In the
main()
function, theprintMessage()
function is called with a sample message. - This modular approach demonstrates how
puts()
can be integrated into user-defined functions for reusable code.
Program Output:
Custom function output using puts()