CS19002 Programming and Data Structures Laboratory, Section 5 |
Spring 2007 |
Exercise 1 | Exercise 2 | Exercise 3 | Exercise 4 | Exercise 5 | |
Solution 1 | Solution 2 | Solution 3 | Solution 4 | Solution 5 | |
Show all | Hide all |
Click on the links above
Exercise 1
Write a C function that accepts as input an array of real numbers and the size of the array and that computes the standard deviation of the elements of the array.
Solution 1
double stddev ( double A[], int n ) { double s1, s2; int i; s1 = s2 = 0; for (i=0; i<n; ++i) { s1 += A[i]; s2 += A[i] * A[i]; } return (s2/n) - (s1/n)*(s1/n); }Exercise 2
What values does the following program print?
#include <stdio.h> void doit ( int A[] ) { int *p; p = A; ++p; printf("%d\n", *p); } int main () { int A[] = {1,2,3,4,5}; int *p; p = A; doit(p); printf("%d"\n", *p); }Solution 2
2 1Exercise 3
Write a function that accepts a character string as input and converts the string to upper case. For example the upper case of the string "I.I.T. Kharagpur" is "I.I.T. KHARAGPUR". Do not use any string library functions.
Solution 3
void makeuc ( char A[] ) { int l, i; l = strlen(A); for (i=0; i<l; ++i) if ((A[i] >= 'a') && (A[i] <= 'z')) A[i] += 'A' - 'a'; }Exercise 4
Write a function that takes three two-dimensional arrays A,B,C and three positive integers r,s,t as input. A is treated as an rxs matrix, and B as an sxt matrix. The function computes and stores in C the product matrix AB.
Solution 4
void matmul ( int A[][100], int B[][100], int C[][100], int r, int s, int t ) { int i, j, k; for (i=0; i<r; ++i) { for (j=0; j<t; ++j) { C[i][j] = 0; for (k=0; k<s; ++k) C[i][j] += A[i][k] * B[k][j]; } } }Exercise 5
Write a recursive function that computes the maximum of an array A of size n as follows. It first computes the maximum of the first n/2 elements and stores this maximum in a temporary variable a. It then recursively computes the maximum of the remaining elements of the array and stores this second maximum in a temporary variable b. The function then compares a and b and returns the larger of these values. Recursion stops when the size of the array is reduced to one.
Solution 5
#define ERROR -2147483648 int findmax ( int A[], int n ) { int a,b; if (n == 0) return ERROR; if (n == 1) return A[0]; a = findmax(A,n/2); b = findmax(A+n/2,n-(n/2)); return ((a >= b) ? a : b); }