On this page (10 sections)
- 🎯 Why This Matters
- 1️⃣ The 1-D Character Array: One String
- 2️⃣ Why Do We Need a 2-D Character Array?
- 3️⃣ The 2-D Character Array: A List of Strings
- 4️⃣ Reading Names into a 2-D Array
- 5️⃣ Working with a Collection of Strings
- ⚠️ Common Mistakes
- 📊 1-D vs 2-D Character Array at a Glance
- ❓ Frequently Asked Questions
- ✅ Key Takeaways
Module II · Strings · 1-D and 2-D Character Arrays (Collections of Strings)
🎯 Why This Matters
Think about the programs you use every day. An attendance register stores the names of 60 students. A phone stores a list of contacts. A restaurant app stores the menu items. A railway app stores the names of stations. None of these is a single number, and none of them is a single word. They are collections of strings.
In the previous post we learnt that C stores one string in a 1-D character array. In this post we take the next step: how to store many strings together in a 2-D character array, how to read them, display them and use them. By the end you will be able to build a small student register of your own.
1️⃣ The 1-D Character Array: One String
A 1-D character array is a row of boxes, and every box holds one character. When the characters are followed by the null character '\0', the array holds a string, for example one name or one word.
char name[10] = "Rohit";
| [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] |
| R | o | h | i | t | \0 |
Figure 1: A 1-D char array holds ONE string. "Rohit" uses 5 boxes for letters and 1 box for the null character; the other 4 boxes are unused.
The number in the brackets is the size of the array, the number of boxes reserved. It must be at least number of letters + 1, because the '\0' also needs a box. The syntax is:
char array_name[size];
Ways to Initialize a 1-D Character Array
| Declaration | Array size | Remark |
|---|---|---|
char a[] = "Hello"; | 6 | The compiler counts for you: 5 letters + '\0' |
char b[10] = "Hello"; | 10 | Extra boxes are filled with '\0' |
char c[] = {'H','e','l','l','o','\0'}; | 6 | Letter by letter. You must write the '\0' yourself |
char d[10] = {'H','i'}; | 10 | Remaining boxes become '\0', so this is the string “Hi” |
char e[5] = "Hello"; | 5 | ⚠️ No box left for '\0': not a proper string |
Example 1: Store and Display a Name
Let us store the name Rohit and display it in different ways.
#include <stdio.h>
int main() {
char name[20] = "Rohit";
int i;
printf("Name : %s\n", name);
printf("Name letter by letter: ");
for (i = 0; name[i] != '\0'; i++) {
printf("%c ", name[i]);
}
printf("\n");
printf("First letter: %c\n", name[0]);
printf("Last letter : %c\n", name[i - 1]);
return 0;
}
Name : Rohit
Name letter by letter: R o h i t
First letter: R
Last letter : t
How it works:
char name[20] = "Rohit";reserves 20 boxes and stores the 5 letters and the'\0'in the first 6.%sprints the whole string. It starts at the first box and stops when it reaches the'\0'.- The
forloop visits one box after another withname[i]and stops at'\0'. When the loop ends,iis 5, the length of the name. name[0]is the first letter. Since the loop ended withi = 5,name[i - 1]isname[4], the last letter.
Example 2: Size of the Array and Length of the String
The size of an array and the length of the string stored in it are two different things. sizeof tells how many boxes exist, and strlen() tells how many characters come before the '\0'.
#include <stdio.h>
#include <string.h>
int main() {
char a[] = "Hello";
char b[10] = "Hello";
char c[] = {'H', 'e', 'l', 'l', 'o', '\0'};
char d[10] = {'H', 'i'};
printf("a: size = %2zu, length = %zu\n", sizeof(a), strlen(a));
printf("b: size = %2zu, length = %zu\n", sizeof(b), strlen(b));
printf("c: size = %2zu, length = %zu\n", sizeof(c), strlen(c));
printf("d: size = %2zu, length = %zu\n", sizeof(d), strlen(d));
return 0;
}
a: size = 6, length = 5
b: size = 10, length = 5
c: size = 6, length = 5
d: size = 10, length = 2
Look at the results: a and c have size 6 (5 letters and the '\0'). b and d were given size 10, so sizeof says 10, but the strings inside them are only 5 and 2 characters long. The size never changes, the length depends on where the first '\0' is.
Reading a Name into a 1-D Array
There are two common ways to read text from the keyboard.
Example 3: Reading One Word with scanf()
#include <stdio.h>
int main() {
char word[30];
printf("Enter a word: ");
scanf("%s", word);
printf("Stored in the array: %s\n", word);
return 0;
}
Enter a word: Rohit
Stored in the array: Rohit
#include <stdio.h>
int main() {
char word[30];
printf("Enter a word: ");
scanf("%s", word);
printf("Stored in the array: %s\n", word);
return 0;
}
Enter a word: Rohit Sharma
Stored in the array: Rohit
Notice that there is no & before word. The name of an array already means the address of its first box. In run 2 the user typed Rohit Sharma, but only Rohit was stored, because scanf("%s") stops reading at the first space.
Example 4: Reading a Full Name with fgets()
To read a name that contains spaces, use fgets(). It reads the whole line, including spaces, and it never writes more characters than the array can hold.
#include <stdio.h>
#include <string.h>
int main() {
char name[40];
printf("Enter your full name: ");
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0';
printf("Hello, %s!\n", name);
printf("Your name has %zu characters.\n", strlen(name));
return 0;
}
Enter your full name: John Smith
Hello, John Smith!
Your name has 10 characters.
fgets(name, sizeof(name), stdin)reads a line from the keyboard (stdin) intoname, at mostsizeof(name) - 1characters.fgets()also stores the new line character'\n'that comes from pressing Enter.strcspn(name, "\n")finds its position, and we overwrite it with'\0'to remove it.- The length is 10: the 4 letters of John, the space, and the 5 letters of Smith.
gets(). It cannot limit the input, so a long name overflows the array. It was removed from the C standard. Use fgets().2️⃣ Why Do We Need a 2-D Character Array?
Suppose a teacher wants to store the names of 50 students. With 1-D arrays she would need char name1[20]; char name2[20]; ... char name50[20];, fifty different variables! It would be impossible to use a loop, and a program to print all the names would have to be 50 lines long.
Remember how we solved the same problem for numbers: instead of 50 variables we used one array, int marks[50]. For strings we do exactly the same, but because every element is itself a string (an array of characters), we need an array of arrays, a 2-D array.
| R | o | h | i | t | \0 |
| [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | |
| names[0] | A | m | i | t | \0 | |||||
| names[1] | N | e | h | a | \0 | |||||
| names[2] | R | o | h | i | t | \0 | ||||
| names[3] | P | r | i | y | a | \0 |
Figure 2: A 1-D array holds one name. A 2-D char array holds a whole list of names, one name in every row.
3️⃣ The 2-D Character Array: A List of Strings
Declaration
char names[ROWS][COLUMNS];
char names[4][10]; // 4 strings, each of at most 9 letters + '\0'
- The first size (rows) is how many strings the array can hold.
- The second size (columns) is the maximum length of one string, including the
'\0'.
| [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | |
| names[0] | A | m | i | t | \0 | |||||
| names[1] | N | e | h | a | \0 | |||||
| names[2] | R | o | h | i | t | \0 | ||||
| names[3] | P | r | i | y | a | \0 |
Figure 3: char names[4][10] is a table of 4 rows and 10 columns. Every row stores one string, ending with '\0'.
Row or Single Character? One Index or Two?
This is the most important idea of the whole post:
| Expression | Meaning | Example (from the figure) |
|---|---|---|
names[i] | The whole string in row i | names[3] is “Priya” |
names[i][j] | The single character in row i, column j | names[3][2] is ‘i’ |
| [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | |
| names[0] | A | m | i | t | \0 | |||||
| names[1] | N | e | h | a | \0 | |||||
| names[2] | R | o | h | i | t | \0 | ||||
| names[3] | P | r | i | y | a | \0 |
names[3] = “Priya” (whole row) names[3][2] = ‘i’ (one cell)Figure 4: One index selects a whole string (a row). Two indexes select one character.
That is why we print a name with printf("%s", names[i]), using %s with one index, and a letter with printf("%c", names[i][j]), using %c with two indexes.
Initialization
// 1. A list of names, one string per row
char names[4][10] = {"Amit", "Neha", "Rohit", "Priya"};
// 2. The number of rows may be left empty (the columns may NOT)
char cities[][12] = {"Mathura", "Agra", "Delhi"}; // 3 rows
// 3. Fewer names than rows: the remaining rows become empty strings
char team[5][10] = {"Kiran", "Sunita"}; // rows 2, 3, 4 are ""
char names[][] = {...}; is an error.How Big Should the Column Size Be?
Every row has the same length, so choose the column size according to the longest string you expect, plus one for the '\0'. If you choose too small a size, the longest name will not fit; if you choose a much bigger one, memory is wasted.
| [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | |
| names[0] | A | m | i | t | \0 | |||||
| names[1] | N | e | h | a | \0 | |||||
| names[2] | R | o | h | i | t | \0 | ||||
| names[3] | P | r | i | y | a | \0 |
Figure 5: In char names[4][10] the four names use only 22 of the 40 bytes. The column size should be the longest name + 1.
Example 5: Initialize and Display a List of Names
#include <stdio.h>
int main() {
char names[4][10] = {"Amit", "Neha", "Rohit", "Priya"};
int i;
printf("Names in the list:\n");
for (i = 0; i < 4; i++) {
printf("%d. %s\n", i + 1, names[i]);
}
printf("\nnames[2] = %s\n", names[2]);
printf("names[2][0] = %c\n", names[2][0]);
printf("names[1][2] = %c\n", names[1][2]);
return 0;
}
Names in the list:
1. Amit
2. Neha
3. Rohit
4. Priya
names[2] = Rohit
names[2][0] = R
names[1][2] = h
char names[4][10] = {...}creates 4 rows and stores one name in each.- The
forloop runs withifrom 0 to 3 (the row number).names[i]is the whole name in rowi, so%sprints it. We printi + 1so that the numbering starts from 1. names[2]is “Rohit” (a string),names[2][0]is its first letterR, andnames[1][2]is the third letter of “Neha”, which ish.
How the 2-D Array Sits in Memory
Memory is a long single line of bytes. A 2-D array is therefore stored row after row (row-major order): all boxes of row 0, then all boxes of row 1, and so on.
| A | m | i | t | \0 | N | e | h | a | \0 | J | o | y | \0 | ||||
names[0]address 1000 | names[1]address 1006 | names[2]address 1012 | |||||||||||||||
Figure 6: names[3][6] occupies 18 consecutive bytes. Each row starts exactly one "column size" after the previous row.
- Address of row
i= start address +i × columns. - Total memory =
rows × columnsbytes (everychartakes 1 byte).
4️⃣ Reading Names into a 2-D Array
To read a list of names we use a loop. The loop variable is the row number, and in every round the next word is stored in the next row.
| Round | User types | scanf(“%s”, names[i]) stores it in |
| i = 0 | Amit | names[0] → Amit |
| i = 1 | Neha | names[1] → Neha |
| i = 2 | Rohit | names[2] → Rohit |
Figure 7: In every round of the loop, scanf stores one word in row i of the array.
Example 6: Read n Names and Display Them
#include <stdio.h>
int main() {
char names[10][20];
int n, i;
printf("Enter number of names: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter name %d: ", i + 1);
scanf("%s", names[i]);
}
printf("\nYou entered:\n");
for (i = 0; i < n; i++) {
printf("%d. %s\n", i + 1, names[i]);
}
return 0;
}
Enter number of names: 3
Enter name 1: Amit
Enter name 2: Neha
Enter name 3: Rohit
You entered:
1. Amit
2. Neha
3. Rohit
Trace of the first loop (the user types Amit, Neha, Rohit):
| i | Prompt shown | Word typed | Stored in |
|---|---|---|---|
| 0 | Enter name 1: | Amit | names[0] |
| 1 | Enter name 2: | Neha | names[1] |
| 2 | Enter name 3: | Rohit | names[2] |
Again, there is no & in scanf("%s", names[i]), because names[i] is a row, and a row is an array, so it already means an address. The array names[10][20] can hold up to 10 names of at most 19 letters, so we use only the first n rows.
Example 7: Read Full Names (with Spaces)
For names with spaces, such as John Smith, replace scanf by fgets. The row names[i] is the destination, and we remove the '\n' from each row.
#include <stdio.h>
#include <string.h>
int main() {
char names[3][30];
int i;
for (i = 0; i < 3; i++) {
printf("Enter full name %d: ", i + 1);
fgets(names[i], sizeof(names[i]), stdin);
names[i][strcspn(names[i], "\n")] = '\0';
}
printf("\nStudent list:\n");
for (i = 0; i < 3; i++) {
printf("%d. %s (%zu characters)\n",
i + 1, names[i], strlen(names[i]));
}
return 0;
}
Enter full name 1: John Smith
Enter full name 2: Neha Verma
Enter full name 3: Rohit Sharma
Student list:
1. John Smith (10 characters)
2. Neha Verma (10 characters)
3. Rohit Sharma (12 characters)
scanf("%d") and fgets() carelessly. After scanf("%d", &n) the Enter key remains in the input, and the next fgets() would read an empty line. This is why this program uses a fixed number of names. If you must read a number first, clear the leftover with scanf("%d%*c", &n);.⚠️ You Cannot Assign a String to a Row with =
char names[3][10];
names[0] = "Amit"; // ❌ ERROR: an array cannot be assigned
strcpy(names[0], "Amit"); // ✅ correct: copy the characters into the row
A row is an array, and C does not allow whole arrays to be assigned with =. Use strcpy() (from string.h) to put a string into a row after the declaration.
5️⃣ Working with a Collection of Strings
Once the names are in the array, the real power comes from loops. Every program below follows the same pattern: a loop over the rows, and inside it the usual string tools (strlen, strcmp, strcpy).
Example 8: Initials and Lengths
The first letter of every name sits in column 0, so names[i][0] gives the initials. The last letter is at index length - 1.
| [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | |
| names[0] | A | m | i | t | \0 | |||||
| names[1] | N | e | h | a | \0 | |||||
| names[2] | R | o | h | i | t | \0 | ||||
| names[3] | P | r | i | y | a | \0 |
names[i][0]Figure 8: names[i][0] is the first letter of every name, the whole of column 0.
#include <stdio.h>
#include <string.h>
int main() {
char names[4][10] = {"Amit", "Neha", "Rohit", "Priya"};
int i, len;
printf("%-8s %-8s %-8s %s\n", "Name", "Initial", "Length", "Last letter");
for (i = 0; i < 4; i++) {
len = strlen(names[i]);
printf("%-8s %-8c %-8d %c\n",
names[i], names[i][0], len, names[i][len - 1]);
}
printf("\nInitials together: ");
for (i = 0; i < 4; i++) {
putchar(names[i][0]);
}
printf("\n");
return 0;
}
Name Initial Length Last letter
Amit A 4 t
Neha N 4 a
Rohit R 5 t
Priya P 5 a
Initials together: ANRP
strlen(names[i])gives the length of the name in rowi.names[i][len - 1]is the last letter, because the letters are at indexes 0 tolen - 1.%-8sprints a string left-aligned in a field of 8 characters, which keeps the table tidy.
Example 9: Search a Name in the List
To search a list of strings we compare every row with the name we are looking for, using strcmp(). Remember: never compare strings with ==.
#include <stdio.h>
#include <string.h>
int main() {
char names[5][10] = {"Amit", "Neha", "Rohit", "Priya", "Kiran"};
char key[10];
int i, pos = -1;
printf("Enter the name to search: ");
scanf("%s", key);
for (i = 0; i < 5; i++) {
if (strcmp(names[i], key) == 0) {
pos = i;
break;
}
}
if (pos == -1)
printf("%s is not in the list.\n", key);
else
printf("%s found at row %d (position %d).\n",
key, pos, pos + 1);
return 0;
}
Enter the name to search: Priya
Priya found at row 3 (position 4).
#include <stdio.h>
#include <string.h>
int main() {
char names[5][10] = {"Amit", "Neha", "Rohit", "Priya", "Kiran"};
char key[10];
int i, pos = -1;
printf("Enter the name to search: ");
scanf("%s", key);
for (i = 0; i < 5; i++) {
if (strcmp(names[i], key) == 0) {
pos = i;
break;
}
}
if (pos == -1)
printf("%s is not in the list.\n", key);
else
printf("%s found at row %d (position %d).\n",
key, pos, pos + 1);
return 0;
}
Enter the name to search: Sunil
Sunil is not in the list.
pos = -1means “not found yet”.strcmp(names[i], key) == 0is true when the two strings are exactly equal. Then we remember the row and stop withbreak.- After the loop,
postells whether the name was found. Priya is in row 3, so it is the 4th name.
Example 10: Longest and Shortest Name
This is the “find the maximum” idea you already know, but applied to the length of the strings. We keep the row number of the best name so far.
#include <stdio.h>
#include <string.h>
int main() {
char names[5][12] = {"Amit", "Priyanka", "Raj", "Kiran", "Sunita"};
int i, longest = 0, shortest = 0;
for (i = 1; i < 5; i++) {
if (strlen(names[i]) > strlen(names[longest]))
longest = i;
if (strlen(names[i]) < strlen(names[shortest]))
shortest = i;
}
printf("Longest name : %s (%zu letters)\n",
names[longest], strlen(names[longest]));
printf("Shortest name: %s (%zu letters)\n",
names[shortest], strlen(names[shortest]));
return 0;
}
Longest name : Priyanka (8 letters)
Shortest name: Raj (3 letters)
longestandshorteststart at row 0.- For every other row, we compare its length with the length of the current best name, and update the row number if it is longer (or shorter).
- At the end,
names[longest]is the longest name: Priyanka with 8 letters. Raj is the shortest with 3.
Example 11: Sort the Names Alphabetically
Sorting a list of names is the bubble sort you know, with two differences: we compare with strcmp() instead of >, and we swap with strcpy() instead of =.
| Step | names[j] | names[j+1] | temp |
| Start | Rohit | Amit | — |
| 1. strcpy(temp, names[j]) | Rohit | Amit | Rohit |
| 2. strcpy(names[j], names[j+1]) | Amit | Amit | Rohit |
| 3. strcpy(names[j+1], temp) | Amit | Rohit | Rohit |
Figure 9: Swapping two names takes a temporary string and three strcpy() calls.
#include <stdio.h>
#include <string.h>
int main() {
char names[5][10] = {"Rohit", "Amit", "Neha", "Priya", "Kiran"};
char temp[10];
int i, j;
printf("Before sorting:");
for (i = 0; i < 5; i++)
printf(" %s", names[i]);
for (i = 0; i < 4; i++) {
for (j = 0; j < 4 - i; j++) {
if (strcmp(names[j], names[j + 1]) > 0) {
strcpy(temp, names[j]);
strcpy(names[j], names[j + 1]);
strcpy(names[j + 1], temp);
}
}
}
printf("\nAfter sorting :");
for (i = 0; i < 5; i++)
printf(" %s", names[i]);
printf("\n");
return 0;
}
Before sorting: Rohit Amit Neha Priya Kiran
After sorting : Amit Kiran Neha Priya Rohit
strcmp(names[j], names[j + 1]) > 0means that the name in rowjcomes after the next name in dictionary order, so they are in the wrong order.- The three
strcpy()calls are the swap shown in Figure 9: save the first name intemp, copy the second into the first place, then copytempinto the second place. - The inner loop runs up to
4 - ibecause after every pass the largest name has already reached its final place at the end.
Example 12: Split a Sentence into Words
A 2-D char array is also the natural place to keep the words of a sentence. We cut the sentence with strtok() and copy every word into its own row.
#include <stdio.h>
#include <string.h>
int main() {
char sentence[] = "C is easy and fun";
char words[10][20];
char *w;
int count = 0, i;
w = strtok(sentence, " ");
while (w != NULL && count < 10) {
strcpy(words[count], w);
count++;
w = strtok(NULL, " ");
}
printf("Number of words: %d\n", count);
printf("Words in reverse order:\n");
for (i = count - 1; i >= 0; i--) {
printf("%s\n", words[i]);
}
return 0;
}
Number of words: 5
Words in reverse order:
fun
and
easy
is
C
strtok(sentence, " ")returns the first word (the text up to the first space). Each later callstrtok(NULL, " ")returns the next word, and returnsNULLwhen no word is left.strcpy(words[count], w)copies the word into the next free row, andcountcounts the rows used.- Printing the rows from
count - 1down to 0 shows the words in reverse order. count < 10in the loop condition protects the array: it has only 10 rows.
Example 13: Names and Marks Together (Parallel Arrays)
A student register needs a name and marks. We keep two arrays side by side: a 2-D char array for the names and a 1-D int array for the marks. The element with the same index belongs to the same student: names[i] goes with marks[i].
#include <stdio.h>
int main() {
char names[5][15] = {"Amit", "Neha", "Rohit", "Priya", "Kiran"};
int marks[5] = {78, 91, 66, 85, 59};
int i, top = 0, total = 0;
printf("%-4s %-10s %s\n", "No.", "Name", "Marks");
for (i = 0; i < 5; i++) {
printf("%-4d %-10s %d\n", i + 1, names[i], marks[i]);
total += marks[i];
if (marks[i] > marks[top])
top = i;
}
printf("\nTopper : %s with %d marks\n", names[top], marks[top]);
printf("Average: %.1f\n", (float)total / 5);
return 0;
}
No. Name Marks
1 Amit 78
2 Neha 91
3 Rohit 66
4 Priya 85
5 Kiran 59
Topper : Neha with 91 marks
Average: 75.8
- The loop prints one table row per student, and adds each mark to
total. topstores the index of the best student so far. Because the same index works in both arrays,names[top]andmarks[top]give the topper’s name and marks.(float)total / 5converts the total to a decimal number first, so the average is 75.8 and not 75.
⚠️ Common Mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
char names[][] = {...}; | Compile error: the column size is missing | Write the second size: char names[][10] |
| Column size equal to the longest name | No place for '\0', so the string is not terminated | Column size = longest name + 1 |
names[0] = "Amit"; | Compile error: arrays cannot be assigned | strcpy(names[0], "Amit"); |
scanf("%s", &names[i]); | Unneeded &; works by luck or gives a warning | scanf("%s", names[i]); |
if (names[i] == key) | Compares addresses, not the text, so it is almost never true | if (strcmp(names[i], key) == 0) |
printf("%s", names[i][0]); | names[i][0] is one character, not a string, so the program may crash | Use %c for one character, %s for a row |
Looping up to i <= rows | Reads a row that does not exist | Use i < rows |
| Reading more names than there are rows | Writes outside the array | Check n against the number of rows |
📊 1-D vs 2-D Character Array at a Glance
| 1-D character array | 2-D character array | |
|---|---|---|
| Stores | One string (a name or a word) | A list of strings (many names or words) |
| Declaration | char name[20]; | char names[5][20]; |
| Whole string | name | names[i] |
| One character | name[j] | names[i][j] |
| Read a word | scanf("%s", name); | scanf("%s", names[i]); |
| Read a line | fgets(name, 20, stdin); | fgets(names[i], 20, stdin); |
printf("%s", name); | printf("%s", names[i]); | |
| Loops needed to visit every letter | 1 | 2 (rows and letters), or 1 loop plus string functions |
| Memory | size bytes | rows × columns bytes |
❓ Frequently Asked Questions
Q: Can the names in a 2-D array have different lengths?
Yes. Every row has the same capacity (the column size), but each string inside it can be shorter. The '\0' marks where each string ends, and the remaining boxes of the row are simply not used.
Q: Is a 2-D char array the same as a 2-D int array?
The structure is the same (rows and columns), but we use it differently. With numbers we usually need both indexes, as in A[i][j]. With strings we mostly use one index, names[i], because every row is a complete string.
Q: How do I know how many names are stored?
C does not remember it. Keep a counter (like n or count in our programs), or store it in a variable when you read the names.
✅ Key Takeaways
- A 1-D character array stores one string:
char name[20];. Its size must be at least letters + 1 for the'\0'. - A 2-D character array stores a list of strings:
char names[ROWS][COLS];. Rows = how many strings, columns = the longest string + 1. names[i]is the whole string in rowi(use%s).names[i][j]is one character (use%c).- The column size can never be omitted in the declaration.
- Use
scanf("%s", names[i])for single words andfgets()for names with spaces. Never usegets(). - Never assign a string to a row with
=and never compare with==. Usestrcpy()andstrcmp(). - The rows are stored one after another in memory, so the array needs
rows × columnsbytes. - Processing a list of names is a loop over the rows with
strlen(),strcmp()andstrcpy()inside.
🚀 Keep practising: (1) Read 5 names and print only those that start with the letter ‘A’. (2) Read 5 names and print them in reverse order of the list. (3) Print every name in capital letters. (4) Read 5 names with marks and print the name of the student with the lowest marks. (5) Read 5 words and print the longest one. Try them first on paper, then in code.
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