Share
Explore BrainMass

Two important exercises with Arrays

Arrays are collections of elements of the same type. The elements of the array can be accessed using their position (index) in the array. Arrays may have several dimensions: they can be similar to lists (1-dimension), matrices (2-dimensions), cubes (3-dimensions) etc.
1. The first exercise involves a 1-dimensional array of integers and uses a function that returns the maximum value of the array. The program is not completely defined, the ?? should be replaced with the corresponding expressions in order to get the program work correctly.

Here is the program

#include <iostream>

using namespace std;

//declares the size of the array as a constant integer

const int SIZE = 10;

//declares the function that computes the maximum value

//the function returns an integer and has an array of integers as parameter

int max(int a[]);

int main()

{

//declares the array of integers having the size SIZE

int arrayone[SIZE];

int max_value;

//initializes each element of the array with the value of its index+1

for(int i=0; i<SIZE; i++)

arrayone[i] = i+1;

//call here the function that returns the maximum value

max_value = ??;

cout <<"The maximum element of the array is "<< max_value <<endl;

return(0);

}

int max(int a[])

{

int maximum;

//compare each element with maximum and assign its value to maximum if //greater

for (int i=??; i<??; i++)

{

if (maximum < a[i])

maximum = a[i];

}

return(maximum);

}

2. The second program declares a bi-dimensional array and uses a function to compute the sum of the elements on the main diagonal (with index [ii]). Again, the program is not completely defined, you have to replace the ?? in order to get a compilable version.

Here is the program:

#include <iostream>

using namespace std;

//declares the size of te array as a constant integer

const int SIZE = 10;

//declares the function that returns the sum of

// the elements on the main diagonal

int sum(int a[SIZE][SIZE]);

int main()

{

//declares the array of integers

int arraytwo[SIZE][SIZE];

int s;

//initializes each element of the array with the sum of its indexes

for(int i=0; i<SIZE; i++)

for(int j = 0; j<SIZE; j++)

arraytwo[i][j] = i+j;

//call here the function that returns the sum of the main diagonal elements

s = ??

cout <<"The sum of the main diagonal elements is "<< s <<endl;

return(0);

}

int sum(int a[SIZE][SIZE])

{

int s=0;

//compute the sum of elements on main diagonal

for (int i=0; i<SIZE; i++)

{

s = ??

}

return(s);

Solution Preview

These are two interesting programs to learn about arrays in C++ / C.
I have written two separate programs: 78983-1.cpp and 78983-2.cpp and in each I have extensively used comments to explain what is happening and how.

issue for 1:
// NOTE WITHOUT THE FOLLOWING LINE THE PROGRAM OUTPUT WILL BE ...

$2.19