On this page (14 sections)
- 🎯 Why This Matters
- 1️⃣ What Exactly Is a String?
- 2️⃣ Declaring and Initializing a String
- 3️⃣ Accessing Individual Characters
- 4️⃣ Reading and Printing Strings
- 5️⃣ Traversing a String
- 6️⃣ Reversing a String and Palindromes
- 7️⃣ Copying and Joining Strings by Hand
- 8️⃣ The Library Functions in string.h
- 9️⃣ Arrays of Strings
- 🚫 Common Mistakes
- 🎓 Practice Exercises
- ❓ Frequently Asked Questions
- ✅ Key Takeaways
Module II · Arrays and Strings · Strings (Character Arrays)
🎯 Why This Matters
So far our arrays held numbers. But a program that only handles numbers is very limited. Names, passwords, addresses, messages and file names are all text, and C stores text in a special kind of array called a string.
Unlike many other languages, C has no separate string type. A string in C is simply an array of char whose last element is a special marker, the null character '\0'. Once you understand that one idea, everything else in this post (reading, printing, reversing, comparing, copying) is just a loop over an array, which you already know how to write.
1️⃣ What Exactly Is a String?
A string is a sequence of characters stored in consecutive memory boxes, followed by a '\0'. The '\0' (called the null terminator) has the ASCII value 0. It tells every C function, “the text ends here”.
Figure 1: The string “Hello” occupies 6 boxes: 5 characters plus the null terminator.
Notice three things in this picture:
- The word
Hellohas 5 characters, but the array needs 6 boxes. The extra box holds'\0'. - Every character is really stored as a small number, its ASCII code.
'H'is 72,'e'is 101 and so on. - The
'\0'is not printed on the screen, but it is always there. Without it, C would not know where the text stops.
💡 Remember:'0' (the digit zero character, ASCII 48) and '\0' (the null character, ASCII 0) are two completely different things.
2️⃣ Declaring and Initializing a String
The general form of a declaration is:
char name[size];
where size must be large enough to hold all the characters plus one extra box for the '\0'. There are several ways to give a string its initial value.
Example 1: The Simplest Way
#include <stdio.h>
int main() {
char name[] = "Ajay";
printf("Hello, %s!\n", name);
return 0;
}
🖥️ Output:
Hello, Ajay!
Writing char name[] = "Ajay"; is the most convenient form. The compiler counts the characters (4), adds the '\0' and makes the array of size 5 for you. The %s format specifier prints a whole string, from the first character up to (but not including) the '\0'.
Example 2: Three Ways to Initialize
#include <stdio.h>
int main() {
char a[] = {'C', 'a', 't', '\0'}; // character by character
char b[] = "Cat"; // string literal (size found automatically)
char c[10] = "Cat"; // extra room, rest filled with \0
printf("a = %s, size = %d\n", a, (int) sizeof(a));
printf("b = %s, size = %d\n", b, (int) sizeof(b));
printf("c = %s, size = %d\n", c, (int) sizeof(c));
return 0;
}
🖥️ Output:
a = Cat, size = 4
b = Cat, size = 4
c = Cat, size = 10
alists each character one by one. Here you must write the'\0'yourself.buses a string literal in double quotes. The compiler adds the'\0'automatically.casks for 10 boxes."Cat"fills the first 4 and the remaining 6 are automatically set to'\0'.
Example 3: Length of a String vs Size of the Array
These two ideas are often confused. strlen() (from <string.h>) counts the characters before the '\0'. sizeof tells how many bytes the array occupies in total.
#include <stdio.h>
#include <string.h>
int main() {
char s[20] = "Programming";
printf("Characters in the string : %d\n", (int) strlen(s));
printf("Size of the array : %d bytes\n", (int) sizeof(s));
return 0;
}
🖥️ Output:
Characters in the string : 11
Size of the array : 20 bytes
“Programming” has 11 letters, so strlen gives 11. But we asked for a 20-byte array, so sizeof gives 20. The extra boxes are simply unused.
Single Quotes vs Double Quotes
This is the most common beginner confusion. Single quotes make one character. Double quotes make a string, which silently includes the '\0'.
Figure 2: ‘A’ is one byte, while “A” is two bytes.
#include <stdio.h>
int main() {
char ch = 'A'; // one character, 1 byte
char str[] = "A"; // a string, 2 bytes: 'A' and '\0'
printf("sizeof(ch) = %d\n", (int) sizeof(ch));
printf("sizeof(str) = %d\n", (int) sizeof(str));
return 0;
}
🖥️ Output:
sizeof(ch) = 1
sizeof(str) = 2
⚠️ Rule: Use 'A' with a char variable, and "A" for a string. Writing char c = "A"; is an error.
How Big Should the Array Be?
| Declaration | Characters | Array size | Verdict |
|---|---|---|---|
char s[] = "Hello"; | 5 | 6 (automatic) | ✅ Best choice |
char s[6] = "Hello"; | 5 | 6 | ✅ Exactly enough |
char s[20] = "Hello"; | 5 | 20 | ✅ Room to grow |
char s[5] = "Hello"; | 5 | 5 | ❌ No room for '\0' |
3️⃣ Accessing Individual Characters
Because a string is an array, each character has an index starting from 0. So s[0] is the first character, s[1] the second, and so on.
Example 4: Looking Inside “Hello”
#include <stdio.h>
int main() {
char s[] = "Hello";
for (int i = 0; i < 6; i++) {
printf("s[%d] = '%c' ASCII = %d\n", i, s[i], s[i]);
}
return 0;
}
🖥️ Output:
s[0] = ‘H’ ASCII = 72
s[1] = ‘e’ ASCII = 101
s[2] = ‘l’ ASCII = 108
s[3] = ‘l’ ASCII = 108
s[4] = ‘o’ ASCII = 111
s[5] = ” ASCII = 0
The loop goes up to index 5 on purpose, so that you can see the '\0'. Its ASCII value is 0, and since it is not a printable character, nothing appears between the quotes on the last line. In real programs we never hard-code the length like this. We stop the loop when we meet '\0', as you will see in Section 5.
4️⃣ Reading and Printing Strings
There are several ways to get a string from the keyboard, and each behaves differently. Understanding the differences will save you from many bugs.
Example 5: Reading a Word with scanf
#include <stdio.h>
int main() {
char name[30];
printf("Enter your name: ");
scanf("%s", name); // no & needed for an array
printf("Hello, %s!\n", name);
return 0;
}
🖥️ Output:
Enter your name: Asha
Hello, Asha!
Notice that we wrote name and not &name. For an array, the name itself already stands for the address of the first element, so the & is not needed. scanf also adds the '\0' automatically.
Example 6: The Space Problem
What if the user types two words?
#include <stdio.h>
int main() {
char name[30];
printf("Enter your full name: ");
scanf("%s", name);
printf("You entered: %s\n", name);
return 0;
}
🖥️ Output:
Enter your full name: Asha Kumar
You entered: Asha
Only Asha was stored! scanf("%s") stops reading at the first space, tab or newline. The word Kumar is left waiting in the input buffer.
Figure 3: scanf stops at the space, while fgets reads the whole line.
Example 7: Reading Several Words with scanf
If you know there will be two words, you can read them into two separate strings.
#include <stdio.h>
int main() {
char first[20], last[20];
printf("Enter first and last name: ");
scanf("%s %s", first, last);
printf("First = %s\n", first);
printf("Last = %s\n", last);
return 0;
}
🖥️ Output:
Enter first and last name: Asha Kumar
First = Asha
Last = Kumar
Example 8: Reading a Whole Line with fgets
To read a full line including spaces, use fgets(array, size, stdin). The second argument is the maximum number of boxes it may fill, which protects your array from overflowing.
#include <stdio.h>
int main() {
char line[50];
printf("Enter your full name: ");
fgets(line, 50, stdin); // reads up to 49 characters, or until Enter
printf("You entered: %s", line);
return 0;
}
🖥️ Output:
Enter your full name: Asha Kumar
You entered: Asha Kumar
fgets also stores the Enter key ('\n') at the end of the string if there is room. In the program above, that is why we wrote "%s" without a \n: the newline is already inside the string.
Example 9: Removing the Newline from fgets
Usually we do not want that trailing '\n'. We can find it and overwrite it with '\0'. The helper strcspn(line, "\n") returns the index of the first '\n'.
#include <stdio.h>
#include <string.h>
int main() {
char line[50];
printf("Enter your full name: ");
fgets(line, 50, stdin);
line[strcspn(line, "\n")] = '\0'; // replace the newline with \0
printf("Hello, [%s]\n", line);
printf("Length = %d\n", (int) strlen(line));
return 0;
}
🖥️ Output:
Enter your full name: Asha Kumar
Hello, [Asha Kumar]
Length = 10
Now the brackets hug the text tightly, and the length is exactly 10 (Asha Kumar is 4 + 1 + 5 characters).
Example 10: Another Way, the Scanset %[^\n]
%[^\n] means “read every character except a newline”. It is a handy trick when you want to use scanf but still read spaces.
#include <stdio.h>
int main() {
char city[40];
printf("Enter a city: ");
scanf("%[^\n]", city); // read everything up to the Enter key
printf("City = %s\n", city);
return 0;
}
🖥️ Output:
Enter a city: New Delhi
City = New Delhi
Example 11: Printing with puts and putchar
puts(s) prints a string and moves to the next line automatically. putchar(c) prints a single character.
#include <stdio.h>
int main() {
char s[] = "Learning C is fun";
puts(s); // prints the string and adds a newline
putchar(s[0]); // prints a single character
putchar('\n');
return 0;
}
🖥️ Output:
Learning C is fun
L
Which Input Method Should I Use?
| Method | Reads spaces? | Stores '\n'? | Safe against overflow? | Best for |
|---|---|---|---|---|
scanf("%s", s) | No (stops at space) | No | No (unless you add a width) | A single word |
scanf("%[^\n]", s) | Yes | No | No | A quick full line |
fgets(s, n, stdin) | Yes | Yes | Yes | A full line (recommended) |
gets(s) | Yes | No | Never | ❌ Removed from modern C. Never use it. |
5️⃣ Traversing a String
This is the single most important pattern in this post. We do not know how long a string is in advance, so we simply walk through it until we reach the '\0':
for (int i = 0; s[i] != '\0'; i++) {
// work with s[i]
}
Almost every string problem is a variation of this loop.
Example 12: Finding the Length Without strlen
#include <stdio.h>
int main() {
char s[] = "Computer";
int i = 0;
while (s[i] != '\0') {
i++;
}
printf("Length of \"%s\" = %d\n", s, i);
return 0;
}
🖥️ Output:
Length of “Computer” = 8
🔍 Trace:
i = 0 → s[0] = ‘C’ → not ‘\0’ → i = 1
i = 1 → s[1] = ‘o’ → i = 2 … and so on …
i = 8 → s[8] = ‘\0’ → loop stops, so the length is 8
Example 13: Length of a Line Typed by the User
When we use fgets, the string may end with '\n', so we stop at either one.
#include <stdio.h>
int main() {
char s[100];
int len = 0;
printf("Enter a string: ");
fgets(s, 100, stdin);
for (int i = 0; s[i] != '\0' && s[i] != '\n'; i++) {
len++;
}
printf("Length = %d\n", len);
return 0;
}
🖥️ Output:
Enter a string: Hello World
Length = 11
Example 14: Counting Vowels
#include <stdio.h>
int main() {
char s[] = "Programming in C";
int vowels = 0;
for (int i = 0; s[i] != '\0'; i++) {
char ch = s[i];
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
vowels++;
}
}
printf("Vowels = %d\n", vowels);
return 0;
}
🖥️ Output:
Vowels = 4
The characters are P-r-o-g-r-a-m-m-i-n-g, i-n and C. The vowels are o, a, i and i, which makes 4.
Example 15: Classifying Every Character
Characters are just numbers, so we can compare them with >= and <=. In ASCII, all uppercase letters sit together (65 to 90), all lowercase letters together (97 to 122) and all digits together (48 to 57).
#include <stdio.h>
int main() {
char s[] = "Room 101, Block C";
int upper = 0, lower = 0, digit = 0, space = 0, other = 0;
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] >= 'A' && s[i] <= 'Z') upper++;
else if (s[i] >= 'a' && s[i] <= 'z') lower++;
else if (s[i] >= '0' && s[i] <= '9') digit++;
else if (s[i] == ' ') space++;
else other++;
}
printf("Uppercase : %d\n", upper);
printf("Lowercase : %d\n", lower);
printf("Digits : %d\n", digit);
printf("Spaces : %d\n", space);
printf("Others : %d\n", other);
return 0;
}
🖥️ Output:
Uppercase : 3
Lowercase : 7
Digits : 3
Spaces : 3
Others : 1
Example 16: Converting to Uppercase Manually
The difference between a lowercase letter and its uppercase twin is always 32 ('a' = 97, 'A' = 65). So subtracting 32 converts it.
#include <stdio.h>
int main() {
char s[] = "hello world";
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] >= 'a' && s[i] <= 'z') {
s[i] = s[i] - 32; // 'a' is 97, 'A' is 65, difference is 32
}
}
printf("Uppercase: %s\n", s);
return 0;
}
🖥️ Output:
Uppercase: HELLO WORLD
Example 17: Toggling Case with ctype.h
The header <ctype.h> gives ready-made helpers: isupper(), islower(), toupper() and tolower(). Digits and spaces are left alone.
#include <stdio.h>
#include <ctype.h>
int main() {
char s[] = "Hello World 2026";
for (int i = 0; s[i] != '\0'; i++) {
if (isupper(s[i])) s[i] = tolower(s[i]);
else if (islower(s[i])) s[i] = toupper(s[i]);
}
printf("Toggled: %s\n", s);
return 0;
}
🖥️ Output:
Toggled: hELLO wORLD 2026
Example 18: Counting How Often a Character Appears
#include <stdio.h>
int main() {
char s[] = "banana";
char target = 'a';
int count = 0;
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] == target) {
count++;
}
}
printf("'%c' appears %d times in \"%s\"\n", target, count, s);
return 0;
}
🖥️ Output:
‘a’ appears 3 times in “banana”
Example 19: Counting Words
Words are separated by spaces, so a string with n spaces (single spaces only) has n + 1 words.
#include <stdio.h>
int main() {
char s[] = "C is a powerful language";
int words = 1;
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] == ' ') {
words++;
}
}
printf("Words = %d\n", words);
return 0;
}
🖥️ Output:
Words = 5
Example 20: Sum of the Digits in a String
To turn the character '7' into the number 7, subtract '0'. This works because digits are stored in order: '0' = 48, '1' = 49 and so on, so '7' - '0' = 55 − 48 = 7.
#include <stdio.h>
int main() {
char s[] = "A1B22C333";
int sum = 0;
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] >= '0' && s[i] <= '9') {
sum = sum + (s[i] - '0'); // '7' - '0' gives the number 7
}
}
printf("Sum of digits = %d\n", sum);
return 0;
}
🖥️ Output:
Sum of digits = 14
6️⃣ Reversing a String and Palindromes
Example 21: Printing a String Backwards
The easy way: run the loop from the last character down to the first, without changing the string.
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Programming";
printf("Backwards: ");
for (int i = strlen(s) - 1; i >= 0; i--) {
printf("%c", s[i]);
}
printf("\n");
return 0;
}
🖥️ Output:
Backwards: gnimmargorP
Example 22: Reversing a String in Place
Here we actually change the array. We keep one index i at the start and another j at the end, swap the two characters, then move both inward until they meet.
Figure 4: Reversing in place. Swap the ends, then move both indexes toward the middle.
#include <stdio.h>
int main() {
char s[] = "Hello";
int len = 0;
while (s[len] != '\0') {
len++;
}
int i = 0, j = len - 1;
while (i < j) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
printf("Reversed: %s\n", s);
return 0;
}
🖥️ Output:
Reversed: olleH
The '\0' never moves. We only swap the visible characters, which is why j starts at len - 1 and not at len.
Example 23: Palindrome Check (a palindrome)
A palindrome reads the same forwards and backwards, like madam. We compare the first character with the last, the second with the second-last and so on. We only need to check half the string.
#include <stdio.h>
#include <string.h>
int main() {
char s[50];
int is_palindrome = 1;
printf("Enter a word: ");
scanf("%s", s);
int len = strlen(s);
for (int i = 0; i < len / 2; i++) {
if (s[i] != s[len - 1 - i]) {
is_palindrome = 0;
break;
}
}
if (is_palindrome) {
printf("%s is a palindrome\n", s);
} else {
printf("%s is not a palindrome\n", s);
}
return 0;
}
🖥️ Output:
Enter a word: madam
madam is a palindrome
Example 24: Palindrome Check (not a palindrome)
The same program, with a different input:
#include <stdio.h>
#include <string.h>
int main() {
char s[50];
int is_palindrome = 1;
printf("Enter a word: ");
scanf("%s", s);
int len = strlen(s);
for (int i = 0; i < len / 2; i++) {
if (s[i] != s[len - 1 - i]) {
is_palindrome = 0;
break;
}
}
if (is_palindrome) {
printf("%s is a palindrome\n", s);
} else {
printf("%s is not a palindrome\n", s);
}
return 0;
}
🖥️ Output:
Enter a word: hello
hello is not a palindrome
h and o are different, so the flag becomes 0 and break stops the loop at once.
7️⃣ Copying and Joining Strings by Hand
Before using library functions, it is worth knowing what they do inside. This also shows why the '\0' matters so much.
Example 25: Copying a String
You cannot write dest = source; for arrays. Instead, copy one character at a time, then add the '\0' yourself.
#include <stdio.h>
int main() {
char source[] = "Welcome";
char dest[20];
int i;
for (i = 0; source[i] != '\0'; i++) {
dest[i] = source[i];
}
dest[i] = '\0'; // never forget the terminator
printf("Source : %s\n", source);
printf("Destination : %s\n", dest);
return 0;
}
🖥️ Output:
Source : Welcome
Destination : Welcome
Example 26: Joining Two Strings (Concatenation)
First walk to the '\0' of the first string. Then copy the second string starting at that position, and finish with a new '\0'.
#include <stdio.h>
int main() {
char first[30] = "Good ";
char second[] = "Morning";
int i = 0, j = 0;
while (first[i] != '\0') { // go to the end of the first string
i++;
}
while (second[j] != '\0') { // copy the second string after it
first[i] = second[j];
i++;
j++;
}
first[i] = '\0';
printf("Result: %s\n", first);
return 0;
}
🖥️ Output:
Result: Good Morning
The first array was declared with size 30, so there was plenty of room for the joined text. Always make sure the destination is big enough.
8️⃣ The Library Functions in string.h
C provides a ready-made toolbox in <string.h>. After seeing how they work by hand, the library versions feel natural.
| Function | What it does | Example |
|---|---|---|
strlen(s) | Number of characters before '\0' | strlen("Hi") → 2 |
strcpy(dest, src) | Copies src into dest | strcpy(a, "Hi") |
strcat(dest, src) | Appends src to the end of dest | strcat(a, "!") |
strcmp(s1, s2) | Compares two strings (0 means equal) | strcmp("a", "b") → negative |
Example 27: strlen
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "Hello";
char s2[] = "Hello World";
char s3[] = "";
printf("strlen(\"%s\") = %d\n", s1, (int) strlen(s1));
printf("strlen(\"%s\") = %d\n", s2, (int) strlen(s2));
printf("strlen(\"%s\") = %d\n", s3, (int) strlen(s3));
return 0;
}
🖥️ Output:
strlen(“Hello”) = 5
strlen(“Hello World”) = 11
strlen(“”) = 0
An empty string "" has only the '\0', so its length is 0.
Example 28: strcpy
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Data Structures";
char dst[30];
strcpy(dst, src); // strcpy(destination, source)
printf("src = %s\n", src);
printf("dst = %s\n", dst);
return 0;
}
🖥️ Output:
src = Data Structures
dst = Data Structures
Remember the order: strcpy(destination, source), like the assignment dest = src.
Example 29: strcat
#include <stdio.h>
#include <string.h>
int main() {
char name[40] = "GLA";
strcat(name, " ");
strcat(name, "University");
printf("%s\n", name);
printf("Length = %d\n", (int) strlen(name));
return 0;
}
🖥️ Output:
GLA University
Length = 14
name had room for 39 characters, and we only used 14 (“GLA University”), so there was no overflow.
Example 30: strcmp
strcmp compares two strings character by character (by ASCII value) and returns:
- 0 if both strings are identical,
- a negative number if the first string comes before the second in dictionary order,
- a positive number if the first string comes after the second.
#include <stdio.h>
#include <string.h>
int main() {
printf("strcmp(\"apple\", \"apple\") = %d\n", strcmp("apple", "apple"));
printf("strcmp(\"apple\", \"banana\") = %d\n", strcmp("apple", "banana"));
printf("strcmp(\"banana\", \"apple\") = %d\n", strcmp("banana", "apple"));
return 0;
}
🖥️ Output:
strcmp(“apple”, “apple”) = 0
strcmp(“apple”, “banana”) = -1
strcmp(“banana”, “apple”) = 1
📝 Note: The exact negative or positive number can differ between compilers (some give -1 and 1, others give the actual ASCII difference). Rely only on whether it is below 0, equal to 0 or above 0.
Example 31: A Simple Password Check
#include <stdio.h>
#include <string.h>
int main() {
char password[] = "c@123";
char entered[30];
printf("Enter password: ");
scanf("%s", entered);
if (strcmp(entered, password) == 0) {
printf("Access granted\n");
} else {
printf("Wrong password\n");
}
return 0;
}
🖥️ Output:
Enter password: c@123
Access granted
Example 32: Which String Comes First?
#include <stdio.h>
#include <string.h>
int main() {
char a[] = "Hello";
char b[] = "Help";
int r = strcmp(a, b);
if (r == 0) printf("Both strings are same\n");
else if (r < 0) printf("\"%s\" comes before \"%s\"\n", a, b);
else printf("\"%s\" comes after \"%s\"\n", a, b);
return 0;
}
🖥️ Output:
“Hello” comes before “Help”
The first two letters match (He), so the decision is made at the third character: 'l' (108) is less than 'p' (112). That is why "Hello" comes before "Help".
9️⃣ Arrays of Strings
What if we want to store the names of 3 students? We need an array of strings, which is a 2-D char array. The first index picks which string and the second picks which character.
Figure 5: Each row of the 2-D array is one complete string with its own ‘\0’.
The number of columns must be big enough for the longest string plus its '\0'. Here "Arjun" has 5 letters, so 6 columns are needed.
Example 33: Printing Several Names
#include <stdio.h>
int main() {
char names[3][10] = {"Ram", "Sita", "Arjun"};
for (int i = 0; i < 3; i++) {
printf("names[%d] = %s\n", i, names[i]);
}
printf("\nFirst letter of each name: ");
for (int i = 0; i < 3; i++) {
printf("%c ", names[i][0]);
}
printf("\n");
return 0;
}
🖥️ Output:
names[0] = Ram
names[1] = Sita
names[2] = Arjun
First letter of each name: R S A
names[i] alone (with one index) is the whole string in row i, which is why %s works. names[i][0] (two indexes) is a single character.
Example 34: Reading Several Names
#include <stdio.h>
#include <string.h>
int main() {
char names[3][20];
for (int i = 0; i < 3; i++) {
printf("Enter name %d: ", i + 1);
scanf("%s", names[i]);
}
printf("\nYou entered:\n");
for (int i = 0; i < 3; i++) {
printf("%d. %s (%d letters)\n", i + 1, names[i], (int) strlen(names[i]));
}
return 0;
}
🖥️ Output:
Enter name 1: Neha
Enter name 2: Rohan
Enter name 3: Ishita
You entered:
1. Neha (4 letters)
2. Rohan (5 letters)
3. Ishita (6 letters)
Example 35: Finding the Longest Word
#include <stdio.h>
#include <string.h>
int main() {
char words[4][15] = {"cat", "elephant", "dog", "tiger"};
int longest = 0;
for (int i = 1; i < 4; i++) {
if (strlen(words[i]) > strlen(words[longest])) {
longest = i;
}
}
printf("Longest word: %s (%d letters)\n", words[longest], (int) strlen(words[longest]));
return 0;
}
🖥️ Output:
Longest word: elephant (8 letters)
We start by assuming word 0 is the longest. Then we check the remaining words one by one, and remember the index of the longest one so far.
🚫 Common Mistakes
Mistake 1: Comparing Strings with ==
Two strings with identical text are not equal according to ==, because == compares where the arrays live in memory, not what they contain.
#include <stdio.h>
int main() {
char a[] = "hello";
char b[] = "hello";
if (a == b) {
printf("Equal\n");
} else {
printf("Not equal\n");
}
return 0;
}
🖥️ Output:
Not equal
The compiler may even warn you about this. Always use strcmp(a, b) == 0 instead.
Mistake 2: Assigning with = After Declaration
char name[20];
name = "Asha"; // ❌ ERROR: arrays cannot be assigned
strcpy(name, "Asha"); // ✅ correct
The = only works at the moment of declaration (char name[20] = "Asha";). Later, use strcpy.
Mistake 3: Forgetting Space for ‘\0’
char s[5] = "Hello"; // ❌ 5 letters need 6 boxes
The terminator has nowhere to go, so functions like printf("%s") will keep reading past the array until they accidentally find a zero byte, printing garbage.
Mistake 4: Writing a Longer String Than the Array Holds
char name[5];
scanf("%s", name); // ❌ typing "Alexander" overflows the array
C does not check array bounds. Overflowing corrupts neighbouring memory and is a classic source of crashes and security holes. Prefer fgets(name, 5, stdin), which never writes more than 5 boxes.
Mistake 5: Using & with scanf for Strings
scanf("%s", &name); // ❌ unnecessary and misleading
scanf("%s", name); // ✅ the array name is already an address
🎓 Practice Exercises
Exercise 1: Predict the Output
char s[] = "Code";
printf("%d %c", s[1], s[3]);
(Answer: 111 e. %d prints the ASCII code of s[1], which is 'o' = 111, and %c prints the character 'e'.)
Exercise 2: Length vs Size
char s[10] = "Hi";
printf("%d %d", (int) strlen(s), (int) sizeof(s));
(Answer: 2 10. The text has 2 characters, but the array has 10 boxes.)
Exercise 3: A Surprise in the Middle
char s[] = "abcde";
s[2] = '\0';
printf("%s", s);
(Answer: ab. We placed a '\0' in the middle, so printf stops there. The characters d and e are still in memory but are no longer part of the string.)
Exercise 4: strcat and strlen
char a[20] = "Fun";
char b[] = "Day";
strcat(a, b);
printf("%s %d", a, (int) strlen(a));
(Answer: FunDay 6. "Fun" and "Day" are joined into "FunDay", which has 6 characters.)
Exercise 5: Skipping Characters
char s[] = "hello";
for (int i = 0; s[i] != '\0'; i += 2) {
printf("%c", s[i]);
}
(Answer: hlo. The index jumps 0, 2, 4, so it prints h, l and o.)
Exercise 6: Build It Yourself
- Read a word and print how many times each vowel (a, e, i, o, u) appears.
- Read a line with
fgetsand print it with every space replaced by an underscore. - Read a word and print it with its first letter in uppercase.
- Read two words and tell whether they are the same, without using
strcmp. - Read 5 names, and print the one that comes first in dictionary order.
❓ Frequently Asked Questions
Q: Is there a string data type in C?
No. A string is just a char array that ends with '\0'. Everything that works for arrays also works for strings.
Q: Why does scanf("%s") not need an &?
The name of an array already gives the address of its first element, so scanf already has what it needs.
Q: What is the difference between "A" and 'A'?'A' is one character (1 byte). "A" is a string of two bytes: 'A' and '\0'.
Q: Why does my fgets output have an extra blank line?fgets keeps the '\n' typed by the user. If you then print with printf("%s\n", line), you get two line breaks. Remove the newline as shown in Example 9.
Q: Why can’t I compare strings with ==?
Because == compares memory addresses of the two arrays, not their contents. Use strcmp.
Q: What happens if I forget the '\0'?
Functions such as printf, strlen and strcpy will keep reading memory until they stumble on a zero byte somewhere. You get garbage output or even a crash.
✅ Key Takeaways
- A string in C is a
chararray that ends with the null character'\0'. There is no separate string type. - The array needs one extra box for the
'\0'."Hello"has 5 characters but needs 6 boxes. 'A'(single quotes) is a character."A"(double quotes) is a string including'\0'.scanf("%s")reads one word and needs no&.fgetsreads a whole line safely, but keeps the'\n'.- To traverse a string, loop until you meet the terminator:
for (i = 0; s[i] != '\0'; i++). strlencounts characters, whilesizeofgives the size of the whole array.- Use
strcpyto copy,strcatto join andstrcmpto compare. Never use==or=to compare or copy strings. - An array of strings is a 2-D
chararray:names[i]is one whole string andnames[i][j]is one character. - C never checks bounds, so always make the array big enough for the text and the
'\0'.
🚀 Keep practising: Type every example yourself instead of copying it, and change the input to see how the output reacts. Whenever a string program misbehaves, ask yourself first: “Did I leave space for the
'\0', and did I stop my loop at it?”
All 29 lessons in this series (open course page)
Part 1 · Getting Started
- Lesson 1: Introduction to C Programming: Overview, Features and Applications
- Lesson 2: The Structure of a C Program: Building Your First Blueprint
- Lesson 3: Identifiers, Keywords and Variables: Naming Things in C Programming
- Lesson 4: Introduction to Algorithms: Thinking Before You Code
- Lesson 5: Introduction to Flowcharts: Drawing the Logic You Already Know
Part 2 · Data Types, Input/Output and Operators
- Lesson 6: Data Types in C: Choosing the Right Box for Every Value
- Lesson 7: Formatted Input and Output in C: Taking Control of printf and scanf
- Lesson 8: Practice Exercise Sheet: Data Types in C
- Lesson 9: Operators and Expressions in C: Assignment, Unary, and Arithmetic
- Lesson 10: Relational, Logical, and Conditional Operators in C
- Lesson 11: Bitwise and Special Operators in C
- Lesson 12: Operator Precedence and Associativity in C
Part 3 · Decisions and Loops
- Lesson 13: Decision and Case Control: if and if-else in C
- Lesson 14: The switch Statement — and switch vs. if-else Ladder
- Lesson 15: The for Loop: Definite Repetition in C
- Lesson 16: while and do-while Loops: Indefinite Repetition in C
- Lesson 17: break and continue in C: Controlling a Loop from the Inside
- Lesson 18: The goto Statement in C: Jumping Around Your Program
Part 4 · Arrays
- Lesson 19: 1-D Arrays in C: Declaration, Address Calculation, Insertion and Deletion
- Lesson 20: Two-Dimensional Arrays in C: Declaration, Initialization and Accessing Elements
- Lesson 21: Matrix Addition and Matrix Multiplication in C
Part 5 · Strings
- Lesson 22: Strings in C: Working with Character Arrays
- Lesson 23: 1-D and 2-D Character Arrays in C: Storing Names and Words
Part 6 · Functions and Scope
- Lesson 24: Functions in C: Declaration and Definition
- Lesson 25: Categories of Functions in C
- Lesson 26: Scope of Variables in C
- Lesson 27: Call by Value in C: How Parameter Passing Works
- Lesson 28: Passing Arrays to Functions in C: Search, Sum and Sort