Group1 Arrays
Group1 Arrays
❖ ---
- Indexing: Arrays are zero-indexed, meaning the first element is at index 0, the
second at index 1, and so on.
❖ Example:
❖ c
❖ int arr[5] = {10, 20, 30, 40, 50};
- arr[0] = 10
- arr[1] = 20
❖ Types of Arrays
- 1D Array (One-Dimensional Array): A simple list of elements.
- Example:
❖ c
❖ int arr[3] = {1, 2, 3};
Array Operations
❖ Insertion:
- Adding an element at a specific index.
❖ c
❖ arr[2] = 25; // Inserts 25 at index 2
❖ Access:
- Accessing elements using index.
❖ c
❖ printf("%d", arr[2]); // Outputs 25
❖ Traversal:
- Visiting each element of the array sequentially.
❖ c
❖ for (int i = 0; i < 5; i++) {
❖ printf("%d ", arr[i]);
❖ }
❖ Update:
- Modifyingan existing element.
❖ c
❖ arr[3] = 45; // Updates the value at index 3
❖ Deletion
- Removing an element at a specific index (not supported directly, can shift
elements)
Advantages of Arrays
❖ Efficient Access: Random access to any element using its index in constant time O(1).
Disadvantages of Arrays
❖ Fixed Size: Once declared, the size of an array cannot be changed dynamically.
Arrays:
Linked Lists:
Applications of Arrays
Storing lists of numbers, characters, or other data types.
epresenting graphs.
Note: While arrays are a fundamental data structure, they may not be the most suitable choice for all
scenarios. Other data structures like linked lists, stacks, queues, and trees may be more appropriate
depending on the specific requirements.
Practical Examples
❖ #include <stdio.h>
❖ int main() {
❖ int arr[3] = {10, 20, 30};
❖ printf("Element at index 1: %d\n", arr[1]); // Outputs 20
❖ return 0;
❖ }
❖ int main() {
❖ int arr[5] = {1, 2, 3, 4, 5};
❖ for (int i = 0; i < 5; i++) {
❖ printf("%d ", arr[i]);
❖ }
❖ return 0;
❖ }
❖ Example 3: Two-Dimensional Array
❖ c
❖ #include <stdio.h>
❖ int main() {
❖ int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
❖ for (int i = 0; i < 2; i++) {
❖ for (int j = 0; j < 3; j++) {
❖ printf("%d ", matrix[i][j]);
❖ }
❖ printf("\n");
❖ }
❖ return 0;
❖ }
❖ Conclusion
- Arrays are a foundational data structure that provides efficient random access
to elements.
- While they have limitations, such as fixed size, they are easy to use and crucial
for managing collections of elements in a program.
- Understanding arrays is essential before exploring more complex data
structures like linked lists, stacks, and queues.