Neural Sync Active
Control Flow, Arrays, and Strings in C
Registry Synced
Control Flow, Arrays, and Strings in C
801 words
4 min read
Reading compass
Now · 🎯 Learning Objectives
Control Flow, Arrays, and Strings in C
🎯 Learning Objectives
- Use if/else, switch, loops (for, while, do-while)
- Declare and access 1D, 2D, and multidimensional arrays
- Manipulate strings using standard library functions
- Understand the relationship between arrays and pointers
1. Control Flow
1.1 Conditional Statements
c// if-else ladder int score = 85; if (score >= 90) { printf("A grade\n"); } else if (score >= 80) { printf("B grade\n"); // This executes } else { printf("C grade\n"); } // switch statement switch (score / 10) { case 10: case 9: printf("A\n"); break; case 8: printf("B\n"); break; default: printf("Below B\n"); }
1.2 Loops
c// for loop for (int i = 0; i < 10; i++) { printf("%d ", i); } // while loop int i = 0; while (i < 10) { printf("%d ", i++); } // do-while (executes at least once) int j = 0; do { printf("%d ", j++); } while (j < 10);
1.3 break, continue, goto
cfor (int i = 0; i < 10; i++) { if (i == 3) continue; // Skip iteration (i=3 not printed) if (i == 7) break; // Exit loop (prints 0,1,2,4,5,6) printf("%d ", i); }
2. Arrays
2.1 1D Arrays
cint arr[5] = {10, 20, 30, 40, 50}; // Access and modify arr[0] = 100; // First element arr[4] = 500; // Last element int size = sizeof(arr) / sizeof(arr[0]); // 5 // Iterate for (int i = 0; i < size; i++) { printf("%d ", arr[i]); }
2.2 2D Arrays
cint matrix[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; // Access: matrix[row][col] printf("%d\n", matrix[1][2]); // 7 // Iterate (row-major order) for (int r = 0; r < 3; r++) { for (int c = 0; c < 4; c++) { printf("%3d ", matrix[r][c]); } printf("\n"); }
3. Strings
3.1 String Representation
Strings in C are null-terminated character arrays:
cchar str1[] = "hello"; // {'h','e','l','l','o','\0'} — 6 bytes char str2[6] = "hello"; // Same as above char str3[] = {'h','e','l','l','o','\0'}; // Explicit printf("Length: %zu\n", strlen(str1)); // 5 (not counting null) printf("Size: %zu\n", sizeof(str1)); // 6 (including null)
3.2 String Functions
c#include <string.h> char src[] = "Hello "; char dest[50]; strcpy(dest, src); // Copy src to dest strcat(dest, "World!"); // Concatenate: "Hello World!" int cmp = strcmp("abc", "abd"); // Negative (-1): "abc" < "abd" int len = strlen(dest); // 12 // Safe versions (with buffer size) strncpy(dest, src, 49); strncat(dest, "World!", 49); strncmp("abc", "abd", 2); // Compares only first 2 chars (equal → 0)
3.3 String Input
cchar buffer[100]; // UNSAFE: no bounds check gets(buffer); // SAFE: reads at most 99 chars fgets(buffer, sizeof(buffer), stdin); // Parse input int num; char word[50]; sscanf("42 hello", "%d %s", &num, word); // num=42, word="hello"
4. 📝 Practice Questions
Q1: Write a function that reverses a string in place.cvoid reverse(char *s) { int len = strlen(s); for (int i = 0; i < len / 2; i++) { char temp = s[i]; s[i] = s[len - 1 - i]; s[len - 1 - i] = temp; } }Q2: Why is it dangerous to usegets()?Answer:gets()has NO bounds checking. If the input exceeds the buffer size, it causes a buffer overflow, overwriting adjacent memory. This is a common security vulnerability. Always usefgets()instead. Q3: What is the output ofprintf("%d", sizeof("abc\0def"))?Answer: 8. The string "abc\0def" has characters a,b,c,\0,d,e,f = 7 characters plus the terminating null = 8. The embedded \0 is just another byte in the array. Q4: Givenint arr[5] = {10,20,30,40,50};, what isarr[5]?Answer: Undefined behavior.arr[5]is one past the end of the array. It accesses whatever memory follows the array (could be another variable, could cause a crash). Q5: Write a program that counts the frequency of each character in a string.cvoid count_chars(const char *str) { int freq[256] = {0}; for (int i = 0; str[i]; i++) { freq[(unsigned char)str[i]]++; } for (int i = 0; i < 256; i++) { if (freq[i] > 0) { printf("'%c': %d\n", i, freq[i]); } } }
5. 🔗 Cross-References
- Week 3 - Pointers: Array-pointer equivalence
- Week 4 - Functions: Passing arrays to functions
- BSCS3005 Week 7 - File I/O: Reading/writing strings to files Join Discord PreviousMemory LayoutNextPointers Deep Dive