C Programs on 1D Arrays

Here are some simple C programs that demonstrate operations on one-dimensional (1D) arrays:

1. Sum of Array Elements:

This program calculates the sum of elements in a 1D integer array.


#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int sum = 0;

    for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++) {
        sum += numbers[i];
    }

    printf("Sum of array elements: %d\n", sum);
    return 0;
}
    

2. Finding the Maximum Element:

This program finds the maximum element in a 1D integer array.


#include <stdio.h>

int main() {
    int numbers[] = {15, 6, 27, 8, 12};
    int max = numbers[0];

    for (int i = 1; i < sizeof(numbers) / sizeof(numbers[0]); i++) {
        if (numbers[i] > max) {
            max = numbers[i];
        }
    }

    printf("Maximum element in the array: %d\n", max);
    return 0;
}
    

3. Copying One Array to Another:

This program copies the elements of one 1D integer array to another.


#include <stdio.h>

int main() {
    int source[] = {5, 10, 15, 20, 25};
    int destination[5];

    for (int i = 0; i < sizeof(source) / sizeof(source[0]); i++) {
        destination[i] = source[i];
    }

    printf("Copied array elements:\n");
    for (int i = 0; i < sizeof(destination) / sizeof(destination[0]); i++) {
        printf("%d ", destination[i]);
    }

    return 0;
}
    

4. Linear Search in Array:

This program performs a linear search to find a specific element in a 1D integer array.


#include <stdio.h>

int main() {
    int numbers[] = {8, 3, 11, 5, 2};
    int target = 11;
    int found = 0;

    for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++) {
        if (numbers[i] == target) {
            found = 1;
            break;
        }
    }

    if (found) {
        printf("Element %d found in the array.\n", target);
    } else {
        printf("Element %d not found in the array.\n", target);
    }

    return 0;
}
    

You can compile and run these programs to see the results. They cover common operations on 1D arrays such as summing elements, finding the maximum element, copying arrays, and searching for elements.