Exam 2 - Answers to Problems 5 - 8


5: Suppose A is a two-dimensional array of integers with N rows and N columns. Then

a) retrieve the value of A that is stored in row 3, column 4, and print it to the screen.

Answer:

cout << A[3][4];    (or cout << A[2][3]; depending on how you count)

b) store the value -10 in the entry in row 4, column 3

Answer:

A[4][3] = -10;  (or A[3][2] = -10;  depending on how you count)

c) find the sum of the numbers in column 0.

Answer:

int sum = 0;
for (int row = 0; row < N; row++)
   sum += A[row][0];

d) find the sum of all numbers in the array

Answer:

int sum = 0;
for (int row = 0; row < N; row++)
   for (int col = 0; col < N; col++)
      sum += A[row][col];

e) find the sum of the numbers along the main diagonal

Answer:

int sum = 0;
for (int i = 0; i < N; i++)
   sum += A[i][i];


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:

fstream f;
f.open("test.dat", ios::in);
double number;

 

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:

fstream f;
f.open("textfile.txt", ios::in);

int counter = 0;
char cc = f.get();
while (!f.eof())
{
   if (cc == '\n')
      counter++;
   cc = f.get();
}
cout << "Lines: " << counter;

7. Suppose the start of a program looks as follows:

const int SIZE=20;
typedef double Array[SIZE];

a) create a function to display an array

Answer:

void display(Array A)
{
   for (int i = 0; i < SIZE; i++)
      cout << A[i] << endl;
}

b) create a function to add two arrays A and B into a suitable output array C

Answer:

void add(Array A, Array B, Array C)
{
   for (int i = 0; i < SIZE; i++)
      C[i] = A[i] + B[i];
}

c) a function that swaps two numbers in an array A

Answer:

void swap(Array A, int pos1, int pos2)
{
    double temp = A[pos1];
   A[pos1] = A[pos2];
   A[pos2] = temp;
}


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:

#include <iostream.h>

enum Boolean {false, true};

Boolean isNegative(int x)
{
   if (x < 0)
      return true;
   else
      return false;
}

void showBoolean(Boolean b)
{
   if (b == true)
      cout << "true";
   else
      cout << "false";
}

int main(void)
{
   int x;
   cout << "Please enter an integer: ";
   cin >> x;

   showBoolean(isNegative(x));

   return 0;
}


(bgw)