ARRAYS AND FUNCTIONS

Arrays are implicitly treated as constant pointers. Array elements can be passed as parameter to Function in TWO ways: Passing element by element OR Passing the whole array(Here number of elements also need to be passed)

1) Passing Individual Elements of an Array
All array-elements can be passed as individual elements to a function like any other variable. The array-element is passed as a value parameter i.e. any change in the formal-parameter will not affect the actual-parameter i.e. array-element. Here we use call by value method.
2) Passing the Whole Array

Here, the address of the array is passed as parameter. Thus here we use call by address value method. Here the formal parameters indirectly through addresses access the values of actual parameters. So, any changes in formal parameter imply there is a change in actual parameter.

Program to Read and Print One dimensional arrays using User Defined Functions & Global Declarations.

#include<stdio.h>
#include<conio.h>
void ReadArray( );
void PrintArray( );
int x[50], n;
int main()
{ clrscr();
printf("\n\tEnter number of elements of an array: ");
scanf("%d", &n);
ReadArray( );
PrintArray( );
getch(); return 0;
}
void ReadArray( )
{ int i;
printf("\n\tEnter %d Elements of an Array: ", n);
for(i = 0; i < n; i++)
scanf("%d", &x[i]);
}
void PrintArray( )
{ int i;
printf("\n\tThe %d Elements of an Array are: ", n);
for(i = 0; i < n; i++)
printf(" %d ", x[i]);
}

Program to illustrate passing individual elements of an array to a function.

#include<stdio.h>
void display(int a)
{
printf("%d", a);
}
void main()
{
int c[3]={2,3,4};
display(c[2]); //Passing array-element c[2] only.
}

Program to Read and Print One dimensional arrays using User Defined Functions By Passing Array: element by element.

#include<stdio.h>
#include<conio.h>
void PrintArray( int n) { printf(“ %d “, n); }
int main()
{ int x[50], n, i; clrscr();
printf("\n\tEnter number of elements : "); scanf("%d", &n);
printf("\n\tEnter %d Elements of an Array: ", n);
for(i = 0; i < n; i++) scanf("%d", &x[i]);
printf("\n\tThe %d Elements of an Array are: ", n);
for(i = 0; i < n; i++)
PrintArray(x[ i ]);
getch(); return 0;
}
ARRAYS AND FUNCTIONS ARRAYS AND FUNCTIONS Reviewed by Unknown on 04:44 Rating: 5

No comments:

Powered by Blogger.