Arrays as Function Arguments
Part of the Fundamentals section of Coddy's C journey — lesson 58 of 63.
Arrays can be passed as arguments to functions in C. When an array is passed to a function, what is actually passed is the memory address of the first element.
Declare an array and a function that takes it as an argument:
void displayArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}Create an array and call the function:
int numbers[5] = {10, 20, 30, 40, 50};
displayArray(numbers, 5);When you pass an array to a function, changes made to the array inside the function will affect the original array:
void doubleValues(int arr[], int size) {
for(int i = 0; i < size; i++) {
arr[i] = arr[i] * 2;
}
}
// Call the function
doubleValues(numbers, 5);
// Now numbers contains: {20, 40, 60, 80, 100}Challenge
EasyCreate a function named sumArray that takes two arguments:
- An integer array (arr).
- An integer (size) representing the size of the array.
The function should calculate and return the sum of all elements in the array.
Then, in the main function:
- Read an integer n (the size of the array).
- Read n integers and store them in an array.
- Call the sumArray function with the array.
- Print the sum in the format: "Sum: X" (where X is the sum).
Cheat sheet
Arrays are passed to functions by reference (memory address of first element):
void displayArray(int arr[], int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}Call the function with array name and size:
int numbers[5] = {10, 20, 30, 40, 50};
displayArray(numbers, 5);Changes made to array inside function affect the original array:
void doubleValues(int arr[], int size) {
for(int i = 0; i < size; i++) {
arr[i] = arr[i] * 2;
}
}Try it yourself
#include <stdio.h>
// Write your sumArray function here
int main() {
int n;
scanf("%d", &n);
int arr[n];
for(int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Call the sumArray function and print the result
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2Variables
Data TypesIntegerFloat - DoubleCharactersBooleansConstantsprintf BasicsVariable Naming RulesType Casting Part 1Type Casting Part 2Recap Challenge8Arrays
Declaring ArraysAccessing ElementsModifying ElementsMultidimensional ArraysRecap Challenge #1Arrays as Function ArgumentsArray AlgorithmsRecap Challenge #23Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge