Lab 3


  1. Modify the program from part 2 of the last lab (hint: use cp to make a copy of it, and place it in an appropriate directory) to read in a data file, and output the results to another file. The program should prompt the user for the input and output filenames and do appropriate validation to make sure the filenames entered are valid. The input file should have more than 3 numbers in it. This should work without using the unix redirection operators.

  2. Finish the following program, which is designed to reverse a 5 digit number (ie, 12468 becomes 86421) Note: You CANNOT use an array!
    #include <iostream>
    
    using std::cout;
    using std::cin;
    using std::endl;
    
    int main()
    {
       int number;
       
       cout <<"Enter a five-digit number: ";
       cin >>number;
    
       // Write a statement to print the leftmost digit of the 5 digit number
       // Write a statement that changes number from 5 digits to 4 digits 
       // Write a statement to print the leftmost digit of the 4 digit number
       // Write a statement that changes number from 4 digits to 3 digits
       // Write a statement to print the left most digit of the 3 digit number
       // Write a statement that changes number from 3 digits to 2 digits
       // Write a statement to print the left most digit of the 2 digit number
       // Write a statement that changes number from 2 digit to 1 digit
    
       cout << number << endl;
    
       return 0;
    } //end main
    
    If you're really good, you will only need 2 statements and a while loop to do the above part.

  3. Dijkstra's Algorithm for finding the GCD of a number states that, if m > n, then GCD(m,n) equals GCD(m-n,n). The reason for this is, if m/d and n/d both have no remainder, then (m-n)/d leaves no remainder (this is very clever. Dijkstra was a very smart man). This leads to the algorithm that
    For m,n > 0, gcd(m,n) =
    
    m if m=n
    gcd(m - n,n) if m > n
    gcd(m,n-m) if m < n
    
    So, for example, finding the GCD of 21 and 9
    gcd(21,9), so m=21 and n=9. m is greater than n, so we do
    gcd(m-n,n) which is ( 21 - 9, 9 ) or gcd ( 12, 9 ) m still greater than n, so
    gcd(m-n,n) or ( 12 - 9, 9 ) = gcd ( 3, 9 ), n is now greater than m, so
    gcd(m,n-m) or ( 3, 9 - 3 ) = gcd ( 3, 6 ), n is still greater than m, so
    gcd(m,n-m) or ( 3, 6 -3 ) = gcd ( 3, 3 ). They are now equal, so gcd = 3 
    
  4. Write a recursive function that implements this algorithm, and a small program t o test it.


Grading:
  1. 40% for Part 1
  2. 20% for Part 2
  3. 40% for Part 3