Day 7: Arrays & Strings#
Overview#
Arrays allow us to store multiple values of the same type. Strings are arrays of characters. Today we’ll learn how to create, manipulate, and work with both.
What We’ll Learn Today#
- One-dimensional arrays
- Two-dimensional arrays
- Accessing array elements
- Strings in C
- String operations
- Common string functions
One-Dimensional Arrays#
Array Declaration and Initialization#
int marks[5]; // Declare array of 5 integers
Initialization#
// Method 1: Without size (inferred)
int marks[] = {85, 90, 78, 92, 88};
// Method 2: With size
int marks[5] = {85, 90, 78, 92, 88};
// Method 3: Partial initialization
int marks[5] = {85, 90}; // Rest are 0
// Method 4: All zeros
int marks[5] = {0};Accessing Array Elements#
Arrays are zero-indexed (first element is at index 0):
#include <stdio.h>
int main() {
int marks[] = {85, 90, 78, 92, 88};
printf("First element: %d\n", marks[0]); // 85
printf("Second element: %d\n", marks[1]); // 90
printf("Third element: %d\n", marks[2]); // 78
printf("Last element: %d\n", marks[4]); // 88
return 0;
}Modifying Array Elements#
int marks[5] = {85, 90, 78, 92, 88};
marks[0] = 95; // Change first element
marks[2] = 82; // Change third element
printf("New first element: %d\n", marks[0]); // 95
printf("New third element: %d\n", marks[2]); // 82
Array Size and Length#
int marks[] = {85, 90, 78, 92, 88};
// Get array size in bytes
int size = sizeof(marks); // 20 (5 integers * 4 bytes)
// Get number of elements
int length = sizeof(marks) / sizeof(marks[0]); // 5
printf("Array size: %d bytes\n", size);
printf("Array length: %d elements\n", length);Iterating Through Arrays#
#include <stdio.h>
int main() {
int marks[] = {85, 90, 78, 92, 88};
int length = sizeof(marks) / sizeof(marks[0]);
printf("Marks: ");
for (int i = 0; i < length; i++) {
printf("%d ", marks[i]);
}
printf("\n");
return 0;
}Output:
Marks: 85 90 78 92 88Practical Example: Calculate Average#
#include <stdio.h>
int main() {
int scores[] = {85, 90, 78, 92, 88};
int length = sizeof(scores) / sizeof(scores[0]);
int sum = 0;
for (int i = 0; i < length; i++) {
sum += scores[i];
}
float average = sum / (float)length;
printf("Average: %.2f\n", average);
return 0;
}Two-Dimensional Arrays#
Arrays with rows and columns:
Declaration#
int matrix[3][4]; // 3 rows, 4 columns
Initialization#
// Method 1: With values
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Method 2: All zeros
int matrix[3][4] = {0};Accessing Elements#
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
printf("%d\n", matrix[0][0]); // 1 (row 0, column 0)
printf("%d\n", matrix[1][2]); // 7 (row 1, column 2)
printf("%d\n", matrix[2][3]); // 12 (row 2, column 3)
Iterating Through 2D Arrays#
#include <stdio.h>
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Print the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%3d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}Output:
1 2 3 4
5 6 7 8
9 10 11 12Strings in C#
A string is an array of characters ending with a null terminator (\0):
char name[] = "Alice";
// Stored as: A l i c e \0 (6 bytes total)
String Declaration#
// Method 1: Array of characters
char name[] = "John";
// Method 2: Specify size
char name[50] = "John";
// Method 3: Without initialization
char name[50]; // Empty string
// Method 4: Character by character
char name[] = {'J', 'o', 'h', 'n', '\0'};Reading Strings from User#
#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
scanf("%s", name); // Note: NO & for strings!
printf("Hello, %s!\n", name);
return 0;
}Important: %s format specifier#
- Use
%sfor strings (not%cfor individual chars) - For
scanf()with strings, do NOT use&(strings are special)
scanf("%s", name); // ✅ Correct
scanf("%s", &name); // ❌ Wrong (though sometimes works)
String Functions#
Include <string.h> for string functions:
strlen() - String Length#
#include <stdio.h>
#include <string.h>
int main() {
char name[] = "Alice";
int length = strlen(name);
printf("Length of '%s': %d\n", name, length); // 5
return 0;
}strcpy() - String Copy#
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello";
char destination[50];
strcpy(destination, source);
printf("Source: %s\n", source); // Hello
printf("Destination: %s\n", destination); // Hello
return 0;
}strcat() - String Concatenation#
#include <stdio.h>
#include <string.h>
int main() {
char greeting[50] = "Hello, ";
char name[] = "Alice";
strcat(greeting, name);
printf("%s\n", greeting); // Hello, Alice
return 0;
}strcmp() - String Comparison#
#include <stdio.h>
#include <string.h>
int main() {
char password[] = "secret123";
char input[50];
printf("Enter password: ");
scanf("%s", input);
if (strcmp(password, input) == 0) {
printf("Access granted!\n");
} else {
printf("Wrong password!\n");
}
return 0;
}Return values:
- 0: Strings are equal
- < 0: First string is less than second
0: First string is greater than second
Iterating Through Strings#
#include <stdio.h>
#include <string.h>
int main() {
char word[] = "HELLO";
// Print each character
for (int i = 0; i < strlen(word); i++) {
printf("%c ", word[i]);
}
printf("\n"); // H E L L O
return 0;
}Practical Example: Student Grade Tracker#
#include <stdio.h>
#include <string.h>
int main() {
// Arrays for students
char names[3][50] = {"Alice", "Bob", "Charlie"};
int scores[3][3] = {
{85, 90, 78},
{92, 88, 85},
{78, 82, 80}
};
printf("=== Student Grades ===\n");
for (int i = 0; i < 3; i++) {
int sum = 0;
for (int j = 0; j < 3; j++) {
sum += scores[i][j];
}
float average = sum / 3.0;
printf("%s: Average = %.2f\n", names[i], average);
}
return 0;
}Output:
=== Student Grades ===
Alice: Average = 84.33
Bob: Average = 88.33
Charlie: Average = 80.00Common String Mistakes#
Mistake 1: Buffer Overflow#
char name[5];
scanf("%s", name);
// User enters "Alexander" - CRASH! (too long for array)
Solution: Limit input with format specifier:
scanf("%4s", name); // Maximum 4 characters
Mistake 2: Forgetting Null Terminator#
// ❌ Wrong - no null terminator
char name[] = {'A', 'l', 'i', 'c', 'e'};
// ✅ Correct - includes null terminator
char name[] = {'A', 'l', 'i', 'c', 'e', '\0'};Mistake 3: Using scanf() for Input with Spaces#
char name[50];
// ❌ scanf stops at first space
scanf("%s", name);
// ✅ Use fgets() for input with spaces
fgets(name, sizeof(name), stdin);Practice Exercises#
Exercise 1: Array Statistics#
Write a program that:
- Takes 10 numbers as input
- Finds the largest and smallest
- Calculates the average
- Counts how many numbers are above average
Exercise 2: Matrix Operations#
Write a program that:
- Creates a 3x3 matrix
- Finds the sum of all elements
- Finds the row sum
- Prints the results
Exercise 3: String Manipulation#
Write a program that:
- Reads a string from user
- Counts vowels and consonants
- Reverses the string
- Checks if it’s a palindrome
Summary#
✅ Learned 1D and 2D arrays
✅ Understood zero-based indexing
✅ Learned string basics
✅ Used common string functions (strlen, strcpy, strcat, strcmp)
✅ Iterated through arrays and strings
✅ Created practical programs with arrays
Key Points to Remember#
- Arrays are zero-indexed (first element is index 0)
- Arrays in loops:
for (int i = 0; i < length; i++) - Strings end with
\0null terminator - Use
%sfor strings, not&namein scanf - String functions require
#include <string.h> - Always check array bounds to avoid overflow
- 2D arrays:
array[row][column]
Next Steps#
Tomorrow we’ll learn about pointers - one of the most important concepts in C!