11/13/00 down to 10/10/00

Due 11/13 Monday

Homework and tests must be kept in chronological order in a folder or a loose leaf binder
0. Due Monday, November 20:  Purchase Be Prepared for the AP Computer Science Exam, 
     Maria Litvin.   Book information and online purchasing outlets
1. Read 5.10 (passing by reference), 5.11 (passing by constant reference), 5.13 (scope)
2. Answer review questions (p. 112) 5.1, 5.2, 5.3, 5.7, 5.8, 5.9 (Bring answers to class)
3. Use mouse and browser to copy program below to your editor and complete it as specified.
4. Can you design a toRadix() for radix > 10 with no decision with respect to the successive remainders?

// FILE: toInt.cpp
// PURPOSE: Use function to convert string representing # in scale of notation 
//           specified by given radix to an integer value
//==========================================================================
#include <iostream.h>
#include <iomanip.h>
#include "apstring.h"
//===============================================================
// INSTRUCTIONS:
// 1. Complete toInt() as specified below
// 2. Run the program to test your solution
//================================================================
int toInt(apstring, int);
apstring toRadix(int, int);
void toIntDriver(void);
int main() {
  toIntDriver();
  cout << endl << endl;
  return 0;
}
      
int toInt(apstring number, int r) {
  // precondition: number represents number in radix r, 2 <= r <= 10 
  //postcondition: returns numerical value that parameter number represents
  int sum(-77);
  return sum;
}
apstring toRadix(int n, int r) {
  // precondition: n >= 0, 2 <= r <= 10
  //postcondtion: Returns st which is a  representation of n 
  //               in r's scale of notation 
  apstring st;
  do {
    st = char( '0' + n % r ) + st;
    n /= r;
  } while ( n != 0 );
  return st;
}
void toIntDriver(void) {
  apstring title("Using toInt() to convert from radix scales from 2 to 10 ");
  cout << "\n\n\n\n\n\n" << setw(38 + title.length()/2) << title.c_str() << endl << endl;
  apstring numbers[] = { "111111", "1000000", "101110", "7777", "10000", "52073",
                         "9999", "10000", "4907"};
  int bases[] = { 2, 2, 2, 8, 8, 8, 10, 10, 10};
  const int VALUES = sizeof(numbers)/sizeof(apstring); 
  for (int k = 0; k < VALUES; ++k) {
    int toIntResult = toInt(numbers[k], bases[k]);
    cout << "toInt(" + numbers[k] + ", " << bases[k] << ") = " << toIntResult;
    if ( toRadix(toIntResult, bases[k]) == numbers[k] )
      cout << "  OK\n";
    else
      cout << "  ***** ERROR\n";
  }
  cout << endl;
}

Due 11/10 Friday

Homework and tests must be kept in chronological order in a folder or a loose leaf binder
0. Due Monday, November 20:  Purchase Be Prepared for the AP Computer Science Exam, 
     Maria Litvin.   Book information and online purchasing outlets
1. Complete letter grade program started below.
2. Modify toRadix() (which was due today) to work without an IF or SWITCH statement.
// FILE: switch.cpp
// PURPOSE: Use switch statement to determine letter grade as
//           specified in this table
//-----------------------------------------------------------------
//        X                Letter Grade        
// ----------------      ------------------   
//        x > 50              error
//  30 <= x <= 50               A 
//  20 <= x < 30                B
//  10 <= x < 20                C 
//        x < 10                D 
//-----------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#include "apstring.h"
apstring letterGrade(int);
void printGradeDriver(int);
int main() {
  cout << "\n\n\n\n\t\tTesting switch statement\n\n";
  printGradeDriver(65);
  printGradeDriver(59);
  printGradeDriver(50);
  printGradeDriver(49);
  printGradeDriver(40);
  printGradeDriver(39);
  printGradeDriver(30);
  printGradeDriver(29);
  printGradeDriver(20);
  printGradeDriver(19);
  printGradeDriver(10);
  printGradeDriver(9);
  printGradeDriver(-15);
  return 0;
}
apstring letterGrade(int n) {
  // Use SWITCH statement to implement this function
  //postcondition: returns letter grade specified in table above
  apstring errorMessage("ERROR: n greater than 50");
  switch ( n ) {
  case 5: 
  case 4:
  case 3: 
  case 2: 
  case 1: 
  default: return "letterGrade() not installed\n"; 
  }//***switch   
}
void printGradeDriver(int m) {
  cout << "letterGrade(" << m << ") = " << letterGrade(m) << endl;
}



Due 11/09 Thursday

Homework and tests must be kept in chronological order in a folder or a loose leaf binder
0. Due Monday, November 20:  Purchase Be Prepared for the AP Computer Science Exam, 
     Maria Litvin.   Book information and online purchasing outlets
1. Read sections 4.3 (do/while loops) and 3.11 (the switch statement)
2. Use your browser and mouse to copy the program below into your editor. Then complete
     toRadix() and doWhile() as specified.

// FILE: toRadix.cpp
// PURPOSE: Use function to convert n to scale of notation specified by radix
//==========================================================================
#include <iostream.h>
#include <iomanip.h>
#include "apstring.h"
//===============================================================
// INSTRUCTIONS:
// 1. Complete toRadix() and doWhile() as specified below
// 2. Run the program to test your solution
//================================================================
apstring toRadix(int, int);
void toRadixDriver(void);
void doWhile(void);
int main() {
  toRadixDriver();
  cout << endl << endl;
  doWhile();
  cout << endl << endl;
  return 0;
}
      
apstring toRadix(int n, int r) {
  // precondition: n >= 0, 2 <= r <= 10
  //postcondtion: returns st as representation of n in r's scale of notation
  apstring st;
  //-----------------------------------------------------------------------
  // Try to use a switch statement. Eventually, we'll see how to accomplish 
  // this task without any decision!!! Consider a do/while loop for this!!
  //------------------------------------------------------------------------
  return st;
}
void doWhile(void) {
  //postcondition: after do/while loop, 1 + 2 + ... + 100 is summed and printed
  //               y is assigned 0.00008123 using e-format
  apstring title("Using a do/while loop to sum 1 + 2 + ... + 100");
  cout << setw(38 + title.length()/2) << title.c_str() << endl << endl;
  //--------------------------------------------------------------------------
  // Clean up nonsense code below to implement postcondition (sum = 5050, remember?)
  //--------------------------------------------------------------------------
  int n(100), sum;
  do {
  } while ( false );
  cout << "Sum computed in do/while loop is: " << sum << endl << endl;
}
void toRadixDriver(void) {
  apstring title("Using toRadix() to convert to radix scales from 2 to 10 ");
  cout << "\n\n\n\n\n\n" << setw(38 + title.length()/2) << title.c_str() << endl << endl;
  cout << "RADIX\n"; 
  for (int radix = 2; radix <= 10; ++radix) {
    cout << setw(2) << radix << ":  ";
    for ( int k = 0; k <= 12; k++ ) {
      cout  << setw(2) << k << " = " << setw(3) << setiosflags(ios::right) 
	    << toRadix(k, radix) << "  ";
      if ( k == 6 ) cout << "\n     ";
    } //***for k
    cout << endl << endl;
  }//***for radix
  cout << endl;
}

 

 

Due 11/08 Wednesday

Homework and tests must be kept in chronological order in a folder or a loose leaf binder
0. Due Monday, November 20:  Purchase Be Prepared for the AP Computer Science Exam, 
     Maria Litvin.   Book information and online purchasing outlets
1. Read sections 2.12 (round-off error), 2.13 (e-format) , 2.14 (nested and parallel scopes)
2. Use your browser and mouse to copy the program below into your editor. Then complete
     decToBinary() and eFormat() as specified;

// FILE: toBinary.cpp
// PURPOSE: Use function to convert base 10 number to binary
//=================================================================
#include <iostream.h>
#include <iomanip.h>
#include "apstring.h"
//===============================================================
// INSTRUCTIONS:
// 1. Complete decToBinary() and eFormat() as specified below
// 2. Run the program to test your solution
//================================================================
apstring decToBinary(int);
void decToBinaryDriver(void);
void eFormat(void);
int main() {
  decToBinaryDriver();
  cout << endl << endl;
  eFormat();
  cout << endl << endl;
  return 0;
}
      
apstring decToBinary(int n) {
  // precondition: n >= 0
  //postcondtion: returns binary representation of n 

  return "000";
}
void eFormat(void) {
  //postcondition: x is assigned 8.123 x 10^47 using e-format
  //               y is assigned 0.00008123 using e-format
  apstring title("Using e-format to assign floating point values");
  cout << "\n\n\n" << setw(38 + title.length()/2) << title.c_str() << endl << endl;
  //---------------------------------------------------
  // replace assignments to x, y with appropriate ones:
  //---------------------------------------------------
  double x(-77), y(-77);
  x = y;
  cout << "x should print out as 8.123e47, x = " << x << endl;
  y = -x;
  cout << "y should print out as 8.123e-5 , y = " << y << endl;
}
void decToBinaryDriver(void) {
  apstring title("Converting non-negative base 10 numbers to binary"),
    table[] = { "0", "1", "10", "11", "100", "101", "110", "111", "1000",
		"1001", "1010", "1011", "1100", "1101", "1110", "1111", "10000",
		"10001", "10010", "10011", "10100", "10101" };
  cout << "\n\n\n\n\n\n" << setw(38 + title.length()/2) << title.c_str() << endl << endl;
  cout << "  n    decToBinary(n)\n" 
       << "---------------------\n";
  for ( int k = 0; k <= 21; k++ ) {
    apstring binString = decToBinary(k);
    cout << setw(3) << k << setw(10) << setiosflags(ios::right) 
	 << binString;
    if ( binString != table[k] ) {
      cout << "  *** ERROR: decToBinary() should =  " << table[k] << endl;
    }
    else {
      cout << endl;
    }
  }//***for
  cout << endl;
}

 

 

Due 11/06 Monday

Homework and tests must be kept in chronological order in a folder or a loose leaf binder
1. Complete sigma() and isPerfect() as specified below .
2. Work on listAmicable(). Remember that if (220, 284) appears in your solution, (284, 220) shouldn't.
     Since a number can't be amicable with itself, perfect number pairings such as (6, 6) or (496, 496)
     are invalid!

// FILE: perfect.cpp
// PURPOSE: Use functions to find perfect and amicable numbers
//-----------------------------------------------------------------
// 1. First complete sigma() as specified below. Run the program
//    to enable the testSigma() function to validate your solution.
// 2. Once sigma() is validated, complete isPerfect() as specified
//    below. Use sigma() to build isPerfect(). Run program to enable 
//    testIsPerfect() to validate your
//    solution. 
// 3. Once isPerfect() is validated, complete listAmicable() 
//    as specified below.
//-----------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#include <string>
void wait() {
   cout << "\nPress <ENTER> to continue: ";
   cin.ignore(10, '\n');
}
int sigma(int n) {
  // precondition: n > 0
  //postcondition: returns sum of n's proper divisors
  //EXAMPLE: sigma(8) = 1 + 2 + 4 = 7 and sigma(12) = 1 + 2 + 3 + 4 + 6 = 16
  int sum(0);
  return sum;
}
void testSigma(void) {
  int table[20] = { 0 , 1, 1, 3, 1, 6, 1, 7, 4,
		    8, 1, 16, 1, 10, 9, 15, 1, 21, 1, 22 }; 
  string title("Testing your sigma() function");
  cout << "\n\n\n\n\n" << setw(39 + title.length()/2) << title.c_str()
       << endl << endl;
  int errorCount(0);
  for (int k = 2; k <= 20; k++) {
    cout << "  sigma(" << setw(2) << k << ") = "  << setw(2) << table[k-1] 
	 << " and your sigma() returns " << setw(3) << sigma(k) << "  "
	 << ((sigma(k)==table[k-1])? "OK\n" : "***ERROR\n");
    if ( sigma(k) != table[k-1] )
      ++errorCount;
  }
  if ( errorCount != 0 ) {
    cout << "\n\nYour sigma() doesn't work yet: there were " 
	 << errorCount << " errors.\n";
    cout << "Keep working on sigma() before starting isPerfect()\n";
  }
  else {
    cout << "\n\nYour sigma() is fine. You're ready to start on isPerfect()\n";
    cout << "Go to main() and delete the call to testSigma()\n";
  }
  wait();
}
bool isPerfect(int n) {
  // precondition: n > 1
  // postcondition: Uses sigma() to return true when n is the sum of its 
  //                proper divisors, otherwise return false
  // EXAMPLE: 6 is perfect since 1 + 2 + 3 = 6; 28 because 1 + 2 + 4 + 7 + 14 = 28
  return true;
}
void testPerfect(void) {
  // precondition: LAST > 1
  //postcondition: uses isPerfect() to list perfect numbers from 2 to LAST
  const int LAST(9000);
  string title("Testing your isPerfect() function");
  cout << "\n\n\n\n\n" << setw(39 + title.length()/2) << title.c_str()
       << endl << endl;
  int table[] = {6, 28, 496, 8128}, perfectCount(0);
  const int numPerfects = sizeof(table)/sizeof(int);
  cout << "Printing perfect numbers in [2," << LAST << "]\n\n";
  for ( int k = 2; k <= LAST; k++) {
    if ( isPerfect(k) ) {
      ++perfectCount;
      if ( perfectCount > numPerfects || k != table[perfectCount-1] ) {
	cout << "\n\nYour isPerfect() doesn't work yet: " << k 
	     << " isn't a perfect number\n"; 
	cout << "Keep working on isPerfect()\n";
        return;  
      }
      else {
	cout << setw(3) << perfectCount << "." << setw(6) << k << endl;
      }
    }//** if isPerfect
  }//** for
  if ( perfectCount != numPerfects ) {
    cout << "\n\nYour isPerfect() doesn't work yet: you should have found " 
	 << numPerfects << " perfect numbers, but " << perfectCount << " were found.\n";
  }
  else {
    cout << "\n\nYour isPerfect() is fine. You're ready to start on listAmicable()\n";
    cout << "Go to main() and delete the call to testPerfect()\n";
  }
  wait();
}
void listAmicable(void) {
  // precondition: natural numbers n and d are amicable when 
  // sigma(n) == d and sigma(d) == n. 
  // EXAMPLE: sigma(220) = 284 and sigma(284) = 220. Therefore they're amicable.
  //postcondition: lists amicable pairs from 2 to n
  const int LAST(100000);
  string title("Listing Amicable Pairs from 2 to ");
  cout << "\n\n\n\n\n" << setw(37 + title.length()/2) << title.c_str()
       << LAST << endl << endl;
  cout << "You should print out 13 unique pairs, the last being (79750, 88730)\n\n";
  //-------------------------------------------------------------
  // ***The code in the loop is nonsense code: clean it up to
  // enable the cout statement to print when it's appropriate.
  //-------------------------------------------------------------
  int count(0), amicable2;
  for (int n = 2; n <= LAST; n++) {
    amicable2 = n + 1;
    if ( amicable2 == n ) {
      count++;
      cout << setw(3) << count << ".  " << setw(15)
           << n <<  setw(15) << amicable2 << endl;
    }
  }//***for
}
int main() {
  testSigma();
  testPerfect();
  listAmicable();
  return 0;
}

Due 11/02 Thursday

Homework and tests must be kept in chronological order in a folder or a loose leaf binder
Use your browser and mouse to copy this file to your computer. Then complete isPrime() as specified.

// FILE: primes1.cpp
// PURPOSE: Use boolean function to print primes
//=================================================================
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
#include "apstring.h"
//===============================================================
// INSTRUCTIONS:
// 1. Complete isPrime() as specified below
// 2. Run the program to test your solution
// 3. There are 25 primes in [2,100], the last being 97  
//================================================================
bool isPrime(int n) {
  //postcondition: returns true if n is prime
  //               else returns false
 
  return true;
}
int main() {
  apstring title("Printing primes in [2,100] using isPrime() function");
  cout << "\n\n\n\n" << "\t\t" << title << endl << endl;
  int primeCount(0), WIDTH(6);
  for (int k = 2; k <= 100; k++) {
    if ( isPrime(k) ) {
      ++primeCount;   
      cout << setw(WIDTH-3) << primeCount << "." << setw(WIDTH) << k << endl; 
    }
  }
  
  cout << endl << endl;
  return 0;
}

 

 

Due 11/01 Wednesday

Homework and tests must be kept in chronological order in a folder or a loose leaf binder
1. Revise CHALLENGE 4a program by defining your own GCD() function before the main() function and
    using it to facilitate your solution. 
    Optional: you might want to create an isEven() function as well. It would look like this:

      bool isEven(int n) {     
      // postcondition: returns 1 when n is even, else returns 0
          
      }

2. Use your browser to copy the short program below to your computer and complete toUpper()
    as specified.

// FILE: toUpper.cpp
// PURPOSE: Use function to convert string to upper case
//=================================================================
#include <iostream.h>
#include <iomanip.h>
#include "apstring.h"
//===============================================================
// INSTRUCTIONS:
// 1. Complete toUpper() as specified below
// 2. Run the program to test your solution
// 3. Make sure you have apstring.h and apstring.cpp in the
//    directory or folder in which you are compiling this program
//================================================================
apstring toUpper(apstring s) {
  //postcondition: returns upper case version of parameter s 
  return "AbCd#"; 
}
int main() {
  apstring title("Testing toUpper() string conversion function");
  cout << "\n\n\n\n" << "\t\t" << title << endl << endl;
  apstring st("AbCdEfG#$hiHI"), tt("ABCD"), ut("abcd");
  cout << "toUpper(\"" << st << "\") = \"" << toUpper(st) << "\"\n\n";
  cout << "toUpper(\"" << tt << "\") = \"" << toUpper(tt) << "\"\n\n";
  cout << "toUpper(\"" << ut << "\") = \"" << toUpper(ut) << "\"\n\n";
  cout << "toUpper(\"" << "#@" << "\") = \"" << toUpper("#@") << "\"\n\n";
  cout << "toUpper(\"" << "\") = \"" << toUpper("") << "\"\n\n";
  
  cout << endl << endl;
  return 0;
}


Due 10/31 Tuesday

Homework and tests must be kept in chronological order in a folder or a loose leaf binder
0. Test 6 will be returned on Tues, 10/31
1. Read Hubbard sections 5.1 through 5.6 (Local Variables and Functions). There will be a short quiz on this
    material at the beginning of class.
2. Complete CHALLENGE 4a. given in HW due Monday without defining functions. (You'll do that for
    Wednesday) It is NO LONGER OPTIONAL. You  may follow the pseudocode below if you get stuck.
    You may print your solution.
    Hints: 1. You will need to define new variables.
              2. When max = 8, there are 15 primitive triples, the last being (15, 112, 113)

    for m = 2 to max {
       for n = 1 to m - 1 {
           if ( m and n are such that one is odd and one is even )
               find GCD(m, n) and assign to gcd
               if  ( gcd equals 1 ) {
                  generate triple
                  print triple
               }//*** if gcd
          }//*** if m and n...
  }//*** for n
}//*** for m

Due 10/30 Monday                        
Homework and tests must be kept in chronological order in a folder or a loose leaf binder

// FILE: triples2.cpp
// PURPOSE: Use nested loops to print out Pythagorean triples with
//          generating numbers (m, n)
//=================================================================
#include <iostream.h>
#include <iomanip.h>
int main() {
  //===============================================================
  // PROBLEM: Print out Pythagoran triples without using a
  //          Pythagorean if condition
  //==============================================================
  int m, n; // The generating numbers
  int a, b, c; // The lengths of the triangle's sides
  int max(8), wdth(8), count(0);
  cout << "\n\n\n\n\n\t\t\t" << "Printing Pythagorean Triples" << endl << endl;
  // ==============================================================
  // INSTRUCTIONS:
  // 1. Modify the for statements to reduce output lines to 28
  // 2. Modify the inner loop by using generating numbers (m,n) to
  //    assign values to a, b, c
  // 3. If max = 8, you should generate 28 unique triples, the last
  //     being (15, 112, 113)
  // 4a. CHALLENGE: WITH IF STATEMENTS that refer only to m and n, generate
  //     and print only primitive triples, triples where GCD(a, b, c) = 1
  //     HINT: This requires a lot of code because it's an odd/even problem
  //     and a GCD problem!! There are 15, the last being (15, 112, 113)
  // 4b. CHALLENGE: WITHOUT AN IF STATEMENT, use algorithm in a manner
  //     that the hypotenuse of every triple is a perfect square 
  //     HINT: For each triple, use algorithm twice!! The first triple
  //     is (7, 24, 25), the 28th is (3360, 12319, 12769).
  // =================================================================
  // CODE TO GENERATE THE 28 TRIPLES

  for ( m = 1; m <= max; ++m )
    for ( n = 1; n <= max; ++n ) {
      if ( count % 10 == 0 ) {
        cout << "       k       m       n       a       b       c\n"
             << "------------------------------------------------\n";
      }
      ++count;
      a = -7;
      b = -8;
      c = -9;
      cout << setw(wdth) << count << setw(wdth) << m << setw(wdth) << n
           << setw(wdth) << a << setw(wdth) << b << setw(wdth) << c << endl;
    }
  cout << endl << endl;
  return 0;
}

 

Due 10/26 Thursday

// FILE: nested.cpp
// PURPOSE: Practice with nested loops
//=================================================================
#include <iostream.h>
#include <iomanip.h>
int main() {
  //===============================================================
  // PROBLEM: Code the inner loop given an outer loop (which
  //          can't be changed) and specified output.
  //==============================================================
  int m, n; 
  cout << "\n\n\n\n\n\t\t" 
       << "Designing inner loops to realize given output" << endl << endl;
  // ==============================================================
  // INSTRUCTIONS: 
  // 1. For each given outer loop and its given output, code an inner
  //    loop that enables the nested loops to realize the given output.
  // 2. Do NOT change the outer loop!!!
  // ================================================================= 
  // THE NESTED LOOPS: 
  // PROBLEM #1
  //----------------------------------------
    cout << "Specified output, problem #1:\n"
       << "3 2 1" << endl
       << "2 1" << endl
       << "1" << endl << "Result:\n";
  //======================================
  for (m = 1; m <= 3; m++) {
    for (n = 1; n <= 3; n++)  // Change the inner loop only
      cout << n << "  ";
    cout << endl;
  }
  // PROBLEM #2
  //----------------------------------------
  cout << "\nSpecified output, problem #2:\n"
       << "3" << endl
       << "3 2" << endl
       << "3 2 1" << endl << "Result:\n";
  //======================================
  for (m = 1; m <= 3; m++) {
    for (n = 1; n <= 3; n++)  // Change the inner loop only
      cout << n << "  ";
    cout << endl;
  }
  // PROBLEM #3
  //----------------------------------------
  cout << "\nSpecified output, problem #3:\n"
       << "3" << endl
       << "2 3" << endl
       << "1 2 3" << endl << "Result:\n";
  //======================================
  for (m = 1; m <= 3; m++) {
    for (n = 1; n <= 3; n++)  // Change the inner loop only
      cout << n << "  ";
    cout << endl;
  }
  cout << endl << endl;
  return 0;
}

 

Due 10/25 Wednesday

Modify the nested loops in the program below to enable it to print 6 unique Pythagorean triples instead of
the 36 triples it currently prints.

// FILE: triple1.cpp
// PURPOSE: Use nested loops to print out Pythagorean triples
//=================================================================
#include <iostream.h>
#include <iomanip.h>

int main() {
  //===============================================================
  // PROBLEM: Print out Pythagoran triples more effectively than
  //          program currently does
  //==============================================================
  int a, b, c; // The lengths of the triangle's sides
  int max(20), wdth(6), count(0);
  cout << "\n\n\n\n\n\t\t\t" << "Printing Pythagorean Triples" << endl << endl;
  // ==============================================================
  // INSTRUCTIONS: 
  // 1. The program currently prints triples for all a,b,c in [3,20]--
  //    That's 36 triples.
  // 2. Modify the nested loops to prevent duplicate triples from being printed.
  //    EXAMPLE: if 5 12 13 is printed, then 12 13 5 shouldn't be. That's only 11
  //    triples!!! Before modifying the if statement's condition, see if you can
  //    reduce the triples to 6 by changing the loops!!!.
  // 3. NOTE: If you change max from 20 to 30, there should be 11 unique triples.   
  // 4. Define any additional variables you need. (You shouldn't need any)
  // ================================================================= 
  // THE NESTED LOOPS: 

  cout << "     n     a     b     c\n\n";
  for ( a = 3; a <= max; ++a ) {
    for ( b = 3; b <= max; ++b ) {
      for ( c = 3; c <= max; c++ ) {
	if ( a*a + b*b == c*c || a*a + c*c == b*b || b*b + c*c == a*a ) {
	  count += 1;
	  cout << setw(wdth) << count << setw(wdth) << a << setw(wdth) << b 
	       << setw(wdth) << c << endl;
	}
      } //*** for c
    } //*** for b
  } //*** for a

  cout << endl << endl;
  return 0;
}

 

Tuesday  10/24: Optional Test Review Questions

p. 50 Review Questions 3.5a,c; 3.8, 3.9, 3.10, 3.13, 3.14   Answers on p. 52
p. 80 Review Questions 4.1,  4.3,  4.4a, 4.5, 4.6, 4.8, 4.9, 4.10  Answers on p. 82
p. 81 Problems 4.1, 4.2, 4.3, 4.4, 4.11 (This is a cool problem. What you're asked to do is use a
         second int variable to contain the digits of the first int variable in reverse order. If you have time,
         use a while or for loop to implement your solution. This is enough of a hint, hopefully, to ensure that
         you solve it before looking at given solution.) Solutions on p. 83


Due Monday  10/23

1. Save your gcd program to a new file name (gcd2.cpp, for example) and implement Euclid's algorithm
    using a for loop and a break statement.   (Read Hubbard, sect. 4.4)

2. Write a flowchart that represents an algorithm for printing out the nth Fibonacci number after getting
     natural number n from the keyboard. For your flowchart, you may assume that the number entered is
    positive, but you may make no such assumption in part 3 of this assignment.

3. Use a for loop in completing the program started below, which prints the nth Fibonacci number after
    getting n from the keyboard. Review the sample program output screens below for further specifications.

PROGRAM RUN #1

Enter positive n: 4

fib(4) = 3

PROGRAM RUN #2

Enter positive n: 0
ERROR: input must be positive--Enter positive n: -5
ERROR: input must be positive---Enter positive n: 6

fib(6) = 8
// FILE: fib.cpp
// PURPOSE: Use for loop to find nth Fibonacci number
//=================================================================
#include <iostream.h>
int main() {
  //===============================================================
  // PROBLEM: Get natural number n from keyboard and find the
  // nth Fibonacci number
  //==============================================================
  int n, fib;
  cout << "\n\n\n\n\n\t\t\t" << "Finding the nth Fibonacci number" << endl << endl;
  cout << "Enter natural number n: ";
  cin >> n;
  // ==============================================================
  // INSTRUCTIONS: 
  // 1. Keep re-prompting the user until a positive n is entered
  // 2. Define any additional variables you need.
  // 3. At the end of your code, variable fib should contain value of nth Fib #
  // -------------------------------------------------------------
  // The Fibonacci sequence:
  //  fib(n)---> 1 1 2 3 5 8 13 21 34 ...     
  //  n -------> 1 2 3 4 5 6  7  8  9 ...
  // ================================================================= 
  // YOUR CODE: 


  // ==============================================================
  cout << "fib(" << n << ") = " << fib << endl << endl;
  return 0;
}

 


Due Friday  10/20

1. Modify yesterday's GCD program to prevent non-positive integers from reaching the loop with which
    Euclid's Algorithm is implemented. Examine the sample output screen below for an example of
    the specified behavior that you are requested to build into your program.

PROGRAM RUN #1

Enter positive n: -30
ERROR: input must be positive--Enter positive n: 0
ERROR: input must be positive---Enter positive n: 30

Enter positive d: 108

GCD(30, 108) = 6
30/108 = 5/18

PROGRAM RUN #2

Enter positive n: -35
ERROR: input must be positive---Enter positive n: 35

Enter positive d: -22
ERROR: input must be positive---Enter positive n: 22

GCD(35, 22) = 1
35/22 = 35/22

2. Before writing factorial program specified in part 3. of Friday's assignment, represent the algorithm
    with a flow chart. Assume that the number entered isn't negative when representing your algorithm
    with a flowchart but make no such assumption when you write the program specified in part 3.

3. Complete the short program started below which finds n!. Remember that 4! = 4 x 3 x 2 x 1 and
    3! = 3 x 2 x 1 and  2! = 2 x 1 and 1! = 1 but 0! = 1 by definition!! Examine the given sample
    output for further program specifications.

PROGRAM RUN #1

PROGRAM RUN #2

Enter non-negative n: 5

5! = 120
Enter non-negative n: -5

-5! is undefined

// FILE: fact.cpp
// PURPOSE: Use while loop and decisions to find n! 
//=================================================================
#include <iostream.h>
int main() {
  //===============================================================
  // PROBLEM: Get n from keyboard and print n! or state that
  // that n! is undefined (-5! is undefined, for example)
  //==============================================================
  int n;
  cout << "\n\n\n\n\n\t\t\t" << "Finding n!" << endl << endl;
  cout << "Enter non-negative n: ";
  cin >> n;
  cout << endl;
  // =================================================================
  // INSTRUCTIONS: Define any additional variables you need. Recall 
  // that 0! = 1.
  // -----------------------------------------------------------------
  // SAMPLE OUTPUT: Enter non-negative n: 5 | Enter non-negative n: -5
  //                5! = 120                | -5! undefined
  // ================================================================= 
  // YOUR CODE: 


  // ==============================================================
  return 0;
}


Due Thursday  10/19

Complete the program started below. Instructions and test data have been commented into
the program.

// FILE: gcd.cpp
// PURPOSE: Implement Euclid's Algorithm with a while loop
//=================================================================
#include <iostream.h>
#include "apstring.h"

int main() {
  //===============================================================
  // PROBLEM: Get natural numbers n and d from keyboard, find
  // their GCD, and use GCD to express n/d in lowest terms
  //==============================================================
  int n, d, r, gcd;
  cout << "\n\n\n\n\n\t\t" << "Using Euclid's Algorithm to express n/d "
       << "in lowest terms" << endl << endl;
  cout << "Enter natural numbers n d: ";
  cin >> n >> d;
  cout << endl;
  // ==============================================================
  // INSTRUCTIONS: Define any additional variables you need.
  // -------------------------------------------------------------
  // SAMPLE OUTPUT: Enter natural numbers n d: 30 108
  //                GCD = 6
  //                30/108 = 5/18                           
  // -----------------------------------------------------------------
  // TEST DATA: (1449, 460) = 23, (328, 1804) = 164, (1976, 7429) = 19
  // ================================================================= 
  // YOUR CODE: 




  // ==============================================================
  return 0;
}

 

 

Due Wedneday  10/18

Complete the program started below.

// FILE: while3.cpp
// PURPOSE: Solve problems with while loops
//=================================================================
#include <iostream.h>
#include "apstring.h"
int main() {
  //===============================================================
  // Problem 1. Calculate an average using 'sentinel' or 'dummy' 
  //            value of -1 for user to terminate end of input
  // INSTRUCTIONS: Data input terminates after 5 valid scores or
  // after score of -1 is entered. Define  variables if  needed.
  //==============================================================
  int counter, score, sum, max(5);
  double average;
  cout << "\n\n\n\n\n\n\n\n" << "Computing an average of " << max 
       << " or fewer integer scores with sentinel value of -1" << endl << endl;
  // ==============================================================
  // YOUR CODE:



  // ==============================================================
  cout << endl << endl << endl << endl;

  //===============================================================
  // Problem 2. CHALLENGE: Print 10-by-10 multiplication table
  //            using a single loop (creatively). Not due 10/18
  // INSTRUCTIONS: Define additional variables as needed
  //==============================================================
  apstring stars("**********************");
  cout << stars + stars + stars << "\n\n\n\t"
       << "CHALLENGE: Printing 10 x 10 multiplication table with a single loop" 
       << endl << endl;
  // ==============================================
  // YOUR CODE:
  // ==============================================
  cout << endl << endl;
  return 0;
}


Due Tuesday  10/17

Complete the program started below.

// FILE: while2.cpp
// PURPOSE: Solve problems with while loops
//=================================================================
#include <iostream.h>
#include <math.h>
#include "apstring.h"

int main() {
  apstring title("Solving problems with while loops");
  cout << "\n\n\n\n\n" << "\t\t\t" << title << endl << endl;
  // Problem 1. Use while loop to find sum of 1st 50 terms of 2 + 5 + 8 + ...
  //            NOTE: The answer is 3775
  //----------------------------------------------------------------------------
  cout << "Using a while loop to find sum of 1st 50 terms of: 2 + 5 + 8 + ...\n\n";
  int sum, counter;
  //============================================================================
  // INSTRUCTIONS: 1. Use variables sum, counter. Define additional variables if needed.
  //               2. At the end of the code, the variable sum should contain solution



  //============================================================================
  cout << "The sum is: " << sum << endl << endl << endl << endl;


  // Problem 2. Reverse a string WITHOUT defining another string (using indexing)
  // Test data: "ABCD" reverses to "DCBA", "ABC" to "CBA", and "A" to "A"
  //----------------------------------------------------------------------------
  int cntr;
  apstring st;
  cout << "Reversing a string without defining another string\n\n";
  cout << "Enter a string to reverse: ";
  getline(cin, st);
  //============================================================================
  // INSTRUCTIONS: 1. Use variables st and cntr. Do NOT define additional string.
  //               2. At the end of the code, the variable st should contain solution


  //============================================================================
  cout << "st is now: " << st << endl << endl;
  return 0;
}


Due Monday  10/16

1. Bring in Test 5 and Test 4
2. Complete the two short programs started below.
1.  Read example commented in program before completing it (due Mon 10/16)
      Read review of string indexing below to use expressions like st[k] = 'Q' in your solution.

// FILE: convert2.cpp
// PURPOSE: Use decisions, repetition, and indexing to convert a string to lower case
//===========================================================================
// INDEXING:if st == "ABCD":
//   1. st[0] == 'A', st[1] == 'B', st[2] == 'C', st[3] == 'D'
//   2. After statement st[2] = 'Q'; is executed, st == "ABQD".
//   3. The statement st[4] = 'Q'; causes a run-time error since st[3] is last

//      character in st and 3 is the last valid index value.
//   4. st[k] is referred to as "st sub k"-- think of stk
//===========================================================================

// EXAMPLE: if original string == "AbCd#!45E", converted string == "abcd#!45e"
//===========================================================================

#include <iostream.h>
#include "apstring.h"

int main() {
  apstring st;
  cout << "n\n\n\\n\n\t\tConvering string to lower case\n\n";
  cout << "Enter string: ";  
  getline(cin, st);   // equivalent to: cin >> st;
  // ==============================================
  // Your code:
  // ==============================================
  cout << "string now equals: " << st << endl << endl;
  return 0;
}

2.  Study the sample output frames before completing the program (due Mon 10/16)

PROGRAM RUN #1

PROGRAM RUN #2

Computing an average of integer scores

Enter number of scores: 2
Enter score: 10
Enter score: 9

Average is: 9.5
Computing an average of integer scores

Enter number of scores: -1

No basis for average

 

// FILE: average1.cpp
// PURPOSE: Use decisions and repetition to compute average interactively
//==========================================================================

#include <iostream.h>
#include "apstring.h"
int main() {
  int numScores, score, sum;
  double average;
  cout << "\n\n\n\n\n\t\tComputing an average of integer scores" << endl << endl;
  cout << "Enter number of scores: ";
  cin >> numScores;
  // ==============================================
  // Your code:


  // ==============================================
  return 0;
}


Due Wednesday  10/11

1. Re-read Hubbard 3.9; read 3.10
2. Make note of item #3 under ANNOUNCEMENTS: Write p. 89 (math.h functions), p. 342 (ASCII codes),
    p. 351 (C++ operators by precedence), and p. 396 (C and C++ functions) in the back of your copy of
    Programming With C++, 2nd ed.. These are very useful pages to which you'll want to have easy access.

3. Revise your quadratic formula program using 1. nesting and 2. compound statements in order to implement
     the pseudocode below. Use this test data or develop your own. Handwritten or printed.

  EQUATION

OUTPUT

1. 2x2 - x - 6 = 0          
2. x2 - 100 = 0
3. x2 -7x = 0
4. x2 - 2 = 0
5. 4x2 + 20x + 25 = 0
6. x2 + 1 = 0
1. {2, -1.5}
2. {10, -10}
3. {0, 7}
4. {1.41421, -1.41421}
5. {-2.5}
6. Roots are imaginary

    1. write title and author
    2.  prompt for and get integral coefficients a, b, and c
    3a. if ( a is zero )
            announce that quadratic coefficient can't be zero
    3b. else
             1. calculate discriminant
             2a. if (roots are imaginary)
                         announce that roots are imaginary
             2b. else
                       1. calculate one root
                       2a. if ( eqtn has a double root )
                              print it
                       2b. else
                               calculate 2nd root
                                print both roots

 


Due Tuesday  10/10

1. Read Hubbard 3.8-3.9
2. Review Questions 3.10-3.12 on p. 49.
3. Use the Triangle Inequality to revise the triangle classification program that was due on Friday to enable it to
    determine when lengths (a, b, c) don't form a triangle. Do NOT test for non-positive lengths.
4. Run the program. Does the Triangle Inequality catch non-positive candidate lengths like (5, 0, 4) and
    (-1, 9, 8)?

     Specifications:
     When your program determines and announces that lengths (a, b, c) don't form a triangle, it shouldn't
      follow up this announcement by classifying the triangle anyway.
      EXAMPLE OF WHAT SHOULDN'T HAPPEN:
      Enter sides a b c (spaces between numbers): 9 2 4
    
       The lengths don't form a triangle. 
       Triangle is obtuse.

5. Use your browser to copy the short program started below to your C++ editor. Review the sample output
    frames before completing the program in a fashion that enables it to behave as specified.

Converting entered character to lower case
Enter character: H
Lower case 'H' is 'h'

Converting entered character to lower case
Enter character: q
'q'  can't be converted lower case
Converting entered character to lower case
Enter character: ?
'?'  can't be converted lower case
// FILE: convert.cpp
// PURPOSE: Use decisions and ASCII collating sequence to write specfied program
#include <iostream.h>
int main() {
  char ch, ch2;  
  cout << "\n\n\n\n\n" << "Converting entered character to lower case" << endl << endl;
  cout << "Enter character: ";  cin >> ch;
  //---------------------------------------------------------------------------
  // YOUR CODE:

 
//---------------------------------------------------------------------------
  return 0;
}