C Pass Individual Array Elements

#include <stdio.h>

void processArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int array[] = {1, 2, 3, 4, 5};
    int length = sizeof(array) / sizeof(array[0]);

    processArray(array, length);

    return 0;
}

Explanation:

  • #include <stdio.h>: Includes the standard input-output header file for using input-output functions like printf.

  • void processArray(int arr[], int size): Declares a function named processArray that takes an integer array arr and an integer size as arguments. It does not return any value (void). This function prints the elements of the array passed to it.

  • for (int i = 0; i < size; i++) { printf("%d ", arr[i]); }: This for loop iterates through the elements of the array arr and prints each element using printf. It starts at index 0 and continues until i reaches size - 1.

  • printf("\n");: Prints a newline character after printing all the elements of the array, creating a line break in the output.

  • int main() { ... }: Defines the main function, the entry point of the program.

  • int array[] = {1, 2, 3, 4, 5};: Declares an integer array named array and initializes it with values {1, 2, 3, 4, 5}.

  • int length = sizeof(array) / sizeof(array[0]);: Calculates the number of elements in the array by dividing the total size of the array by the size of a single array element (sizeof(array) gives the total size of the array, and sizeof(array[0]) gives the size of one element).

  • processArray(array, length);: Calls the processArray function and passes the array and its length (length) as arguments.

  • return 0;: Indicates successful execution and termination of the main() function.