Arrays and Strings in C - Exam Notes
Arrays and Strings are fundamental concepts in C, used to store and manipulate
data efficiently. Arrays store multiple values of the same data type, while strings are character
arrays used to handle text.
1. Array Declaration and Initialization
Array Declaration: Arrays are declared with a data type, name, and size.
Example: int arr[5]; // Declares an integer array with 5 elements.
Array Initialization: Arrays can be initialized at the time of declaration.
Example: int arr[5] = {1, 2, 3, 4, 5}; // Array is initialized with 5 values.
2. Bound Checking in Arrays
C does not perform automatic bound checking. Accessing elements outside the array
size may lead to undefined behavior. It is the programmer's responsibility to ensure valid
indexing.
3. One-Dimensional Array
One-dimensional arrays store data in a single row.
Example: int arr[5] = {10, 20, 30, 40, 50}; // Stores 5 elements.
4. Two-Dimensional Array
Two-dimensional arrays store data in rows and columns.
Example:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}}; // 2 rows and 3 columns.
Arrays and Strings in C - Exam Notes
5. Character Arrays and Strings
Character arrays store strings in C. A string is a sequence of characters
terminated with a null character '\0'.
Example: char str[6] = "Hello"; // 'Hello' is stored with an implicit null terminator.
Common String Functions:
1. strlen(str): Returns the length of the string.
2. strcpy(dest, src): Copies one string to another.
3. strcmp(str1, str2): Compares two strings.