Nearby lessons

44 of 72

C - String Output

Learn how to display strings in C using printf(), puts(), and fputs(). Understand their basic differences through simple examples.

Displaying a String Using printf()

We can use printf() to display a string on the screen.

The %s format specifier is used to display a string.

Example01
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[] = "Rahul";
6 
7 printf("%s", name);
8 
9 return 0;
10}
Output
Rahul

Displaying Multiple Strings Using printf()

We can display multiple strings and messages using printf().

Use \n when you want to move the output to the next line.

Example02
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[] = "Rahul";
6 char city[] = "Ahmedabad";
7 
8 printf("Name: %s\n", name);
9 printf("City: %s\n", city);
10 
11 return 0;
12}
Output
Name: Rahul
City: Ahmedabad

Displaying a String Using puts()

The puts() function displays a string and automatically moves the cursor to the next line.

It is useful when we want to display a simple message.

Example03
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char message[] = "Welcome to C programming";
6 
7 puts(message);
8 puts("Keep learning!");
9 
10 return 0;
11}
Output
Welcome to C programming
Keep learning!

Displaying a String Using fputs()

The fputs() function displays a string on the specified output stream.

For screen output, we can use stdout. Unlike puts(), fputs() does not automatically add a newline.

Example04
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char first[] = "Hello ";
6 char second[] = "World!";
7 
8 fputs(first, stdout);
9 fputs(second, stdout);
10 fputs("\n", stdout);
11 
12 return 0;
13}
Output
Hello World!

Difference Between printf(), puts(), and fputs()

These functions can display strings, but they have some differences.

  • printf() supports format specifiers such as %s and %d.
  • puts() displays a string and automatically adds a newline.
  • fputs() displays a string without automatically adding a newline.

For beginners, use printf() when you need to display variables with labels, and use puts() for simple messages.

Example05
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[] = "Rahul";
6 
7 printf("Name: %s\n", name);
8 
9 puts("Welcome to C");
10 
11 fputs("Happy Learning!", stdout);
12 fputs("\n", stdout);
13 
14 return 0;
15}
Output
Name: Rahul
Welcome to C
Happy Learning!

Common Mistakes

  • Using %d instead of %s to display a string.
  • Expecting printf() to move to the next line without using \n.
  • Forgetting that puts() adds a newline automatically.
  • Expecting fputs() to add a newline automatically.
📝 Key Takeaways
  • printf("%s", name) displays a string.
  • The %s format specifier is used to display a string.
  • puts() automatically adds a newline after the string.
  • fputs() does not automatically add a newline.
  • Choose the output function according to your requirement.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3