TalentJR

⚙️ C programming basics · Class 10 · Lesson 3 of 18 · Free

Arrays and Strings in C – Lists of Marks, Names and string.h

⏱ About 40 minutes · ▶ run real C here — nothing to install · no sign-in

In this lesson you will

  • Create arrays, loop over them and pass them to functions with their length
  • Explain how C stores a string as characters ending in '\0'
  • Read a full line with fgets and use strlen, strcpy, strcat and strcmp

A class teacher has marks for 40 students. Making 40 separate variables named m1, m2, m3… would be painful. An array keeps all of them under one name. And every name on the report card, like "Riya Sharma", is stored in C as an array of characters.

What is an array in C?

An array is a row of boxes of the same type, kept side by side in memory. int marks[5] makes 5 int boxes. You reach each box with an index in square brackets, starting from 0. So the last box is marks[4], not marks[5].

C does NOT check the index for you. marks[5] would touch memory outside the array. That is a serious bug, so keep your loops between 0 and size - 1.

sizeof(marks) / sizeof(marks[0]) gives the number of items: total bytes divided by bytes per item.

Try it: add a sixth mark, 95, to the list and run again. The count updates by itself.

⚙️ C — you can edit this code
Output
Subject 1: 78
Subject 2: 92
Subject 3: 65
Subject 4: 88
Subject 5: 71
Subjects: 5
Total: 394, Average: 78.80
After re-check, subject 3 has 70

How do you pass an array to a function in C?

When you pass an array to a function, C passes a pointer to its first item (you saw this in Lesson 2). No copy is made.

Two results follow. First, the function cannot find the length by itself, so you must pass the length too. Second, the function can change the caller's array.

Here add_grace gives 5 grace marks to everyone below 33. Use const in a parameter when the function only reads the array.

Try it: change the grace marks from 5 to 3 and run again.

⚙️ C — you can edit this code
Output
30 45 29 88 31 
35 45 34 88 36 

What is a string in C?

C has no separate string type. A string is a char array that ends with a special character '\0', called the null character. It marks where the text stops.

char name[] = "Riya"; makes 5 boxes: 'R', 'i', 'y', 'a' and '\0'. strlen counts letters before '\0' (4). sizeof counts all boxes (5).

Each char is really a small number (its ASCII code). 'A' is 65. So you can print a char with %c or %d.

Try it: change the name to your own and run again.

⚙️ C — you can edit this code
Output
Name: Riya
strlen = 4, sizeof = 5
name[0] = 'R' (code 82)
name[1] = 'i' (code 105)
name[2] = 'y' (code 121)
name[3] = 'a' (code 97)
Changed: Piya

How do you read a full name with spaces in C?

scanf("%s", ...) stops reading at the first space, so "Riya Sharma" becomes just "Riya". To read a whole line, use fgets(buffer, size, stdin).

fgets never writes more than size - 1 characters, so your array cannot overflow. It also keeps the Enter key as '\n' at the end. strcspn(name, "\n") finds that position, and we replace it with '\0'.

Try it: change the input to a longer name, like your full name, and run again.

⚙️ C — you can edit this code
Output
Passenger name: Riya Sharma
Ticket booked for [Riya Sharma]
Name has 11 characters

💡 The [ ] around the name show that no extra newline is left inside the string.

Which string.h functions should you know in C?

You cannot copy a string with = or compare it with ==. Use the functions in <string.h>.

strcpy(dest, src) copies text. strcat(dest, src) adds text to the end. strcmp(a, b) returns 0 when they are equal, a negative number when a comes first in dictionary order, and a positive number when b comes first.

The destination array must be big enough for all the letters plus '\0'. C will not stop you if it is too small.

Try it: change second to "Aman" and see which name comes first.

⚙️ C — you can edit this code
Output
Full name: Ananya Iyer (11 characters)
Ananya comes before Kabir

How do you count and change characters in a C string?

Because a string is an array, you can loop through it until you reach '\0'. The <ctype.h> header gives helpers like toupper, isdigit and isalpha.

This program checks a railway PNR-style code: it counts digits and letters and makes all letters capital.

Try it: change the code to "ab12cd34" and run again.

⚙️ C — you can edit this code
Output
Code: PNR4521K9
Digits: 5, Letters: 4

💡 The (unsigned char) cast is the safe way to call ctype functions with a char.

🤔 Predict the output

Think like C: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

int a[5] = {4, 7};
printf("%d %d\n", a[1], a[3]);

Question 2. What does this print?

char s[] = "Class 10";
printf("%zu %zu\n", strlen(s), sizeof(s));

Question 3. What does this print?

char w[] = "tiffin";
int count = 0;
for (int i = 0; w[i] != '\0'; i++) {
    if (w[i] == 'f') {
        count++;
    }
}
w[0] = 'T';
printf("%s %d\n", w, count);

🧩 Your challenge

Read a full name with fgets and print the initials (first letter of each word, followed by a dot) and the number of letters without spaces. For input Riya Sharma Patil the output ends with: Initials: R.S.P. Letters: 15

Expected output (with the inputs given):
Full name: Riya Sharma Patil
Initials: R.S.P.
Letters: 15
⚙️ C — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

char name[20];
name = "Riya";
printf("%s\n", name);

Line 2: error: array type 'char[20]' is not assignable

✅ Right

char name[20];
strcpy(name, "Riya");
printf("%s\n", name);

You cannot assign to a whole array with = after it is made. Copy the text in with strcpy (or set it when you declare: char name[20] = "Riya";).

❌ Wrong

char a[] = "Riya";
char b[] = "Riya";
if (a == b) {
    printf("Same\n");
} else {
    printf("Different\n");
}

Compiles and runs, but prints: Different ⏎

✅ Right

char a[] = "Riya";
char b[] = "Riya";
if (strcmp(a, b) == 0) {
    printf("Same\n");
} else {
    printf("Different\n");
}

== compares the two arrays' addresses, which are always different. strcmp compares the letters.

❌ Wrong

#include <stdio.h>

int total(int m[]) {
    int n = sizeof(m) / sizeof(m[0]);
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += m[i];
    }
    return sum;
}

int main(void) {
    int marks[] = {78, 92, 65, 88, 71};
    printf("Total: %d\n", total(marks));
    return 0;
}

Compiles and runs, but prints: Total: 78 ⏎

✅ Right

#include <stdio.h>

int total(const int m[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += m[i];
    }
    return sum;
}

int main(void) {
    int marks[] = {78, 92, 65, 88, 71};
    int n = sizeof(marks) / sizeof(marks[0]);
    printf("Total: %d\n", total(marks, n));
    return 0;
}

Inside a function, m is only a pointer, so sizeof(m) is the pointer's size, not the array's. Work out the length where the array is made and pass it in.

📌 Remember

  • An array holds many values of one type; indexes go from 0 to size - 1, and C does not check them.
  • Arrays are passed to functions as pointers: pass the length too, and remember the function can change them.
  • A C string is a char array ending in '\0'; strlen does not count it, sizeof does.
  • Use fgets to read a whole line safely, then remove the '\n' with strcspn.
  • Copy with strcpy, join with strcat, compare with strcmp — never = or == on strings.

Finished the quiz and the challenge?

Questions students ask

Why do arrays start at index 0 in C?

The index is the distance from the first item. The first item is 0 steps away, so it is marks[0]. This matches pointer arithmetic from Lesson 2: marks[i] means *(marks + i).

What is the difference between a char and a string in C?

A char is one character in single quotes, like 'A'. A string is many chars in an array ending with '\0', written in double quotes, like "A" (which is 2 bytes: 'A' and '\0').

Why is gets() not used in C anymore?

gets had no way to know the size of your array, so long input could overflow it. It was removed from the C standard in C11. Use fgets, which takes the size.

What happens if I go past the end of an array in C?

C does not stop you. The program may print strange values, change other variables or crash. This is called undefined behaviour, so always keep indexes inside the array.