Array to Function in C
×


Array to Function in C

314

 Array to function in C Language is passed when we need to pass a list of parameters to the function.

Array to function in C is passed in two ways.

1 Call by value

passing Array as a parameter in the function.

When you pass an array to a function using call by value it copies all parameters of the array directly.

So, any changes made to the array inside the function will not affect the original array.


2 Call by Reference

Passing a pointer to the function to hold the base address of the array.

When you pass an array to the function using call by reference it will give the memory location of the array.

So, any changes made to the array inside the function will directly affect the original array.

Program to pass the array to function using call by value

//Program to pass the array to function using call by value
#include <stdio.h>
void arrayelement(int array[], int A) {

for (int i = 0; i < A; i++) {
printf("%d ", array[i]);
}
printf("\n");
}

int main() {
int arr[] = {6, 7, 8, 9, 10};
int A= sizeof(arr) / sizeof(arr[0]);

printf("Original Array: ");

arrayelement(arr, A);
return 0;
}

Output:

Original Array: 6 7 8 9 10

Program to pass the array to function using call by Reference

//Program to pass the array to function using call by Reference
#include<stdio.h> 

// Function to modify array elements by adding 5 to each element
void addFiveToElements(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        arr[i] += 5;
    }
}

// Function to print the elements of an array
void printArray(int *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

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

    printf("Original Array: ");
    printArray(numbers, size);  // Print original array

    addFiveToElements(numbers, size);  // Call function to add 5 to each element

    printf("Modified Array: ");
    printArray(numbers, size);  // Print modified array

    return 0;
}

Output:

Original Array: 1 2 3 4 5 
Modified Array: 6 7 8 9 10 


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments