Midterm Review #2 Problems

advertisement
Mech 215 Midterm Review #2
1) Write a program that reads a string variable str1 (maximum length of 20) from
the keyboard. Then print out the length of the string, whether or not it is equal to
“apple”, and make a copy of str1 storing the result in the string variable str2.
Note: Use the C++ library functions strlen(…), strcmp(…), and strcpy(…) to carry
out the tasks above (use #include <cstring>). See section 4.5 of the textbook for
more details on these functions and their usage.
2) Write a function called file_statistics(file_name, number_words, number_chars)
that determines the number of words and the number of visible characters (spaces
and control characters don’t count) in a file. The name of the file is stored in the
string argument file_name. Return 1 if there is an error and 0 otherwise. Use the
C++ library function strlen(…) to simplify your task.
Test out the function for the file "file1.dat" made by the example structures22.rar.
3) Write a function called text_search(file_name, text) that returns the number of
occurrences in a file (name stored in file_name) of the string stored in the
argument text. Use the C++ library function strcmp(…) to simplify your task.
Test out the function for the file "file1.dat" made by the example structures22.rar.
4) Write a function called math_function(f_name, x) that returns the value of a
function evaluated at x. The function name is stored in the string argument
f_name. The valid cases of f_name are “sin”, “cos”, and “exp”. For each one of
these cases return the value sin(x), cos(x), and exp(x), respectively. If it is not one
of these cases print out an error message and return -1.0e7.
5)
a) Develop a structure called lookup_table that contains the double 1D array
variables x and f (maximum length 1000 for each). It also contains N the number
of elements of the table. In this case, the index of the array is considered to start
at zero.
b) Develop a function called init_lookup_table(table) that initializes a lookup_table
structure table to the following values: N = 100, x[i] = i / 10, and f[i] = sin(x[i]).
c) Develop a function called interpolate(table, xp) that searches the lookup_table
structure table for two consecutive values x[i] and x[i+1] that contain the
interpolation point xp. Then calculate and return the interpolated value fp using
linear interpolation. In order to perform linear interpolation you just assume a line
between (x[i],f[i]) and (x[i+1],f[i+1]) to compute fp at xp. Therefore,
fp = f[i] + df_dx * (xp - x[i]) where df_dx = ( f[i+1] - f[i] ) / ( x[i+1] - x[i] ). Test the
function for the cases xp = 2.777 and xp = 3.14159 where table has first been
initialized using the function in part b).
Download