Arrays


 

Arrays are a fundamental data structure in computer programming that allow you to store a collection of data of the same type in contiguous memory locations. An array is a collection of elements of the same data type, each identified by an index or a subscript.

The elements in an array can be accessed by their index value. The first element in an array is typically indexed with 0, and the last element is indexed with n-1, where n is the total number of elements in the array.

Arrays can be used to represent a variety of data structures, including lists, stacks, and queues. They are useful for storing large amounts of data that can be accessed and processed quickly.

Here's an example of declaring and initializing an array of integers in C:


int arr[5] = {1, 2, 3, 4, 5};

In this example, we declare an array of integers called arr with 5 elements. We initialize the array with the values 1, 2, 3, 4, and 5.

To access an element in the array, we can use its index value:

int x = arr[0]; // Access the first element in the array
int y = arr[2]; // Access the third element in the array

Arrays can also be used to implement other data structures, such as matrices and strings. However, one limitation of arrays is that their size is fixed at the time of declaration, which means that you cannot change the size of an array dynamically during runtime.

Example:

#include <stdio.h>

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int sum = 0;
    float average;
    
    // Calculate the sum of all elements in the array
    for(int i = 0; i < 5; i++) {
        sum += arr[i];
    }
    
    // Calculate the average of all elements in the array
    average = (float) sum / 5;
    
    printf("The sum of all elements in the array is %d\n", sum);
    printf("The average of all elements in the array is %.2f\n", average);
    
    return 0;
}

In this program, we first declare and initialize an array of 5 integers called arr with the values 1, 2, 3, 4, and 5. We then calculate the sum of all elements in the array using a for loop, and store the result in the variable sum. Next, we calculate the average of all elements in the array by dividing the sum by the number of elements, and store the result in the variable average. Finally, we print out the values of sum and average using printf statements.

This program demonstrates some basic operations that can be performed on arrays, including declaring and initializing an array, accessing array elements using a for loop, and performing calculations using array elements.

Comments

Popular posts from this blog

TRAVELING SALESMAN USING BRANCH AND BOUND TECHNIQUE

BOOKS DETAILS USING C STRUCTURE

PASCAL TRIANGLE USING C