function for get array from the user
#include <stdio.h>
void getArray()
{
printf("Enter size of array: ");
scanf("%d",&n);
printf("Enter %d elements in the array : ", n);
for(i=0;i<n;i )
{
scanf("%d", &a[i]);
}
}
function for display array
void displayArray(){
printf("\nElements in array are: ");
for(i=0;i<n;i )
{
printf("%d ", a[i]);
}
}
Both functions are called in the main
int main(){
int a[1000],i,n;
getArray();
displayArray();
return 0;
}
The problem is how to pass the array that we get from the user to the display array function and both functions can be called in the main and also the array want to declare in the main function
CodePudding user response:
You can pass that shared variable as argument. Also return and use the returned value if reference not having valid data. Or else you need to pass this argument as reference instead of value like this.
#include <stdio.h>
int[] getArray(int a[])
{
printf("Enter size of array: ");
scanf("%d",&n);
printf("Enter %d elements in the array : ", n);
for(i=0;i<n;i )
{
scanf("%d", &a[i]);
}
return a;
}
function for display array
void displayArray(int a[]){
printf("\nElements in array are: ");
for(i=0;i<n;i )
{
printf("%d ", a[i]);
}
}
Both functions are called in the main
int main(){
int a[1000],i,n;
a = getArray(a);
displayArray();
return 0;
}
CodePudding user response:
An example that does not handle input errors. In order for your functions to have knowledge of the array, you must send them its address as well as its size.
#include <stdio.h>
int getArray(int a[], int size_max)
{
int n;
printf("Enter size of array: ");
while(1)
{
scanf("%d",&n);
if(n>size_max) printf("The size must be less than %d: ", size_max);
else break;
}
printf("Enter %d elements in the array : ", n);
for(int i=0; i<n; i ) scanf("%d", &a[i]);
return n;
}
void displayArray(int a[], int n)
{
printf("\nElements in array are: ");
for(int i=0; i<n; i ) printf("%d ", a[i]);
}
int main()
{
int a[1000];
int n = getArray(a, 1000);
displayArray(a, n);
return 0;
}