Saturday, November 4, 2017

Day 8 - Intro to Data Structures: One Dimensional Arrays

CLASSWORK:
Maximum Value within a 1D Array
/*–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/ 
/* This program defines an array and */
/* determines the maximum value with a function. */
#include <stdio.h>
#define N 10 
int main(void) { 
/* Declare variables and function prototype. */ 
int k=0, npts = N; 
double y[N]= {9,7,3,2,5,5,1,7,4,8}; 
double max(double x[],int n); 
/* Find and print the maximum value. */ 
printf("Maximum value: %f \n",max(y,npts)); 
/* Exit program. */ 
return 0; 


/*––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––-*/ 
/* This function returns the maximum value in an array x with n elements. */ 
double max(double x[],int n)
/* Declare variables. */ 
int k; 
double max_x; 
/* Determine maximum value in the array. */ 
max_x = x[0]; 
for (k=1; k<=n-1; k++) 
if (x[k] > max_x) max_x = x[k]; 
/* Return maximum value. */ 
return max_x; 
}

HOMEWORK:
Assume that we have defined the following variables:
int k=6; 
double data[]={1.5,3.2,-6.1,9.8,8.7,5.2}; 

Using the max function presented in this section, give the value of each of the following expressions:

  1. max(data,6); 
  2. max(data,5); 
  3. max(data,k-3); 
  4. max(data,k%5);
1. This statement means that we must return the maximum value from the first six numbers in the data array. Therefore, the answer is 9.8.

2. This statement means that we must return the maximum value from the first five numbers in the data array. Therefore, the answer is 9.8.

3. Since k=6, we will look at the first k-3= 6 elements in the data array. Therefore, the maximum value is 3.2.


4. Since k%5= 1, we will only look at the first element in the data array. Therefore, the maximum value is 1.5.

No comments:

Post a Comment