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
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
// Using printf() to print the string
printf("%s\n", str);
return 0;
}
Explanation:
- We declare a character array
str[]
and initialize it with"Hello, World!"
. - The
printf()
function is used with the%s
format specifier to print the string. - 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
#include <stdio.h>
int main() {
char str[] = "Welcome to C programming!";
// Using puts() to print the string
puts(str);
return 0;
}
Explanation:
- We declare a character array
str[]
and initialize it with"Welcome to C programming!"
. - The
puts()
function is used to print the string. - 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
#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:
- We declare a character array
str[]
and initialize it with"C Language"
. - We use a
while
loop to iterate through each character instr
until we reach the null character'\0'
. - Inside the loop, the
putchar()
function prints one character at a time. - 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:
printf()
: Used for formatted output with%s
.puts()
: Prints the string and automatically adds a newline.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.