Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.
You are here - Home > Programming > C > Basics

Passing Array Elements


As we pass values to the function in the same way we can also pass array elements to the function.

There are two ways to pass array elements

  • Call by value - In which value of the array element is copied into the calling function.
  • Call by reference - While here the address location number is passed to the calling function.

Source code

  • //Passing array elements to function using call by value
  • #include <stdio.h>
  • #include <conio.h>
  • void main()
  • {
  • int i,arr[]={23,43,2,423,34,53};
  • clrscr();
  • for(i=0;i<=5;i++)
  • {
  • display(arr[i]);
  • }
  • getch();
  • }
  • display(int b)
  • {
  • printf("%d\n",b);
  • return 0;
  • }

Program working steps

  • First line is the comment, 2nd and 3rd lines are preprocessor directives, which contains definition of functions like clrscr(), getch(), printf() scanf() etc.
  • From void main() function the program execution starts.
  • Declaration of integer variable i and array arr initialization of six elements as defining the size of array is optional, so we have not declared the size.
  • clrscr() for clearing of screen.
  • To pass value of each array element to the function, we have used for loop which starts from index 0, checks the condition expression and then increments the index value.
  • When the loop starts it intializes the variable i to zero and then checks the condition whether it is true or not. If true it will execute the block of code, calling the display function.
  • On line no.11 display(arr[i]); is the calling function which passes the array value of index i. At the first iteration of for loop i value will be 0, so it will pass value of arr[0]. At function definition line no.15 passed value will be copied to variable b and thereafter implementing the block of code printing the value of b and returning back to the For loop.
  • After returning back to the For loop i value will be incrementd by 1 and now again the for loop condition is checked, And above point explanation goes on repeating till the condition becomes false executing the display function and printing the values of array elements arr.
  • At Last is the getch function to wait for the user to exit.

Tip Box

Passing array element index value should not exceed the array size less than one.


Terms of Use | Privacy Policy | Contact Us | Advertise
CodesandTutorials © 2014 All Rights Reserved