0% found this document useful (0 votes)
25 views

Assignment 5 Solutions

Uploaded by

yukizyx230
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Assignment 5 Solutions

Uploaded by

yukizyx230
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Q1.

#include <stdio.h>

#define SIZE 7

int main(void) {
int data[] = { 5, 3, -12, 34, 2, -17, 6 };
int index = 0;
int maxVal = data[0];
index = 0 1 ..6
while (index < SIZE) {
if (data[index] > maxVal){ index=0, maxVal = 5
maxVal = data[index]; index=1,
...
} index=3, maxVal = 34
index++; ...
}

printf("Maximum value found in array: %d\n", maxVal);

return 0;
}
Q2.
int data[] = { 5, 3, -12, 34, 2, -17, 6 };

result = search(data, 7, 34) --> 3


#define NOT_FOUND -1 result = search(data, 7, 100) --> -1
int search( int array[ ], int size, int toFind ) {
int index;

for (index = 0; index < size; index++) { index=0,


if ( array[ index ] == toFind ){
return index;
}
}

return NOT_FOUND;
}

Q3.

#define NOT_FOUND -1

int search( int array[ ], int size, int toFind );

int compare_arrays(int array1[], int size1, int array2[], int size2)


{
int index1; arr1 = {1, 2, 3, 4, 5}
int duplicates_found = 0; arr2 = {2,3}
int toFind;

for ( index1 = 0; index1 < size1; index1++ ) { index1=0, toFind=1


toFind = array1[index1];

if ( search(array2, size2, toFind) != NOT_FOUND ){


duplicates_found++;
} index / -1
}

return duplicates_found;
}
Q4. index = 0,1,2..size-1 (index<size)
index = startIndex, startIndex+1... size-1

int indexOfSmallest( int data[], int size, int startIndex ) {


int index;
int indexOfMin = startIndex;

for( index = startIndex + 1; index < size; index++ ) {


if( data[ index ] < data[ indexOfMin ] ){
indexOfMin = index;
}
}

return indexOfMin;
}

12345678
col_i=0
row_i=0 1 2 3 4 arr
row_i=1 5 6 7 8 arr[0][0]

Q5.
rowIndex这一行小于threshold这个值的元素的数量
int belowThresholdOnRow(int data[][NUMCOLS], int rowIndex, int
threshold){
int count = 0;
for (int colIndex = 0; colIndex < NUMCOLS; colIndex++) {
if (data[rowIndex][colIndex] < threshold){
count++;
}
}
return count;
}
Q6.

void addMatrix(int dataA[][NUMCOLS], int dataB[][NUMCOLS], int


dataC[][NUMCOLS], int numRows){
for (int row = 0; row < numRows; row++){
for (int col = 0; col < NUMCOLS; col++){
dataC[row][col] = dataA[row][col] + dataB[row][col];
}
}
}

You might also like