What is a arrays and function in python

In C programming, you can pass en entire array to functions. Before we learn that, let's see how you can pass individual elements of an array to functions.

Passing individual array elements

Example 1: Passing an array

  1. #include <stdio.h>
  2. void display(int age1, int age2)
  3. {
  4. printf("%d\n", age1);
  5. printf("%d\n", age2);
  6. }
  7. int main()
  8. {
  9. int ageArray[] = {2, 8, 4, 12};
  10. // Passing second and third elements to display()
  11. display(ageArray[1], ageArray[2]);
  12. return 0;
  13. }
Output
8
4

Example 2: Passing arrays to functions

  1. // Program to calculate the sum of array elements by passing to a function
  2. #include <stdio.h>
  3. float calculateSum(float age[]);
  4. int main() {
  5. float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
  6. // age array is passed to calculateSum()
  7. result = calculateSum(age);
  8. printf("Result = %.2f", result);
  9. return 0;
  10. }
  11. float calculateSum(float age[]) {
  12. float sum = 0.0;
  13. for (int i = 0; i < 6; ++i) {
  14. sum += age[i];
  15. }
  16. return sum;
  17. }
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an argument.
  1. result = calculateSum(age);
However, notice the use of [] in the function definition.
  1. float calculateSum(float age[]) {
  2. ... ..
  3. }
This informs the compiler that you are passing a one-dimensional array to the function.



Post a Comment

0 Comments