ARRAYS AND FUNCTIONS
The entire array can be passed on to a function in C++. An
array name can be used as an argument for the function declaration. No
subscripts or square brackets are required to invoke a function using arrays.
The following
program illustrates how to invoke a function using an array declaration.
#include <iostream.h>
#defince MAX 100
void main (void)
{
int sumarray (int a[], int n);
int a [MAX];
int sum;
sum = sumarray (a,n);
}
int sumarray (int x[], int max)
{
//local variable declaration, if any
//body of the function
return (value);
}
PROGRAM
A program to read a set of numbers from the keyboard and
sort out the given array of elements in ascending order using a function.
//example 5.5
#include <iostream.h>
#define MAX 100
int a [MAX]
#include <iostream.h>
void main (void)
{
void input (void); //function declaration
input ();
}
void input ()
{
void input (int a[], int n);
int short (int a[], int n);
int a [MAX];
int n;
cout << “How many numbers are in
the array ? “ << endl;
cin >> n;
cout << “Enter the elements “
<< endl;
for (int i = 0; i <= n-1; ++i) {
cin >> a[i];
}
cout << “Unsorted array”
<< endl;
output (a,n);
sort (a,n);
cout << endl;
cout << “Sorted array “ <<
endl;
output (a,n);
}
void output (int a[], int n)
{
cout << endl;
for (int i = 0; i <= n-1; ++i) {
cout << a[i] <<
‘\t’;
}
}
int sort (int a[], int n)
{
int temp;
for (int i = 0; i <= n-1;
++i) {
for (int j = 0; j <= n-2;
++j)
if (a[i] < a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
} // end of sorting
Output of the above
program
How many numbers are in the array ?
7
Enter the elements
11
22 -56 78
-90 44 55
Unsorted array
11
22 -56 78
-90 44 55
Sorted array
-90
-56 11 22
44 55 78
PROGRAM
A program to read a set of numbers from the keyboard and to
find out the sum of all elements of the given array using function.
//example 5.6
#include <iostream.h>
#define MAX 100
void main (void)
{
void output (int a[], int n); //
function declaration
int sumarray (int a[], int n);
int a [MAX];
int i,n,sum;
cout << “how many numbers
are in the array ? “ << endl;
cin >> n;
cout << “Enter the elements
“ << endl;
for (i = 0; i <= n-1; ++i) {
cin >> a[i];
}
cout << “output from the
array” <<endl;
output (a,n);
sum = sumarray (a,n);
cout << endl;
cout << “som of the values
of the array =” << sum;
}
void output (int a[], int n)
{
cout << endl;
for (int i = 0; i <= n-1;
++i) {
cout << a[i] <<
‘\t’;
}
}
int sumarray (int x[] ,int max)
{
int value = 0;
for (int i = 0; i <= max-1;
++i) {
value = value +x[i];
}
return (value);
}
Output of the above
program
How many numbers are in the array ?
5
Enter the elements
11
23 45 66
77
Output from the array
11
23 45 66 77
Sum of the values of the array =222
No comments:
Post a Comment