Various operations on array
In C programming, arrays are used to store a collection of elements of the same data type. Arrays allow you to perform various operations efficiently. Here are some common operations you can perform on arrays:
1. Declaring an array:
// Syntax: data_type array_name[array_size];
int numbers[5]; // Declares an integer array with 5 elements
2. Initializing an array:
int numbers[5] = {1, 2, 3, 4, 5}; // Initializes the array with specific values
3. Accessing elements of an array:
int element = numbers[index]; // Access the element at the specified index (index starts from 0)
4. Modifying elements of an array:
numbers[index] = new_value; // Modifies the element at the specified index
5. Looping through an array:
// Using a for loop
for (int i = 0; i < array_size; i++) {
// Access and process elements using numbers[i]
}
// Using a while loop
int i = 0;
while (i < array_size) {
// Access and process elements using numbers[i]
i++;
}
6. Finding the length of an array:
int array_length = sizeof(numbers) / sizeof(numbers[0]);
7. Summing elements of an array:
int sum = 0;
for (int i = 0; i < array_size; i++) {
sum += numbers[i];
}
8. Finding the maximum and minimum elements of an array:
int max = numbers[0];
int min = numbers[0];
for (int i = 1; i < array_size; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
if (numbers[i] < min) {
min = numbers[i];
}
}
9. Searching for an element in an array (linear search):
int search_element = 42;
int found_index = -1; // Initialize with a value indicating the element is not found
for (int i = 0; i < array_size; i++) {
if (numbers[i] == search_element) {
found_index = i;
break; // Stop searching once the element is found
}
}
10. Sorting elements of an array (using bubble sort as an example):
for (int i = 0; i < array_size - 1; i++) {
for (int j = 0; j < array_size - i - 1; j++) {
if (numbers[j] > numbers[j + 1]) {
// Swap the elements
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}