Print Your Own Name
Display name entered by user
This program demonstrates how to take user input using scanf()and display it back using printf(). It is one of the first programs that teaches you how to interact with users.
📚 What You Will Learn
- •How to declare a character array (string) in C
- •Using
scanf()to read user input - •Using format specifiers (
%s) with printf and scanf
C Program to Print Your Name
1#include <stdio.h>23int main() {4 // Declare a character array to store name5 char name[50];6 7 // Prompt user for input8 printf("Enter your name: ");9 10 // Read the name from user11 scanf("%49s", name);12 13 // Display greeting with the name14 printf("Hello, %s! Welcome to C programming.\n", name);15 16 return 0;17}Enter your name: John
Hello, John! Welcome to C programming.
Detailed Code Explanation
char name[50];Declares a character array (string) that can hold up to 49 characters plus a null terminator.
Why 50 but only 49 characters?
In C, strings end with a special character \\0 (null terminator). So a char[50] array can store 49 characters + 1 null character.
scanf("%49s", name);Reads a string from the user and stores it in the name array.
scanf() Function Signature:
int scanf(const char *format, ...);- • format: Format string with specifiers like %s, %d, %f
- • ...: Addresses where to store the input values
- • Returns: Number of items successfully read
| Part | Meaning |
|---|---|
| %s | Format specifier for string |
| %49s | Read max 49 characters (prevents buffer overflow) |
| name | No & needed - array name is already a pointer |
printf("Hello, %s!", name);The %s is replaced by the string stored in name.
Step-by-Step Execution:
Memory is allocated for 50 characters to store the name
printf shows "Enter your name: " on screen
scanf pauses program and waits for user to type
When user presses Enter, text is stored in name array
printf replaces %s with the name and prints greeting
Reading Full Name with Spaces
Limitation: scanf("%s") stops reading at whitespace. For names like "John Doe", use fgets() instead:
1#include <stdio.h>23int main() {4 char name[50];5 6 printf("Enter your full name: ");7 fgets(name, sizeof(name), stdin);8 9 printf("Hello, %s", name);10 return 0;11}Enter your full name: John Doe
Hello, John Doe
⚠️ Common Mistakes to Avoid
- • Using & with arrays:
scanf("%s", &name)❌ - arrays are already addresses - • No size limit:
scanf("%s", name)can cause buffer overflow - • Forgetting null terminator space: char[10] holds only 9 characters + \\0
📝 Key Takeaways
char array[] to store stringsscanf() reads formatted input%s is for stringsRelated Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials