Question.5
A developer left-rotates an array by k positions using the brute-force approach. The array has 5 elements. He calls rotate_left(arr, 5, 7):
void rotate_left(int arr[], int n, int k) {
for (int r = 0; r < k; r++) {
int temp = arr[0];
for (int i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[n - 1] = temp;
}
}The code works, but what's the performance problem?
An array in C is a contiguous block of memory that stores multiple elements of the same data type. It allows you to:
Array Declaration
int numbers[10]; // Array of 10 integers
uint8_t buffer[32]; // 32-byte buffer (commonly used in firmware)
Declares a fixed-size array — memory is allocated statically.
Array Initialization
int values[4] = {10, 20, 30, 40}; // full initialization
int empty[4] = {0}; // all elements = 0
char message[] = "Hi"; // string-style initIf you skip the size (like message[ ]) , the compiler counts the size automatically.
Accessing Array Elements
int arr[3] = {5, 10, 15};
printf("%d", arr[1]); // prints 10
arr[2] = 20; // modify element at index 2The index starts from 0. Always ensure you stay within 0 to n-1.
Array Size with sizeof()
int arr[5];
int total_bytes = sizeof(arr); // e.g., 20 if int = 4 bytes
int element_bytes = sizeof(arr[0]); // gives size of int i.e. 4 bytes
int element_count = sizeof(arr) / sizeof(arr[0]); // gives 5This only works within the same scope where the array is declared (not when passed to a function).
int arr[4] = {10, 20, 30, 40};
Assuming the starting address is 0x2000, the memory looks like:
| Address | Value |
|---|---|
| 0x2000 | 10 |
| 0x2004 | 20 |
| 0x2008 | 30 |
| 0x200C | 40 |
Each int = 4 bytes (on most systems).
In embedded systems, arrays are used for: