← C EnglishChapter 06 of 13

Arrays and Strings

## Learning Objectives - Create and initialize arrays - Access and modify array elements - Work with strings - Master array operations ## Declaring Arrays ### Syntax ```c int numbers[5]; // Declaration int numbers[5] = {0}; // Declaration with initialization ``` ### Initialization ```c // By size (elements zero-initialized) int numbers[5] = {0}; // Result: [0, 0, 0, 0, 0] // With values int numbers[5] = {1, 2, 3, 4, 5}; // Partial initialization (rest are 0) int numbers[5] = {1, 2}; // Result: [1, 2, 0, 0, 0] // Size inferred from initializer int numbers[] = {1, 2, 3, 4, 5}; ``` ### Default Initialization ```c int numbers[3]; // Contains garbage values (undefined) int numbers[3] = {0}; // All elements = 0 ``` ## Array Length ```c int numbers[] = {1, 2, 3, 4, 5}; int length = sizeof(numbers) / sizeof(numbers[0]); // 5 ``` ## Accessing Elements ### Index ```c int numbers[] = {10, 20, 30, 40, 50}; printf("%d\n", numbers[0]); // First element: 10 printf("%d\n", numbers[4]); // Last element: 50 printf("%d\n", numbers[sizeof(numbers)/sizeof(numbers[0]) - 1]); // Last element ``` ### Modifying Elements ```c int numbers[] = {10, 20, 30}; numbers[0] = 15; // Change first element numbers[2] = 35; // Change last element ``` ### Bounds Checking **Warning:** C does not check array bounds! ```c int numbers[3]; numbers[5] = 100; // No error! Undefined behavior numbers[-1] = 50; // No error! Undefined behavior ``` ## Iterating Arrays ### for Loop ```c int numbers[] = {1, 2, 3, 4, 5}; for (int i = 0; i < 5; i++) { printf("%d\n", numbers[i]); } ``` ### While Loop ```c int numbers[] = {1, 2, 3, 4, 5}; int i = 0; while (i < 5) { printf("%d\n", numbers[i]); i++; } ``` ## Common Operations ### Sum and Average ```c int numbers[] = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i < 5; i++) { sum += numbers[i]; } double average = (double) sum / 5; ``` ### Find Maximum ```c int numbers[] = {3, 7, 2, 9, 4}; int max = numbers[0]; for (int i = 1; i < 5; i++) { if (numbers[i] > max) { max = numbers[i]; } } ``` ### Count Matches ```c int numbers[] = {1, 2, 3, 2, 4, 2, 5}; int target = 2; int count = 0; for (int i = 0; i < 7; i++) { if (numbers[i] == target) { count++; } } ``` ## Sorting ### Bubble Sort ```c void bubbleSort(int arr[], int size) { for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } ``` ### Using qsort ```c #include int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main(void) { int numbers[] = {3, 1, 4, 1, 5, 9}; int size = sizeof(numbers) / sizeof(numbers[0]); qsort(numbers, size, sizeof(int), compare); return 0; } ``` ## Multi-Dimensional Arrays ### Declaration ```c int matrix[3][4]; // 3 rows, 4 columns ``` ### Multi-Dimensional Array Initialization ```c int matrix[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; ``` ### Accessing ```c printf("%d\n", matrix[0][0]); // First element: 1 printf("%d\n", matrix[2][3]); // Last element: 12 matrix[1][2] = 10; // Modify element ``` ### Iterating ```c for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } ``` ### Row-Major Order ```c int matrix[2][3] = {1, 2, 3, 4, 5, 6}; // Is stored as: // Row 0: [1, 2, 3] // Row 1: [4, 5, 6] ``` ## Strings ### String Basics ```c char name[] = "Hello"; // {'H', 'e', 'l', 'l', 'o', '\0'} ``` ### String Initialization ```c char str1[] = "Hello"; // With null terminator char str2[6] = "Hello"; // Explicit size char str3[10] = "Hello"; // Larger array (rest is '\0') ``` ### Character Array vs String Literal ```c char arr[] = "Hello"; // Mutable - can be modified char *ptr = "Hello"; // Points to read-only memory (undefined behavior to modify) ``` **Warning:** String literals are typically stored in read-only memory. ## String Functions (string.h) ### strlen - String Length ```c #include char str[] = "Hello"; size_t len = strlen(str); // 5 ``` ### strcpy - Copy String ```c #include char dest[20]; strcpy(dest, "Hello"); ``` ### strncpy - Copy N Characters ```c #include char dest[10]; strncpy(dest, "Hello World", sizeof(dest) - 1); dest[9] = '\0'; // Ensure null-terminated ``` ### strcat - Concatenate ```c #include char str[20] = "Hello"; strcat(str, " World"); // "Hello World" ``` ### strncat - Concatenate N Characters ```c #include char str[20] = "Hello"; strncat(str, " World!!!", 6); // "Hello World" ``` ### strcmp - Compare Strings ```c #include strcmp("abc", "abc"); // 0 (equal) strcmp("abc", "def"); // negative (< 0) strcmp("xyz", "abc"); // positive (> 0) ``` ### strncmp - Compare N Characters ```c #include strncmp("hello", "help", 3); // 0 (first 3 chars equal) ``` ## String Input ### scanf ```c char name[50]; scanf("%49s", name); // Reads until whitespace printf("%s\n", name); ``` ### fgets (Recommended) ```c #include char name[100]; fgets(name, sizeof(name), stdin); name[strcspn(name, "\n")] = '\0'; // Remove newline ``` ## String to Number ```c #include int i = atoi("42"); double d = atof("3.14"); long l = atol("123456"); ``` ### Safe Conversion (strtol, strtod) ```c #include char *endptr; int i = (int)strtol("123", &endptr, 10); if (*endptr != '\0') { // Conversion failed } double d = strtod("3.14", &endptr); ``` ## Common Patterns ### String Reverse ```c void reverse(char *str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { char temp = str[i]; str[i] = str[len - 1 - i]; str[len - 1 - i] = temp; } } ``` ### Palindrome Check ```c int isPalindrome(const char *str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { if (str[i] != str[len - 1 - i]) { return 0; } } return 1; } ``` ## Summary - Arrays: `type name[size]` or `type name[] = {values}` - Access: `array[index]` - Array size: `sizeof(array) / sizeof(array[0])` - Strings are char arrays ending with `\0` - Use `string.h` functions for string operations - Use `fgets()` for safe string input - C does not check array bounds

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →