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()

</>
Copy
int puts(const char *str);

Parameters

ParameterDescription
strC 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

</>
Copy
#include <stdio.h>

int main() {
    // Print a simple string using puts()
    puts("Hello, World!");
    return 0;
}

Explanation:

  1. The program includes the stdio.h header which contains the declaration for puts().
  2. The puts() function is called with the string "Hello, World!" to print it to the standard output.
  3. 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

</>
Copy
#include <stdio.h>

int main() {
    // Print multiple lines using puts()
    puts("First line");
    puts("Second line");
    puts("Third line");
    return 0;
}

Explanation:

  1. The program prints three separate strings, each on its own line.
  2. Each call to puts() writes the string and appends a newline automatically.
  3. 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

</>
Copy
#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:

  1. A custom function printMessage() is defined to take a string and print it using puts().
  2. In the main() function, the printMessage() function is called with a sample message.
  3. This modular approach demonstrates how puts() can be integrated into user-defined functions for reusable code.

Program Output:

Custom function output using puts()