Arrays and Strings
1 The Need for Tabular Data
In many real-world problems, we often deal with collections of similar data. Examples include:
-
Storing the scores of all students in a class.
-
Tracking daily temperatures over a week.
-
Representing an image as a grid of pixel colors.
Instead of using separate variables for each piece of data, arrays allow us to store multiple values under one variable name.
2 One-Dimensional Arrays (1D)
A one-dimensional array is a collection of elements, all of the same type, stored in contiguous memory locations. Each element in the array can be accessed using an index.
3 Indexing, Accessing, and Manipulating 1D Arrays
In most programming languages, array indexing starts from 0 or To access or modify an element, you use the array name along with its index.
Vars arr: array[5] of integer; sum, i: integer Start sum ← 0 For i ← 1 to 5 Do read (arr[i]) sum ← sum + arr[i] EndFor write (sum) End
4 Two-Dimensional Arrays (2D) or Matrices
A two-dimensional array is a grid of elements arranged in rows and columns. It is particularly useful for tabular data or matrix operations.
Vars matrix: array[3, 3] of integer; sum, i, j: integer Start sum ← 0 For i ← 1 to 3 Do For j ← 1 to 3 Do read (matrix[i, j]) sum ← sum + matrix[i, j] EndFor EndFor write (sum) End
5 Applications of 1D and 2D Arrays
-
Calculating the average of a list of numbers using a 1D array.
-
Performing matrix addition or multiplication with 2D arrays.
-
Storing and manipulating game board states using a 2D array.
6 Strings: A Special Case of 1D Arrays
A string is a sequence of characters stored in a 1D array. Strings are commonly used in text processing and data manipulation tasks.
Vars str1, str2, result: array[50] of character; i, j: integer Start read (str1) read (str2) i ← 1 While str1[i] ≠ ’\0’ Do result[i] ← str1[i] i ← i + 1 EndWhile j ← 1 While str2[j] ≠ ’\0’ Do result[i] ← str2[j] i ← i + 1 j ← j + 1 EndWhile result[i] ← ’\0’ write (result) End
7 Applications of Strings
-
Checking and comparing user input (e.g., passwords).
-
Searching for substrings within larger text data.
-
Formatting and displaying textual information.
8 Arrays and Strings in C
8.1 Arrays in C
Arrays are data structures that allow storing multiple values of the same type under a single variable name. They are useful for handling collections of data where individual elements are accessed by an index. An array’s elements are stored sequentially in memory, enabling efficient access through indexing.
-
Definition: An array is a collection of items stored at contiguous memory locations. The idea is to allocate memory for a fixed-size list of items.
-
Accessing Elements: Elements of an array are accessed using an index, typically starting from 0 in many programming languages, such as C.
-
Limitations: Once the size of an array is defined, it cannot be resized. This characteristic makes arrays static structures.
In C, arrays are declared by specifying the data type of elements and the size of the array. Elements are accessed by their index positions, and C does not perform bounds-checking for array indices, which means accessing elements outside the array’s limits can cause undefined behavior.
8.1.1 Syntax for Declaring Arrays
dataType arrayName[size];
Here:
-
dataTypeis the type of elements in the array (e.g.,int,float). -
arrayNameis the name of the array. -
sizespecifies the number of elements.
int arr[5]; // Declares an integer array of size 5
-
Declaration: To declare an array, specify the type and the size of the array in square brackets.
-
Initialization: Arrays can be initialized at the time of declaration. Example:
int arr[5] = {1, 2, 3, 4, 5}; -
Accessing Elements: Use the index to access elements. Example:
int x = arr[2]; // Accesses the third element (index 2)
Example: Declaring and Initializing an Array
#include <stdio.h>
int main() {
// Declare an array of size 5
int numbers[5] = {10, 20, 30, 40, 50};
// Access and modify elements
printf("First element: %d\n", numbers[0]);
numbers[2] = 25; // Update the third element
printf("Updated third element: %d\n", numbers[2]);
return 0;
}
Output:
First element: 10
Updated third element: 25
8.1.2 Common Operations on Arrays
Example: Iterating Through an Array
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
// Print each element of the array
for (int i = 0; i < 5; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}
Output:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
8.1.3 Multidimensional Arrays
Multidimensional arrays are arrays of arrays. In C, the most common type of multidimensional array is the two-dimensional array, which can be visualized as a matrix.
int matrix[3][3]; // Declares a 3x3 matrix of integers
-
Declaration: Specify each dimension in square brackets.
-
Initialization: Multidimensional arrays can be initialized in a nested way.
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; -
Accessing Elements: Access elements by specifying row and column indices.
int x = matrix[1][2]; // Accesses the element in the second row, third column
Example: 2D Array (Matrix)
#include <stdio.h>
int main() {
// Declare and initialize a 2D array
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
// Print the matrix
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
8.2 Strings in C
A string is a sequence of characters, commonly used to represent text data. In many programming languages, strings are stored as arrays of characters, terminated by a special character (e.g., the null character in C).
-
Definition: A string is a sequence of characters stored in contiguous memory, often terminated with a null character (
\0) in C. -
Usage: Strings are used to represent textual data such as names, addresses, and other readable content.
A string in C is an array of characters terminated by a null character (’\0’). Strings are used to represent text.
8.2.1 Declaring Strings
Strings can be declared as a character array:
char str[20]; // Can hold up to 19 characters + null terminator
8.2.2 Initializing Strings
Strings can be initialized in the following ways:
char str1[20] = "Hello";
char str2[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Explicit null terminator
Example: Working with Strings
#include <stdio.h>
int main() {
char greeting[20] = "Hello, World!";
// Print the string
printf("Greeting: %s\n", greeting);
// Modify the string
greeting[7] = 'C';
greeting[8] = '\0'; // End the string early
printf("Modified Greeting: %s\n", greeting);
return 0;
}
Output:
Greeting: Hello, World!
Modified Greeting: Hello, C
8.2.3 Assigning a Value to a String
There are multiple ways to assign a value to a string, depending on how it is defined.
8.2.3.1 Initializing a String at Declaration
Using a Character Array:
char str1[] = "Hello, World!"; // Includes the null terminator
char str2[20] = "Hello"; // Explicit size, shorter string
Using a Character Pointer (Next Semester):
char *str = "Hello, World!"; // Points to a string literal in read-only memory
Note: Strings defined as pointers point to read-only memory and cannot be modified.
8.2.3.2 Assigning a Value After Declaration
For a Character Array: You can use the strcpy function from the <string.h> library:
#include <string.h>
char str[20];
strcpy(str, "Hello, World!");
For a Character Pointer: A pointer can point to a string literal directly:
char *str;
str = "Hello, World!";
Caution: The memory pointed to by the pointer is read-only, and modifying it will cause undefined behavior.
Examples
Let’s examine the following ways of declaring strings.
-
char name[] = "nice";(automatic sizing) -
char name[20] = "nice";(explicit sizing)
The difference lies in how memory is allocated and how the string can be used.
1. char name[] = "nice";
In this case, the compiler automatically determines the size of the array based on the string literal. The array size will be 5 (4 characters for ’n’, ’i’, ’c’, ’e’ and 1 for the null terminator ’ 0’).
Memory Layout
| 'n' | 'i' | 'c' | 'e' | '\0' |
Key Features
-
The array is sized exactly to fit the string.
-
Modifications are allowed within the array bounds, but you cannot store a longer string since there’s no extra space.
2. char name[20] = "nice";
Here, you explicitly allocate memory for 20 characters. The first 5 positions are used for the string "nice" (4 characters + null terminator), and the remaining 15 positions are uninitialized unless explicitly set.
Memory Layout
| 'n' | 'i' | 'c' | 'e' | '\0' | ? | ? | ... (15 uninitialized bytes) |
Key Features
-
Extra space allows you to store longer strings (up to 19 characters + null terminator).
-
Useful when you plan to modify or assign new values to the string dynamically.
Comparison Table
| Feature | char name[] = "nice"; |
char name[20] = "nice"; |
|---|---|---|
| Array Size | Determined automatically (5) | Fixed at 20 |
| Null Terminator | Present at the end | Present at position 5; rest uninitialized |
| Modification | Limited to 4 characters | Can store up to 19 characters |
| Memory Usage | Minimal | Extra memory allocated |
| Flexibility | Fixed size | Can hold longer strings later |
More Examples
Example 1: char name[] = "nice";
#include <stdio.h>
int main() {
char name[] = "nice";
printf("String: %s\n", name); // Prints "nice"
// Modifying within bounds
name[1] = 'o'; // Changes "nice" to "noce"
printf("Modified String: %s\n", name);
// Attempting to add more characters (unsafe, may cause undefined behavior)
// strcpy(name, "longer_string"); // Error: no extra space available
return 0;
}
Output:
String: nice
Modified String: noce
Example 2: char name[20] = "nice";
#include <stdio.h>
#include <string.h>
int main() {
char name[20] = "nice";
printf("String: %s\n", name); // Prints "nice"
// Modifying within bounds
name[1] = 'o'; // Changes "nice" to "noce"
printf("Modified String: %s\n", name);
// Adding a longer string
strcpy(name, "longer_string"); // Safe: enough space for 20 characters
printf("New String: %s\n", name);
return 0;
}
Output:
String: nice
Modified String: noce
New String: longer_string
Conclusion
-
Use
char name[] = "nice";when the string is fixed and you want minimal memory usage. -
Use
char name[20] = "nice";when you expect to modify or expand the string later, as it provides flexibility with extra space.
8.2.4 Common Operations on Strings
String Functions in <string.h>
C provides a standard library for string manipulation. Some common functions include:
-
strlen(str): Returns the length of the string. -
strcpy(dest, src): Copies a string. -
strcat(dest, src): Concatenates two strings. -
strcmp(str1, str2): Compares two strings.
Example: Using String Functions
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
// String concatenation
strcat(str1, str2);
printf("Concatenated String: %s\n", str1);
// String comparison
if (strcmp(str1, "HelloWorld") == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
return 0;
}
Output:
Concatenated String: HelloWorld
Strings are equal.
char str[6] = "Hello"; // Allocates space for "Hello\textbackslash0"
-
Declaration: Strings are declared as character arrays.
-
Accessing Characters: Individual characters can be accessed by index.
char c = str[1]; // Accesses the second character 'e' -
Functions: C provides functions like
strlento determine string length,strcpyto copy strings, andstrcatto concatenate strings.
Examples and Applications
-
Single-Dimensional Array Example: Summing all elements in an array.
int sum = 0; for (int i = 0; i < 5; i++) { sum += arr[i]; } -
String Example: Concatenating two strings.
char str1[] = "Hello, "; char str2[] = "World!"; strcat(str1, str2); // str1 now contains "Hello, World!" -
Two-Dimensional Array Example: Transposing a matrix.
int transpose[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { transpose[j][i] = matrix[i][j]; } }