Cover Image for C Array Test
99 views

C Array Test

Testing arrays in C typically involves creating arrays, populating them with data, and performing operations or computations on the elements of the arrays. Here’s a simple example that demonstrates array creation, initialization, and basic testing in C:

C
#include <stdio.h>

int main() {
    // Declare and initialize an array of integers
    int numbers[] = {10, 20, 30, 40, 50};

    // Calculate the length of the array
    int length = sizeof(numbers) / sizeof(numbers[0]);

    // Print the array elements
    printf("Array elements: ");
    for (int i = 0; i < length; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    // Find the sum of array elements
    int sum = 0;
    for (int i = 0; i < length; i++) {
        sum += numbers[i];
    }
    printf("Sum of elements: %d\n", sum);

    // Search for a specific element (e.g., 30)
    int searchElement = 30;
    int found = 0;
    for (int i = 0; i < length; i++) {
        if (numbers[i] == searchElement) {
            found = 1;
            break;
        }
    }
    if (found) {
        printf("%d found in the array.\n", searchElement);
    } else {
        printf("%d not found in the array.\n", searchElement);
    }

    return 0;
}

In this example:

  1. We declare an array of integers called numbers and initialize it with values.
  2. We calculate the length of the array by dividing the size of the array in bytes by the size of one element in bytes.
  3. We iterate through the array to print its elements and calculate the sum of the elements.
  4. We search for a specific element (e.g., 30) by iterating through the array and setting a flag if the element is found.

This code demonstrates basic operations with arrays, including initialization, iteration, and searching for elements. You can modify and extend these tests based on your specific requirements for working with arrays in C programs.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS