CMPT 130 Lab 7 - Arrays

 

In this lab you are going to write a function to populate an array with a sequence of values and a second function to find the minimum value in an array.

 

Labs are assessed so make sure that the TA has seen, and marked, your finished work before you leave the lab.

 

Get a Sequence

Write a function called getSequence that populates an integer array with a sequence of values.  The function should return nothing and should have parameters for the array, the number of values to be inserted into the array (which should also be the array size), the starting value of the sequence and the gap between values in the sequence.  The function prototype should therefore look like this.

 

void getSequence(int arr[], int n, int start, int gap)

 

Implementation

Use a for loop and insert values in the array, starting with start, and increasing the value by gap each iteration

 

Sample Main Function Tests

const int ARR1SIZE = 4;

const int ARR2SIZE = 3;

 

int arr1[ARR1SIZE];

int arr2[ARR2SIZE];

 

// should print the values 7, 9, 11, and 13

getSequence(arr1, ARR1SIZE, 7, 2);

for(int i = 0; i < ARR1SIZE; ++i){

     cout << arr1[i] << endl;

}

 

cout << endl;

 

// should print the values 2, -1, and -4

getSequence(arr2, ARR2SIZE, 2, -3);

for(int i = 0; i < ARR2SIZE; ++i){

     cout << arr2[i] << endl;

}

 

cout << endl << endl;

 

Find Smallest

Write a function called min that returns the smallest value in any integer array.  The function should have parameters for the array and the size of the array.

 

Implementation

A pseudocode version of the algorithm looks like this.

 

smallest = arr[0]

for each value in the array

             if current value < smallest

             smallest = current value

return smallest

 

Sample Main Function Tests

int arr3[] = {17, 3, 12, 11, 4};

int arr4[] = {1, 0, 7, 23, 2, -1};

// should print the value 3

cout << min(arr1, 5) << endl;

// should print the value 3

 

// should print the value -1

cout << min(arr2, 6) << endl;

 

 

Assessment

1 mark for completion of the lab.

 

 

CMPT 130 Home

 

John Edgar (johnwill@sfu.ca)