Print a String in C

In C, we can print a string using functions like printf(), puts(), and character-by-character methods such as putchar(). Each function has its own advantages and use cases. In this tutorial, we will explore different ways to print a string in C with detailed explanations and examples.


Examples of Printing a String in C

1. Printing a String Using printf()

In this example, we will use the printf() function to print a string. This function is widely used in C for formatted output.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[] = "Hello, World!";

    // Using printf() to print the string
    printf("%s\n", str);

    return 0;
}

Explanation:

  1. We declare a character array str[] and initialize it with "Hello, World!".
  2. The printf() function is used with the %s format specifier to print the string.
  3. The \n ensures that the output moves to a new line after printing.

Output:

Hello, World!

2. Printing a String Using puts()

In this example, we will use the puts() function to print a string. Unlike printf(), puts() automatically adds a newline after printing.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[] = "Welcome to C programming!";

    // Using puts() to print the string
    puts(str);

    return 0;
}

Explanation:

  1. We declare a character array str[] and initialize it with "Welcome to C programming!".
  2. The puts() function is used to print the string.
  3. Unlike printf(), puts() automatically moves the cursor to a new line after printing.

Output:

Welcome to C programming!

3. Printing a String Character by Character Using putchar()

In this example, we will use the putchar() function inside a loop to print each character of the string individually.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[] = "Apple Banana";
    int i = 0;

    // Using putchar() to print characters one by one
    while (str[i] != '\0') {
        putchar(str[i]);
        i++;
    }
    putchar('\n'); // Move to new line

    return 0;
}

Explanation:

  1. We declare a character array str[] and initialize it with "C Language".
  2. We use a while loop to iterate through each character in str until we reach the null character '\0'.
  3. Inside the loop, the putchar() function prints one character at a time.
  4. After printing all characters, we call putchar('\n') to move to a new line.

Output:

Apple Banana

Conclusion

In this tutorial, we explored different methods to print a string in C:

  1. printf(): Used for formatted output with %s.
  2. puts(): Prints the string and automatically adds a newline.
  3. putchar(): Prints a string character by character inside a loop.

Each method serves different use cases, and understanding them helps in effective string manipulation in C.