return array in c
The variables that we used till now are capable to store only one value at a time. let us consider situation when we want to store 100 students name and student roll numbers, so it would be difficult to stores with previous data type its will be lengthy. Here the concept of Array useful to stores any type data of number of students or number of employees.
The array is a collection of elements of similar Type or data type. The data type of elements any valid data type in c such as int, char or float so the every elements of array share the same variable name is called as Array name and each element has different index number know as subscript.
Passing whole one dimensional(1-D) Array to a function
We can also pass whole array as an actual arguments to any function. The corresponding formal arguments in that function should be declared as an array variable with the same data type
main()
{
arr[20];
..........
..........
fun(arr); /* fun function call, array name is pass without bracket*/
0;
}
fun( val[20])
{
..............
..............
..............
}
|
In the formal argument it is optional to specify the size of the array. we can also write function definition like this
fun( val[])
{
…………..
…………..
…………..
}
|
We know that changes made in the formal arguments do not effect the actual arguments. But this is not case applying while passing array to function. The passing an array to a function is quite different from that a simple variable passing. we know that in the case of when a simple variable pass to a function, The called function create the copy of the simple variable and works on it. so by the called function any changes in the variable do not effect to the original variable. But when we pass array as an actual argument, then the called function actually gets access to the original array. let us take example this is program in which an array us passed to a function.
/* program to understand the effect of passing an array to a function*/
func(int value[]);
main()
{
i,arr[5]={1,4,5,6,4};
fun(arr);
printf("contents of Array are :");
(i=0;i<5;i++)
{
printf("%d \n",arr[i]);
}
}
fun(int value[])
{
sum=0,i;
(i=0;i<5;i++)
{
value[i]=value[i]*value[i];
sum=sum+value[i];
}
printf("Sum of square= %d",sum);
}
|
OUTPUT
sum of square=94
contents of Array are :1 16 25 36 16
|
Pass an Array to function as Pointer
pointpass( *arr)
{
i;
printf("Characters in Array are \n");
(i=0;i<6;i++)
{
printf("%c",arr[i]);
printf("\n");
}
}
main()
{
arr[6]={'N','I','T','I','S','H'};
pointpass(arr);
0;
}
|
Return array in c programming
*returnArry()
{
arr[6],i;
printf("Enter the Elements in Array");
(i=0;i<6;i++)
{
scanf(&arr[i]);
}
arr;
}
main()
{
*result,i;
result=returnArry();
printf("Elements of Array are \n ");
(i=0;i<6;i++)
{
printf(result[i]);
}
0;
}
|