Exam 2 - Answers to Problems 5 - 8
5: Suppose A is a two-dimensional array of integers with N rows and N columns. Thena) retrieve the value of A that is stored in row 3, column 4, and print it to the screen.
Answer:
b) store the value -10 in the entry in row 4, column 3
Answer:
c) find the sum of the numbers in column 0.
Answer:
d) find the sum of all numbers in the array
Answer:
e) find the sum of the numbers along the main diagonal
Answer:
6. Questions dealing with file input and output.
a) If "test.dat" contains double numbers, one per file, find the largest and smallest number and write them to an output file.
Answer:
f >> number;
double max = number, min = number;
while (!f.eof())
{
if (number > max)
max = number;
if (number < min)
min = number;
f >> number;
}
f.close();
f.open("minmax.dat", ios::out);
f << min << endl;
f << max << endl;
f.close();
b) Write a program to count the number of lines in a text file.
Answer:
7. Suppose the start of a program looks as follows:
a) create a function to display an array
Answer:
b) create a function to add two arrays A and B into a suitable output array C
Answer:
c) a function that swaps two numbers in an array A
Answer:
8. Define a type 'Boolean', write a function IsNegative (to return true if an input
integer is negative), and a function showBoolean (to display a boolean on the screen).
Then write a complete program to test everything.
Answer:
(bgw)