Monday, December 12, 2016

Merge Sort - Monday Dec. 12

Presentations ...

Code ...


//
//  mergesort
//

#include <iostream>
#include <vector>
#include <string>
#include <chrono>
using namespace std;

string chars = "qwertyuioplkjhgfdsazxcvbnm";
int charsPerString = 8;
int stringsPerVector = 20000;

char randomChar() {
    return chars[rand() % chars.size()];
}

string makeRandomString() {
    string s;
    for (int i=0; i<charsPerString; i++) {
        s = s + randomChar();
    }
    return s;
}

vector<string> makeRandomStrings() {
    vector<string> vs;
    for (int i=0; i<stringsPerVector; i++) {
        vs.push_back(makeRandomString());
    }
    return vs;
}

void printVector (vector<string> &vs) {
    for (int i=0; i<vs.size(); i++) {
        cout << vs[i] << endl;
    }
    cout << endl;
}

void bubblesort (vector<string> &vs) {
    for (int i=0; i<vs.size()-1; i++) {
        for (int j=0; j<vs.size()-i-1; j++) {
            if (vs[j] > vs[j+1]) {
                string swapper = vs[j];
                vs[j] = vs[j+1];
                vs[j+1] = swapper;
            }
        }
    }
}

vector<string> merge (vector<string> &a, vector<string> &b) {
    
    // create a new deck
    vector<string> result (a.size() + b.size());
    
    // i -> first deck (a)
    // j -> second deck (b)
    int i = 0;
    int j = 0;
    
    // k -> result deck
    for (int k=0; k<result.size(); k++) {
        
        // finished with a and b?
        if (i >= a.size() && j >= b.size()) {
            break;
        }
        
        // finished with a?
        else if (i >= a.size()) {
            result[k] = b[j++];
        }
        
        // finished with b?
        else if (j >= b.size()) {
            result[k] = a[i++];
        }
        
        // compare
        else if (a[i] < b[j]) {
            result[k] = a[i++];
        }
        else {
            result[k] = b[j++];
        }
    }
    return result;
}

vector<string> partial (vector<string> &vs, long start, long end) {
    vector<string> result (end-start+1);
    for (int i=0; i<result.size(); i++) {
        result[i] = vs[start+i];
    }
    return result;
}

vector<string> mergeSort(vector<string> &vs) {
    
    // check base case for recursion
    if (vs.size() <= 1) {
        return vs;
    }
    
    // find midpoint
    long mid = vs.size() / 2;
    
    // divide into two
    vector<string> lowerHalf = partial (vs, 0, mid-1);
    vector<string> upperHalf = partial (vs, mid, vs.size()-1);
    
    // sort using mergeSort
    vector<string> lowerSorted = mergeSort(lowerHalf);
    vector<string> upperSorted = mergeSort(upperHalf);
    
    // merge the two halves
    return merge(lowerSorted, upperSorted);
}


int main(int argc, const char * argv[]) {
 
    vector<string> unsorted = makeRandomStrings();
    
    printVector (unsorted);
    
    auto beforeMerge = chrono::high_resolution_clock::now();
    vector<string> sorted = mergeSort(unsorted);
    auto afterMerge = chrono::high_resolution_clock::now();
    auto mergeElapsedTime = afterMerge - beforeMerge;
    
    printVector (sorted);
    
    auto beforeBubble = chrono::high_resolution_clock::now();
    bubblesort (unsorted);
    auto afterBubble = chrono::high_resolution_clock::now();
    auto bubbleElapsedTime = afterBubble - beforeBubble;
    
    printVector (unsorted);
    
    cout << "Merge Sort: " << mergeElapsedTime.count() << endl;
    cout << "Bubble Sort: " << bubbleElapsedTime.count() << endl;
    cout << "Improvement factor: " << bubbleElapsedTime / mergeElapsedTime << endl;
    
    return 0;
}



Thursday, December 8, 2016

Merge Sort vs. Bubble Sort

I wrote a program that creates 500,000 random strings and sort them twice, once using Merge Sort, and once using Bubble Sort. The Merge Sort completed almost immediately. The Bubble Sort ran for hours ... I started it before lunch, and it just finished.

I added code to calculate the elapsed time for each sort. The Merge Sort was faster by a factor of 3533.

We can code this project together on Monday night. It's 150 lines of code, so bring your computer and be prepared to type fast.


Wednesday, December 7, 2016

Multiple choice final exam

The multiple choice final exam is not posted yet. It has 40 questions. There will be a time limit of 3 hours. It will cover these topics:
  • Most important skill for computer programmers
  • Compiling vs. interpreting code
  • Portability
  • Algorithms
  • Strings
  • Variables
  • Keywords
  • Statement
  • Functions
  • Return values
  • Assignment
  • Calling a function
  • Integer division
  • Recursion
  • Scaffolding
  • Debugging
  • Dead code
  • Void
  • Generalization
  • Object
  • Traversal
  • Compound data types
  • Call by reference
  • Structure
  • Instance variable
  • Pure function
  • Const
  • Top-down design
  • Vector
  • Loops
  • Random numbers
  • Constructor
  • CPP and H files
  • Ordered and unordered sets
  • Binary / Bisection search
  • Merge sort vs. Bubble sort
  • Pseudocode 



    Monday, December 5, 2016

    split

    void split(const string &s, char delim, vector<string> &elems) {
        //-------------------------------------------------------
        // This function splits a line into a vector of strings
        // based on a separating character, such as a comma.
        // s is the input string
        // delim is the separating character.
        // elems is the vector that will hold the output.
        //-------------------------------------------------------
        stringstream ss;
        ss.str(s);
        string item;
        elems.clear();
        while (getline(ss, item, delim)) {
            elems.push_back(item); }

    }

    Lab Materials for Dec. 5

    Presentation
    Data
    Fields: City, Province, Population, Population Growth in %
    Toronto,ON,2615060,9.63
    Montreal,QC,1649519,6.62
    Calgary,AB,1096833,42.8
    Ottawa,ON,833391,22.5
    Edmonton,AB,812201,31.79
    Missasauga,ON,713443,31.06
    Winnipeg,MB,663617,7.3
    Vancouver,BC,603502,17.41
    Brampton,ON,523911,96.31
    Hamilton,ON,519949,11.15
    


    The code:

    //
    //  main.cpp
    //  Dec5Class
    //
    //  Created by Mark Brautigam on 12/5/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    #include <vector>
    #include <string>
    #include <fstream>
    #include <sstream>
    #include <iomanip>
    
    using namespace std;
    
    struct City {
        string name;
        string province;
        int population;
        double delta;
    };
    
    string baseDir = "/Users/markb/Desktop/";
    
    void split(const string &s, char delim, vector<string> &elems) {
        //-------------------------------------------------------
        // This function splits a line into a vector of strings
        // based on a separating character, such as a comma.
        // s is the input string
        // delim is the separating character.
        // elems is the vector that will hold the output.
        //-------------------------------------------------------
        stringstream ss;
        ss.str(s);
        string item;
        elems.clear();
        while (getline(ss, item, delim)) {
            elems.push_back(item); }
    }
    
    void readFileIntoVector (string filepath, vector<City> &vc) {
        ifstream input;
        input.open(baseDir + "canada.csv");
        string line;
        vector<string> fields;
        City city;
        while (!input.eof()) {
            // input >> line;
            getline(input, line);
            if (line.length() < 2)
                continue;
            split (line, ',', fields);
            city.name = fields[0];
            city.province = fields[1];
            city.population = atoi(fields[2].c_str());
            city.delta = atof (fields[3].c_str());
            vc.push_back(city);
        }
        return;
    }
    
    void printData(const vector<City> &vc, string fn) {
        ofstream output;
        output.open (fn);
        
        for (int i=0; i<vc.size(); i++) {
            output.width(15);
            output << left << vc[i].name << " ";
            output.width(5);
            output << left << vc[i].province << " ";
            output.width(10);
            output << right << vc[i].population << " ";
            output.width(8);
            output << right << fixed << setprecision(2) << vc[i].delta << " ";
            output << endl;
        }
        output.close();
    }
    
    bool outOfOrder(const City &a, const City &b, int sortfield) {
        switch (sortfield) {
            case 0 : return a.name       > b.name;
            case 1 : return a.province   > b.province;
            case 2 : return a.population > b.population;
            case 3 : return a.delta      > b.delta;
            default : return a.name      > b.name;
        }
    }
    
    void bubblesort (vector<City> &vc, int sortfield) {
        for (int i=0; i<vc.size(); i++) {
            for (int j=0; j<vc.size()-1; j++) {
                // if (vc[j].delta > vc[j+1].delta) {
                if (outOfOrder (vc[j], vc[j+1], sortfield)) {
                    City swap = vc[j];
                    vc[j] = vc[j+1];
                    vc[j+1] = swap;
                }
            }
        }
    }
    
    int requestSortfield() {
        cout << "Choose a field to sort on by number:\n";
        cout << "0 : City\n";
        cout << "1 : Province\n";
        cout << "2 : Population\n";
        cout << "3 : Population Change\n";
        cout << "Your choice: ";
        int user;
        cin >> user;
        return user;
    }
    
    int main(int argc, const char * argv[]) {
        
        vector<City> cities;
        
        readFileIntoVector (baseDir + "canada.csv", cities);
        int sortfield = requestSortfield();
        bubblesort (cities, sortfield);
        
        string outputFileName =
            baseDir + "canada-sorted-" + to_string(sortfield) + ".txt";
        
        printData(cities, outputFileName);
        
        return 0;
    }
    


    Saturday, December 3, 2016

    Final Exam: Coding Portion

    Here are the instructions: Final exam

    Here is the data you will need:
    1,Dublin,Dublin,1273069,1380.8,Leinster,7.02
    2,Antrim,Ballymena,618108,202.9,Ulster,1.80
    3,Down,Downpatrick,531665,215.6,Ulster,8.72
    4,Cork,Cork,519032,69.0,Munster,7.84
    5,Galway,Galway,250541,40.7,Connacht,8.15
    6,Londonderry,Coleraine,247132,119.1,Ulster,4.78
    7,Kildare,Naas,210312,124.1,Leinster,12.87
    8,Limerick,Limerick,191809,69.4,Munster,4.21
    9,Meath,Navan,184135,78.6,Leinster,13.08
    10,Tyrone,Omagh,177986,54.5,Ulster,8.37
    11,Armagh,Armagh,174792,131.8,Ulster,7.26
    12,Donegal,Lifford,161137,32.9,Ulster,9.42
    13,Tipperary,Nenagh,158754,36.8,Munster,6.37
    14,Kerry,Tralee,145502,30.1,Munster,4.05
    15,Wexford,Wexford,145320,61.2,Leinster,10.30
    16,Wicklow,Wicklow,136640,67.4,Leinster,8.28
    17,Mayo,Castlebar,130638,23.3,Connacht,5.49
    18,Louth,Dundalk,122897,148.7,Leinster,10.45
    19,Clare,Ennis,117196,33.8,Munster,5.63
    20,Waterford,Dungarvan,113795,61.2,Munster,5.40
    21,Kilkenny,Kilkenny,95419,46.0,Leinster,8.98
    22,Westmeath,Mullingar,86164,46.7,Leinster,8.59
    23,Laois,Portlaoise,80559,46.8,Leinster,20.13
    24,Offaly,Tullamore,76687,38.3,Leinster,8.21
    25,Cavan,Cavan,73183,37.7,Ulster,14.34
    26,Sligo,Sligo,65393,35.5,Connacht,7.39
    27,Roscommon,Roscommon,64065,25.0,Connacht,9.01
    28,Fermanagh,Enniskillen,61170,36.1,Ulster,6.33
    29,Monaghan,Monaghan,60483,46.7,Ulster,8.01
    30,Carlow,Carlow,54612,60.8,Leinster,8.47
    31,Longford,Longford,39000,35.7,Leinster,13.40
    32,Leitrim,Carrick-on-Shannon,31796,19.9,Connacht,9.84
    


    Wednesday, November 30, 2016

    Homework 21

    Homework 21 has you add a few things to the code we wrote in class last Monday night.

    Homework 21

    There may be one or two more quick homework assignments, one dealing with Merge Sort, after next Monday, and one dealing with pointers, which we may talk about next Monday.


    Monday, November 28, 2016

    Lab materials for Nov. 28

    Presentation:
    Shuffle Code
    Code
    //
    //  main.cpp
    //  Nov28Cards
    //
    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;
    
    enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
    
    enum Rank { ACE=1, TWO, THREE, FOUR, FIVE, SIX, SEVEN,
        EIGHT, NINE, TEN, JACK, QUEEN, KING };
    
    struct Card {
        Suit suit;
        Rank rank;
        
        Card();
        Card(Suit suit, Rank rank);
        void print();
        bool equals (const Card &c2) const;
        bool isGreater (const Card &c2) const;
    };
    
    // --------------------------------------------------
    // Card methods
    // --------------------------------------------------
    bool Card::isGreater(const Card &c2) const {
        if (suit > c2.suit) return true;
        if (suit < c2.suit) return false;
        
        return (rank > c2.rank);
    }
    
    Card::Card() {
        suit = CLUBS;
        rank = ACE;
    }
    
    Card::Card(Suit suit, Rank rank) {
        this->suit = suit;
        this->rank = rank;
    }
    
    void Card::print () {
        vector <string> suits (4);
        vector <string> ranks (14);
        suits[0] = "Clubs";
        suits[1] = "Diamonds";
        suits[2] = "Hearts";
        suits[3] = "Spades";
        
        ranks[1] = "Ace";
        ranks[2] = "2";
        ranks[3] = "3";
        ranks[4] = "4";
        ranks[5] = "5";
        ranks[6] = "6";
        ranks[7] = "7";
        ranks[8] = "8";
        ranks[9] = "9";
        ranks[10] = "10";
        ranks[11] = "Jack";
        ranks[12] = "Queen";
        ranks[13] = "King";
        
        cout << ranks[rank] << " of " << suits[suit] << endl;
    }
    
    bool Card::equals(const Card &c2) const {
        return (suit == c2.suit && rank == c2.rank);
    }
    
    // --------------------------------------------------
    // other methods
    // --------------------------------------------------
    bool equals (const Card &c1, const Card &c2) {
        return (c1.suit == c2.suit && c1.rank == c2.rank);
    }
    
    vector <Card> deck (52);
    
    void printDeck(vector <Card> &deck) {
        for (int i=0; i<deck.size(); i++) {
            deck[i].print();
        }
    }
    // --------------------------------------------------
    // Binary search
    // --------------------------------------------------
    
    int findBisect (const Card &card,
                    const vector<Card> &deck,
                    int low,
                    int high) {
        
        cout << low << ", " << high << endl; // debug
        
        if (high < low) return -1;
        
        int mid = (low + high) / 2;
        
        if (equals (deck[mid], card)) return mid;
        
        if (deck[mid].isGreater(card)) {
            return findBisect (card, deck, low, mid-1);
        } else {
            return findBisect(card, deck, mid+1, high);
        }
    }
    
    int myrandom(int i) { return rand() % i; }
    
    // --------------------------------------------------
    // start here
    // --------------------------------------------------
    
    int main(int argc, const char * argv[]) {
    
        Card threeOfClubs (CLUBS, THREE);
        threeOfClubs.print();
        
        Card jack (DIAMONDS, JACK);
        jack.print();
        
        cout << threeOfClubs.equals(jack) << endl;
        
        cout << equals (threeOfClubs, jack) << endl;
        
        Card another3clubs (CLUBS, THREE);
        cout << threeOfClubs.equals(another3clubs) << endl;
        
        cout << jack.isGreater(threeOfClubs) << endl;
        
        // nested loop
        int i = 0;
        for (Suit suit = CLUBS; suit <=SPADES; suit = Suit(suit+1)) {
            for (Rank rank=ACE; rank<=KING; rank = Rank(rank+1)) {
                deck[i].rank = rank;
                deck[i].suit = suit;
                i++;
            }
        }
        
        printDeck(deck);
        
        cout << findBisect(deck[24], deck, 0, 51);
        
        Card fake (DIAMONDS, Rank(15));
        cout << findBisect (fake, deck, 0, 51);
        
        srand(time(0));
        random_shuffle(deck.begin(), deck.end(), myrandom);
        printDeck(deck);
        
        return 0;
    }
    

    Friday, November 25, 2016

    Coding Assignments 19 and 20

    Assignment 19. Finish and extend the complex number class.

    Assignment 20. Create a rational number class with arithmetic functions.

    These assignments will be due one week from tonight, Friday night, Dec. 2.


    Homework answers

    This is my code that accomplishes some of the assignments. In general, my code is much simpler than yours.

    I'm sorry, I posted this a few days ago, but to the wrong blog!

    Because I am posting this code, as of today I will not accept late or resubmitted work for assignments 3, 4, 5, 7, 8, or 9.

    I intend to post the rest of the assignments shortly. I want you to be able to study my code as you study for the final exam. If you intend to turn in assignments 10 through 15, please do so right now. Once I publish the code for those assignments, I will no longer accept your work for credit.





    Monday, November 21, 2016

    Complex Number Class

    //
    //  main.cpp
    //  complex
    //
    //  Created by Mark Brautigam on 11/21/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    #include <cmath>
    #include <assert.h>
    using namespace std;
    
    class Complex {
    private:
        double real, imag; // rectangular coordinates
        double mag, theta; // polar coordinates
        bool cartesian, polar; // which set is valid?
        
        void calculateCartesian();
        void calculatePolar();
        
    public:
        Complex();
        Complex(double r, double i);
        double getReal();
        double getImag();
        double getMag();
        double getTheta();
        void printCartesian();
        void printPolar();
        void setPolar (double m, double t);
    };
    
    void Complex::setPolar (double m, double t) {
        mag = m;
        theta = t;
        cartesian = false;
        polar = true;
    }
    
    
    void Complex::printCartesian() {
        cout << getReal() << " + " << getImag() << "i\n";
    }
    
    void Complex::printPolar() {
        cout << getMag() << " e^ " << getTheta() << "i\n";
    }
    
    void Complex::calculateCartesian() {
        assert(polar);
        real = mag * cos (theta);
        imag = mag * sin (theta);
        cartesian = true;
    }
    
    // not in textbook
    void Complex::calculatePolar() {
        assert (cartesian);
        mag = sqrt (real * real + imag * imag);
        theta = atan ( imag / real );
        polar = true;
    }
    
    Complex::Complex () {
        cartesian = false;
        polar = false;
    }
    
    Complex::Complex (double r, double i) {
        real = r;
        imag = i;
        cartesian = true;
        polar = false;
    }
    
    double Complex::getReal() {
        if (cartesian == false)
            calculateCartesian();
        return real;
    }
    
    // not in textbook
    double Complex::getImag() {
        if (cartesian == false)
            calculateCartesian();
        return imag;
    }
    
    // not in textbook
    double Complex::getMag() {
        if (polar == false)
            calculatePolar();
        return mag;
    }
    
    // not in textbook
    double Complex::getTheta() {
        if (polar == false)
            calculatePolar();
        return theta;
    }
    
    Complex add (Complex a, Complex b) {
        double real = a.getReal() + b.getReal();
        double imag = a.getImag() + b.getImag();
        Complex sum (real, imag);
        return sum;
    }
    
    Complex multiply (Complex a, Complex b) {
        double mag = a.getMag() * b.getMag();
        double theta = a.getTheta() + b.getTheta();
        Complex product;
        product.setPolar (mag, theta);
        return product;
    }
    
    int main(int argc, const char * argv[]) {
        
        Complex c (2.0, 3.0);
        c.printCartesian();
        c.printPolar();
        
        Complex d (17.0, 42.0);
        Complex sum = add (c, d);
        sum.printCartesian();
        
        Complex e (2, 2);
        Complex product = multiply (c, e);
        product.printCartesian();
        
        Complex bad;
        bad.printCartesian();
        
        cout << "I got this far!";
        
        return 0;
    }
    

    Presentation and code for Nov. 21 - Classes

    Presentations:

    Starting point code for tonight:
    #include <iostream>
    #include <string>
    #include <cmath>
    #include <vector>
    using namespace std;
    
    struct Point {
        double x, y;
        
        Point (double xx, double yy);
        Point (Point &p);
        Point ();
        
        double distanceTo (Point other);
        string contents ();
        void print ();
    };
    
    struct Triangle {
        Point a, b, c;
        
        Triangle (Point aa, Point bb, Point cc);
        string contents ();
        double area ();
    };
    
    // POINT functions
    //
    // this causes problems and I didn't figure out why
    //
    Point::Point (double xx, double yy) {
      x = xx;
      y = yy;
    }
     
    Point::Point (Point &p) {
      x = p.x;
      y = p.y;
    }
    
    Point::Point () {
        x = 0; y = 0;
    }
    
    double Point::distanceTo (Point other) {
        // Pythagoream Theorem a^2 + b^2 = c^2
        double dx = other.x - x;
        double dy = other.y - y;
        return (sqrt (dx * dx + dy * dy));
    }
    
    string Point::contents () {
        return  "{ " + to_string(x) + ", " +
        to_string(y) + " }";
    }
    
    void Point::print () {
        cout << contents ();
    }
    
    // TRIANGLE functions
    //
    // Constructor
    //
    Triangle::Triangle (Point aa, Point bb, Point cc) {
        a = aa;
        b = bb;
        c = cc;
    }
    
    string Triangle::contents () {
        return "{ " + a.contents() + ", " +
        b.contents() + ", " +
        c.contents() + " }";
    }
    
    double Triangle::area () {
        // Compute the area of a triangle from its corner points
        
        // 1. Compute the lengths of the side
        double dbc = b.distanceTo(c);
        double dac = a.distanceTo(c);
        double dab = a.distanceTo(b);
        
        // 2. Plug the lengths into the standard formula
        double s = (dbc + dac + dab) / 2;
        double t = s * (s-dbc) * (s-dac) * (s-dab);
        return sqrt (t); // <cmath>
    }
    
    int main(int argc, const char * argv[]) {
        
        Point p ( 42, 17 );
        Point q ( 17, 42 );
        double d = p.distanceTo(q);
        cout << d << endl;
        d = q.distanceTo(p);
        cout << d << endl;
        cout << p.contents();
        cout << endl;
        
        Triangle t ( p, q, { 100, 100 } );
        cout << t.area();
        cout << endl;
    
        return 0;
    }
    

    Tuesday, November 15, 2016

    Materials for Monday Nov. 14 Lab

    Last night's topic was reading and writing files. There is no PowerPoint presentation this week. Here is a list of the main points:

    • Copy the colors in the next post into four text files: English.txt, French.txt, German.txt, and Spanish.txt.
    • Put the files in a place that you can easily type out the full path to. I suggest using your desktop or a folder on your desktop.
      • Mac desktop file example: /Users/markb/Desktop/French.txt
      • Windows desktop file example: c:\\Users\\davidf\\Desktop\\German.txt
      • Not that the Windows version has double backslashes. The backslash is an escape character in C++. In order to circumvent this, we escape the backslash itself by putting another backslash before it. You can look this up on the interwebs.
    • You must also have write permissions to the folder where you are going to put your files, if you are going to write new files into that folder.
    • Include <fstream> at the top of your code to get the file stream library functions.
    • An input file stream (reading a file) uses ifstream.
    • An output file stream (writing a file) uses ofstream.
    Code for reading a file into a vector and using its data:
    //
    //  main.cpp
    //  Nov14
    //
    
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    #include <cmath>
    using namespace std;
    
    // This is a forward declaration
    int lookupColor (vector<string> , string );
    
    int main(int argc, const char * argv[]) {
        
        vector<string> colors;
        vector<int> colorNumbers;
        
        string s;
        cout << "What language would you like to use?";
        cout << "([E]nglish, [F]rench, [G]erman, [S]panish)\n";
        cin >> s;
        
        // Choose the file based on the user choice.
        // Could you put this in a separate function?
        // Remember, the function should not open the file,
        // because we don't do I/O operations in a function.
        // Instead, the function should return the file name
        // so the main function can open it.
        ifstream infile;
        switch (s[0]) {
            case 'E':
            default :
                infile.open("/Users/markb/Desktop/English.txt");
                break;
            case 'F':
                infile.open("/Users/markb/Desktop/French.txt");
                break;
            case 'G':
                infile.open("/Users/markb/Desktop/German.txt");
                break;
            case 'S':
                infile.open("/Users/markb/Desktop/Spanish.txt");
                break;
        }
    
        // Example of Windows path using escaped backslashes
        // c:\\Users\\davidf\\Desktop
    
        // Could we make the following block into a function that 
        // reads the contents of the file into a vector?
    
        // Check first to make sure we actually opened the file successfully
        if (infile.good()) {
    
            // Loop through all lines of the file until we reach the end of the file
            while (!infile.eof()) {
                // infile >> s;
                getline (infile, s);
                // cout << s << endl;
                colors.push_back(s);
            }
        }
        
        // Get the user's input (3 colors)
        // Could this be made into a function? Should it be?
        cout << "Please enter the color names: ";
        
        for (int i=1; i<=3; i++) {
            cout << i << ":";
            cin >> s;
            colorNumbers.push_back(lookupColor(colors, s));
        }
        
        // cout << colorNumbers[0] << " " << colorNumbers[1] << " " << colorNumbers[2];
        
        // cout << s << " has value " << lookupColor(colors, s) << endl;
        
        // Do the computation to get the resistor value.
        // Could this be made into a function? Should it be?
        // Remember, we shouldn't actually write to the output (cout)
        // from inside a function. 
        cout << "Resistance is " <<
            (colorNumbers[0] * 10 + colorNumbers[1]) *
            pow (10, colorNumbers[2]) << " ohms." << endl;
        
        return 0;
    }
    
    // Why does this function need both the haystack (vector)
    // and the needle? Couldn't we just make the colors vector
    // global and access the global variable? 
    int lookupColor (vector<string> haystack, string needle) {
        for (int i=0; i<haystack.size(); i++) {
            if (haystack[i] == needle) {
                return i;
            }
        }
        return -1;
    }
    
    


    Code for writing a file to the disk:
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main(int argc, const char * argv[]) {
        
        ofstream outfile;
        outfile.open ("/Users/markb/Desktop/names.txt");
        
        cout << "Please input names or a blank line when finished.\n";
        string s;
        
        do  {
            getline (cin, s);
            // cout << "ok";
            outfile << s << endl;
        }
            while (s != "");
        
        return 0;
    }
    


    Here is the main function composed of other functions that do all the work. Is this main function easier to read? If you want to complete it, you just need to write all the other functions that get invoked.
    int main(int argc, const char * argv[]) {
        
        vector<string> colors;
        vector<long> colorNumbers;
        
        // This function will prompt user for language, which
        // is OK because that is its primary purpose.
        string lang = getLanguage();
        
        ifstream infile;
        infile.open (getFileName(lang));
        
        if (infile.good()) {
            readFileIntoVector (infile, colors);
        }
        
        // This function will prompt user for colors, which
        // is OK because that is its primary purpose.
        getUserColorsIntoVector (colors, colorNumbers);
        
        cout << "Resistance is " << computeResistance(colorNumbers) << " ohms\n";
        
        return 0;
    }
    


    Monday, November 14, 2016

    Colors in various languages

    English
    Black
    Brown
    Red
    Orange
    Yellow
    Green
    Blue
    Violet
    Gray
    White
    
    Spanish
    Negro
    Marron
    Rojo
    Anaranjado
    Amarillo
    Verde
    Azul
    Violeta
    Gris
    Blanco
    
    French
    Noir
    Marron
    Rouge
    Orange
    Jaune
    Vert
    Bleu
    Violet
    Gris
    Blanc
    
    German
    Schwartz
    Braun
    Rot
    Orange
    Gelb
    Grun
    Blau
    Lila
    Grau
    Weiss
    

    Friday, November 11, 2016

    Coding Assignment 16

    Here is your assignment using structs with functions. You will create a Circle struct, with functions, similar to the Triangle struct we created in class last Monday night.

    This assignment is due one week from tonight (Friday, Nov. 18).

    Coding Assignment 16


    Monday, November 7, 2016

    Presentation and Code for Week 11

    Presentations:
    Starting point code:
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    double PI = acos(-1);
    
    struct Point {
        double x, y;
    };
    
    struct Triangle {
        Point a, b, c;
    };
    
    double dist (Point a, Point b) {
        // Pythagoream Theorem a^2 + b^2 = c^2
        double dx = a.x - b.x;
        double dy = a.y - b.y;
        return (sqrt (dx * dx + dy * dy));
    }
    
    double triangleArea (Triangle triangle) {
        // Compute the area of a triangle from its corner points
        
        // 1. Compute the lenghts of the side
        double a = dist(triangle.b, triangle.c);
        double b = dist(triangle.a, triangle.c);
        double c = dist(triangle.a, triangle.b);
        
        // 2. Plug the lengths into the standard formula
        double s = (a + b + c) / 2;
        double t = s * (s-a) * (s-b) * (s-c);
        return sqrt (t); // <cmath>
    }
    
    string pointContents (Point p) {
        return  "{ " + to_string(p.x) + ", " + 
                       to_string(p.y) + " }";
    }
    
    // NOT ADVISED
    string printContents (Point p) {
        cout  "{ " << to_string(p.x) << ", " << 
                      to_string(p.y) << " }";
    }
    
    string triangleContents (Triangle t) {
        return "{ " + pointContents(t.a) + ", " + 
                      pointContents(t.b) + ", " + 
                      pointContents(t.c) + " }";
    }
    

    Code at end of class.

    Triangle.hpp:
    //
    //  Triangle.hpp
    //  Nov07
    //
    
    #ifndef Triangle_hpp
    #define Triangle_hpp
    
    #include <string>
    using namespace std;
    
    struct Point {
        double x, y;
        
        double distanceTo (Point other);
        string contents ();
        void print ();
    };
    
    struct Triangle {
        Point a, b, c;
        
        Triangle (Point aa, Point bb, Point cc);
        string contents ();
        double area ();
    };
    
    #endif /* Triangle_hpp */
    


    Triangle.cpp:
    //
    //  Triangle.cpp
    //  Nov07
    //
    //  Created by Mark Brautigam on 11/7/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    #include <string>
    #include <cmath>
    #include "Triangle.hpp"
    using namespace std;
     
         // POINT functions
         //
         // this causes problems and I didn't figure out why
         //
         /*Point (double xx, double yy) {
         x = xx;
         y = yy;
         }
         
         Point (Point &p) {
         x = p.x;
         y = p.y;
         }*/
        
        double Point::distanceTo (Point other) {
            // Pythagoream Theorem a^2 + b^2 = c^2
            double dx = other.x - x;
            double dy = other.y - y;
            return (sqrt (dx * dx + dy * dy));
        }
        
        string Point::contents () {
            return  "{ " + to_string(x) + ", " +
            to_string(y) + " }";
        }
        
        void Point::print () {
            cout << contents ();
        }
    
    
         // TRIANGLE functions
         //
         // Constructor
         //
        Triangle::Triangle (Point aa, Point bb, Point cc) {
            a = aa;
            b = bb;
            c = cc;
        }
        
        string Triangle::contents () {
            return "{ " + a.contents() + ", " +
            b.contents() + ", " +
            c.contents() + " }";
        }
        
        double Triangle::area () {
            // Compute the area of a triangle from its corner points
            
            // 1. Compute the lengths of the side
            double dbc = b.distanceTo(c);
            double dac = a.distanceTo(c);
            double dab = a.distanceTo(b);
            
            // 2. Plug the lengths into the standard formula
            double s = (dbc + dac + dab) / 2;
            double t = s * (s-dbc) * (s-dac) * (s-dab);
            return sqrt (t); // <cmath>
        }
    


    main.cpp:
    //
    //  main.cpp
    //  Nov07
    //
    #include <iostream>
    #include <cmath>
    #include <vector>
    #include "Triangle.hpp"
    using namespace std;
    
    // Swap function does not work unless the parameters
    // are passed by reference using &
    // 
    void swap (int &a, int &b) {
        int temp = a;
        a = b;
        b = temp;
    }
    
    int main(int argc, const char * argv[]) {
        
        vector<int> tester = { 1, 2, 3, 4, 5 };
        for (int i=0; i<tester.size(); i++) {
            cout << tester[i] << " ";
        }
        swap (tester[1], tester[2]);
        for (int i=0; i<tester.size(); i++) {
            cout << tester[i] << " ";
        }
        
        Point p = { 42, 17 };
        Point q = { 17, 42 };
        double d = p.distanceTo(q);
        cout << d;
        d = q.distanceTo(p);
        cout << d;
        cout << p.contents();
        cout << endl;
        
        Triangle t ( p, q, { 100, 100 } );
        cout << t.area();
        cout << endl;
    
        return 0;
    }
    


    Wednesday, November 2, 2016

    Coding Assignments 13, 14, 15

    These assignments are due at 11:59 pm next Wednesday night, Nov. 9.

    Coding Assignment 13

    This assignment uses random numbers and a for loop to create random hexadecimal colors.


    Coding Assignment 14

    This assignment uses two vectors and a for loop to translate color names from English to Spanish.


    Coding Assignment 15

    This assignment uses a vector and two nested for loops to sort strings entered by the user.


    Extra Credit:

    Look up the more optimized version of Bubblesort and modify Assignment 15 to use it. I suggest you use a standard data structures reference book such as Aho, Hopcroft, and Ullman. If you find code on the internet, it may or may not be correct.



    Monday, October 31, 2016

    October 31 PowerPoints: Vector

    Presentations:

    Comments

    • The code for srand() did not work because we were using the random() function to get random numbers. The textbook suggested random()  I don't even know where random() comes from ... it's not in any standard reference. 
    • Instead, use the function rand(). This function works with the function srand() to give you different random numbers each time.
    • insert() is not so difficult to use, but it requires iterators, something we haven't talked about yet. See the code below.

    Code
    //
    //  main.cpp
    //  Oct31
    //
    //  Created by Mark Brautigam on 10/31/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    #include <vector>
    #include <cmath>
    #include <ctime>
    using namespace std;
    
    vector<string> resistorColors = { "black", "brown", "red", "orange",
        "yellow", "green", "blue", "violet", "gray", "white" };
    
    int colorToNumber (string color) {
        int colorFoundWhere = -1;
        for (int i=0; i<resistorColors.size(); i++) {
            if (resistorColors[i] == color) {
                colorFoundWhere = i;
                break;
            }
        }
        return colorFoundWhere;
    }
    
    int resistorCalculation (string c1, string c2, string c3) {
        int a = colorToNumber(c1);
        int b = colorToNumber(c2);
        int p = colorToNumber(c3);
        return (a * 10 + b) * pow(10, p);
    }
    
    
    int main(int argc, const char * argv[]) {
    
        vector<double> temperatures;
    //    vector<string> resistorColors;
        
        cout << resistorColors.size() <<endl;
        cout << resistorColors.max_size() <<endl;
        cout << resistorColors.capacity() <<endl;
        // resistorColors.resize(32);
        // cout << resistorColors.size() <<endl;
        // cout << resistorColors.max_size() <<endl;
        // cout << resistorColors.capacity() <<endl;
        
        // cout << resistorColors[17] << endl;
        
        // temperatures.resize(4);
        // cout << temperatures[2] << endl;
        
        cout << resistorColors[1] << endl;
        cout << resistorColors.size() <<endl;
        cout << resistorColors.capacity() <<endl;
        
        // cout << resistorColors << endl; // doesn't work
        
        for (int i=0; i<resistorColors.size(); i++) {
            cout << resistorColors[i] << endl;
            // i++; // DON'T do this
        }
        
        int i=0;
        while (i<resistorColors.size()) {
            cout << resistorColors[i] << endl;
            i++; // don't forget this
        }
        
        // find a color
        string colorToFind = "red";
        int colorFoundAtIndex = colorToNumber("green");
        
        cout << colorToFind << " is number " << colorFoundAtIndex << endl;
        
        cout << "Blue is " << colorToNumber("blue") << endl;
        cout << "Orange is " << colorToNumber("orange") << endl;
        
        cout << resistorCalculation("yellow", "violet", "orange") << endl;
        
        // temperatures.resize(0);
        cout << temperatures.size() << endl;
        cout << temperatures.capacity() << endl;
        temperatures.push_back(98.6);
        cout << temperatures.size() << endl;
        cout << temperatures.capacity() << endl;
        temperatures.push_back(32.0);
        cout << temperatures.size() << endl;
        cout << temperatures.capacity() << endl;
        temperatures.push_back(212);
        cout << temperatures.size() << endl;
        cout << temperatures.capacity() << endl;
        temperatures.push_back(212);
        cout << temperatures.size() << endl;
        cout << temperatures.capacity() << endl;
        temperatures.push_back(212);
        cout << temperatures.size() << endl;
        cout << temperatures.capacity() << endl;
        
        temperatures[6] = -432;
        cout << temperatures.size() << endl;
        cout << temperatures.capacity() << endl;
        
        // I wrote this wrong in class, it's a little more complicated
        vector<double>::iterator it;
        it = temperatures.begin();
        temperatures.insert(it+5, 100);
        cout << temperatures.size() << endl;
        cout << temperatures.capacity() << endl;
    
        // generate random numbers between 1 and 100 instead of 0 to 99
        cout << 1 + rand() % 100 << endl;
        cout << 1 + rand() % 100 << endl;
        cout << 1 + rand() % 100 << endl;
        cout << 1 + rand() % 100 << endl;
        
        vector<int> randomNumbers;
        srand(time(NULL));
        
        // initialize with 10 random numbers
        for (int i=0; i<10; i++) {
            randomNumbers.push_back(rand() % 100);
        }
        
        // print the vector of random numbers
        cout << "---------\n";
        for (int i=0; i<randomNumbers.size(); i++) {
            cout << randomNumbers[i] << endl;
        }
        
        // bubble sort
        for (int i=0; i<randomNumbers.size(); i++) {
            for (int j=0; j<randomNumbers.size()-1; j++) {
                if (randomNumbers[j] > randomNumbers[j+1]) {
                    // out of order - swap them
                    int temp = randomNumbers[j];
                    randomNumbers[j] = randomNumbers[j+1];
                    randomNumbers[j+1] = temp;
                }
            }
        }
        
        // print the vector of sorted numbers
        cout << "---------\n";
        for (int i=0; i<randomNumbers.size(); i++) {
            cout << randomNumbers[i] << endl;
        }
        
        // calculate positions of numbers on a clock
        // We will talk about top-down design again next week
        /*
        void printClockNumber(int clock) {
            double degrees = clockToDegrees(clockNumber);
            double radians = degreesToRadians(degrees);
            double x = getX (radians, center, radius);
            double y = getY (radians, center, radius);
        }
         */
    
        return 0;
    }
    



    Thursday, October 27, 2016

    Using the to_string() function

    The to_string() function is described on these reference pages:
    On both pages, you'll see that there are code examples of how to use the function. Both examples have the following line near the top of the code:

    #include <string> // std::string, std::to_string

    Unfortunately, different programming environments may have different requirements regarding this include statement. The function is part of the standard C++ library, but you may (or may not) have to put this include directive in your code.
    • On Monday, I did not have to put this line in my Xcode file.
    • Others have reported they must use this line if using DevC++.
    • Visual Studio? I have no reports.
    • Unix? I have no reports.
    This applies to other functions and libraries too. There may be inconsistencies between the different platforms. The lesson here is to keep your eyes on the reference pages and use the include directives they suggest, just to be safe. To be fair, we did discuss this on Monday night, but things were going pretty fast.

    In the future, it's a good idea to always include <iostream>, <string>, <cmath>, and starting soon, <vector>.


    Wednesday, October 26, 2016

    Coding Assignments 11 and 12

    These assignments deal with structures (structs). The first one adds circles to the geometric features we implemented in class. The second one asks you to create a struct to hold a pizza order.

    Coding Assignment 11: Geometry

    Coding Assignment 12: Pizza Order

    Since it is now the evening of Wed. Oct. 26, these assignments will be due one week from tonight, before midnight on Wed. Nov 2.


    Monday, October 24, 2016

    October 24 PowerPoints: Structures

    Presentations:

    Code
    //
    //  Oct24
    //
    
    #include <iostream>
    #include <cmath>
    // #include "math.h"
    using namespace std;
    
    struct Point {
        double x, y;
    };
    
    struct Size {
        double width, height;
    };
    
    struct Triangle {
        Point a, b, c;
    };
    
    struct Rectangle {
        Point topLeft;
        Size widthHeight;
    };
    
    struct Circle {
        double radius;
        Point center;
    };
    
    struct Ellipse {
        Point f1, f2;
        double foo;
    };
    
    struct Rotation {
        double angle;
        Point center;
    };
    
    struct Ellipse2 {
        Point center;
        double radiusX;
        double radiusY;
        Rotation rotation;
    };
    
    struct Polygon {
        int numberOfPoints;
        Point p1, p2, p3, p4, p5, p6, p7, p8;
    };
    
    struct ResistorColor {
        std::string color;
        int value;
    };
    
    double dist (Point a, Point b) {
        // Pythagoream Theorem a^2 + b^2 = c^2
        double dx = a.x - b.x;
        double dy = a.y - b.y;
        return (sqrt (dx * dx + dy * dy));
    }
    
    double triangleArea (Triangle triangle) {
        // Compute the area of a triangle from its corner points
        
        // 1. Compute the lengths of the side
        double a = dist(triangle.b, triangle.c);
        double b = dist(triangle.a, triangle.c);
        double c = dist(triangle.a, triangle.b);
        
        // 2. Plug the lengths into the standard formula
        double s = (a + b + c) / 2;
        double t = s * (s-a) * (s-b) * (s-c);
        return sqrt (t); // <cmath>
    }
    
    string drawTriangle (Triangle t, string fill, string stroke) {
        return "<polygon points='" +
           to_string(t.a.x) + " " + to_string(t.a.y) + " " +
           to_string(t.b.x) + " " + to_string(t.b.x) + " " +
           to_string(t.c.x) + " " + to_string(t.c.y) + " z' " +
           "fill='" + fill + "' stroke='" + stroke + "' />";
    }
    
    
    int main(int argc, const char * argv[]) {
        
        Triangle t = {
            { -3, -4 },
            { 6, 0 },
            { 0, 8 } };
        cout << triangleArea (t) << endl;
        
        cout << drawTriangle (t, "red", "blue") << endl;
        
        return 0;
    }
    



    Monday, October 17, 2016

    October 17 PowerPoints and Midterm exam

    The midterm exam is posted on Canvas.

    October 17 Midterm Review:

    Code: 
    //
    //  main.cpp
    //  Oct17
    //
    //  Created by Mark Brautigam on 10/17/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    #include <string> 
    using namespace std;
    
    // ----------------------------------------------------
    bool isSquareLetter (char c) {
    // ----------------------------------------------------
        
        char u = toupper(c);
        /*
        if (u == 'A' || u == 'E' || u == 'F' ||
            u == 'H' || u == 'I' || u == 'K' ||
            u == 'L' || u == 'M' || u == 'N' ||
            u == 'T' || u == 'V' || u == 'W' ||
            u == 'X' || u == 'Y' || u == 'Z')
        */
        string legalChars = "AEFHIKLMNTVWXYZ";
        return legalChars.find(u) != string::npos;
        /*
        if (legalChars.find(u) != string::npos)
            return true;
        else
            return false;
         */
        // return true;
    }
    
    
    // ----------------------------------------------------
    string squareLetters (string s) {
    // ----------------------------------------------------
        
        string newString = "";
        
        int i = 0;
        while ( i<s.length()) {
            if (isSquareLetter(s[i])) {
                newString += toupper(s[i]);
            }
            i++;
        }
        return newString;
    }
    
    // ----------------------------------------------------
    string swap3 (string s) {
    // ----------------------------------------------------
        return s.substr(3) + s.substr(0,3);
    }
    
    // ----------------------------------------------------
    string fixName (string name) {
    // ----------------------------------------------------
        long comma = name.find(',');
        return name.substr(comma+1) + " " + name.substr(0,comma);
        return "notyet";
    }
    
    
    /*
    // ----------------------------------------------------
    string reverse (string s) {
    // ----------------------------------------------------
        int i = s.length()-1;
        while (i >= 0) {
            
        }
    }
     */
    
    // ----------------------------------------------------
    int main(int argc, const char * argv[]) {
    // ----------------------------------------------------
    
        string userInput = "";
        while (userInput != "done") {
            
            cout << "Type a number or \"done\" when finished: ";
            cin >> userInput;
            if (userInput == "done")
                break;
            
            cout << squareLetters (userInput) << endl;
            cout << swap3 (userInput) << endl;
            cout << fixName (userInput) << endl;
            
            // cout << "You said number " << atof(userInput.c_str()) << endl;
        }
        
        
        return 0;
    }
    



    Tuesday, October 11, 2016

    Midterm Exam

    The midterm exam will become available on or before Monday, Oct. 17. It will be due before the beginning of class on Monday, Oct. 24. So you will have one full week to work on it.

    There will be two parts:

    • A coding project that will use variables constants, arithmetic operators, math, math functions, strings, string functions, if conditions, else conditions, switch conditions, while loops, and user input.
    • A multiple-choice test that will be posted on Canvas.
    Next Monday, Oct. 17, we will review for the final exam in class. 


    Monday, October 10, 2016

    October 10 PowerPoints

    PowerPoint format
    PDF format

    Links:
    String class documentation
    Ctype - character functions
    Stof - this function may not be available to you
    Point Plotter

    Note: I posted an update to the Point Plotter this morning. It does the scaling for you so you can enter the raw data, and it will scale the data to fit. For drawing the circle, select "uniform scale." For other curves like sine waves, don't select "uniform scale" or one dimension will get squished. Updated point plotter. 


    //
    //  main.cpp
    //  Oct10
    //
    //  Created by Mark Brautigam on 10/10/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    #include <cmath>
    #include <string>
    using namespace std;
    
    string encrypt (string s) {
        string t = s;
        int len = t.length();
        int i = 0;
        while (i < len) {
            if (isalpha (t[i])) {
                if (tolower (t[i]) <= 'm')
                    t[i] = t[i] + 13;
                else
                    t[i] = t[i] - 13;
            }
            i++;
        }
        return t;
    }
    
    int main(int argc, const char * argv[]) {
        
        string encrypted = encrypt ("Fourscore and seven years ago");
        cout << encrypted << endl;
        string decrypted = encrypt (encrypted);
        cout << decrypted << endl;
        
         double PI = 3.1415926;
        
        /*
        int degrees = -180;
        while (degrees <= 180) {
            double radians = degrees * PI / 180;
            cout << degrees << " " << 100*sin(radians) << endl;
            degrees += 20;
            // degrees = degrees + 2;
        } 
        */   
    
        // y = x^2
        int x = -180;
        while (x <= 180) {
            int y = x * x * x;
            cout << x << " " << y << endl;
            x++;
        }
        
        
        /*
        string userInput = "";
        double sum = 0;
        
        while (userInput != "done") {
            cout << "The current total is " << sum << endl;
            cout << "Please enter a number or /done/ when finished: ";
            cin >> userInput;
            if (userInput == "done") {
                break;
            }
            // n = userInput.stof();
            sum += atof (userInput.c_str());
        }
        
        return 0;
         */
    }
    



    Coding Assignment 8, 9, and 10

    Here is an easy coding assignment due next weekend. I will post a harder assignment later today.

    8: Multiplication Table

    Homework 9 is not difficult. It asks you to use a while loop to obtain multiple user input, then do a simple arithmetic calculation.

    9: Average several numbers together

    Homework 10 is quite involved. It asks you to do some trigonometry calculations you may not understand. But everything you need to know is in the assignment. This one uses a loop, math functions, and arithmetic calculations.

    Allow a lot of time for this assignment.

    10: Plotting Clock Number Points


    Academic Dishonesty

    Please review the Ohlone College Procedure on Academic Dishonesty (e.g. Cheating)

    http://www.ohlone.edu/org/studentservices/academicdishonesty.html


    Monday, October 3, 2016

    October 3 PowerPoints

    Instructor's in-class presentations for October 3:
    Code
    //
    //  main.cpp
    //  phi2
    //
    //  Created by Mark Brautigam on 10/3/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    using namespace std;
    
    // A recursive function that computes PHI to the
    // specified accuracy based on an initial estimate
    //
    double phi (double depth) {
        if (depth == 1)
            return 1.5;
        else
            return 1 + 1 / phi(depth-1);
    }
    
    // Function overloading ... three functions with the
    // same name, but different signatures.
    //
    string combine (string a, string b) {
        return a+b;
    }
    
    double combine (double x, double y) {
        return x*y;
    }
    
    int combine (int p, int q) {
        return p+q;
    }
    
    // The MAIN function
    // The proram starts here.
    
    int main(int argc, const char * argv[]) {
    
        // some string functions: Chapter 7
        //
        string s = "amanaplanpanama";
        cout << s[10] << endl;
        cout << s.length() << endl;
        cout << s.find("ama") << endl;
        cout << s.rfind("ama") << endl;
        cout << s + " zowie!" << endl;
        cout << s.substr(9, 6) << endl;
        
        // A 2-dimensional ASCII table with
        // nested while loops
        cout << "\t";
        int i=0;
        while (i<=15) {
            cout << std::hex << i << "\t";
            i++;
        }
        cout << endl;
        
        int row = 2;
        // This "outer" loop prints a sequence of rows.
        //
        while (row <= 7) {
            cout << row << "\t";
            i = 0;
            
            // This "inner" loops prints the contents of one row.
            //
            while (i<=15) {
                cout << char(row*16+i) << "\t";
                i++;
            }
            cout << endl;
            row++;
        }
        
        // Print HEX and ASCII values in a linear table
        //
        i = 32;
        while (i <= 127) {
            cout << std::dec << i << "\t" << std::hex << i << "\t" << char(i) << endl;
            i++;
        }
        
        // Print squares and cubes in a linear table
        //
        i = 1;
        while (i <= 20) {
            cout << i << "\t" << i*i << "\t" << i*i*i << endl;
            i++;
        }
        
        // Print the numbers from 50 to 100 using a while loop
        //
        i = 50;
        while (i <= 100) {
            cout << i << " ";
            i++;
        }
        
        // Use the overloaded "combine" functions declared above.
        //
        cout << combine (17, 42) << endl;
        cout << combine (17.0, 42.0) << endl;
        cout << combine ("Hello", "World") << endl;
        
        // Arithmetic operators are overloaded to handle different types.
        cout << 17+42 << endl;
        cout << 17.0+42.0 << endl;
        // cout << "seventeen"+"fortytwo" << endl;
        
        // Compute PHI to various levels of accuracy.
        //
        cout << phi(20) << endl;
        cout << phi(40) << endl;
        return 0;
    }
    
    


    I got this output:
    a
    15
    0
    12
    amanaplanpanama zowie!
    panama
      0 1 2 3 4 5 6 7 8 9 a b c d e f 
    2   ! " # $ % & ' ( ) * + , - . / 
    3 0 1 2 3 4 5 6 7 8 9 : ; < = > ? 
    4 @ A B C D E F G H I J K L M N O 
    5 P Q R S T U V W X Y Z [ \ ] ^ _ 
    6 ` a b c d e f g h i j k l m n o 
    7 p q r s t u v w x y z { | } ~  
    32 20  
    33 21 !
    34 22 "
    35 23 #
    36 24 $
    37 25 %
    38 26 &
    39 27 '
    40 28 (
    41 29 )
    42 2a *
    43 2b +
    44 2c ,
    45 2d -
    46 2e .
    47 2f /
    48 30 0
    49 31 1
    50 32 2
    51 33 3
    52 34 4
    53 35 5
    54 36 6
    55 37 7
    56 38 8
    57 39 9
    58 3a :
    59 3b ;
    60 3c <
    61 3d =
    62 3e >
    63 3f ?
    64 40 @
    65 41 A
    66 42 B
    67 43 C
    68 44 D
    69 45 E
    70 46 F
    71 47 G
    72 48 H
    73 49 I
    74 4a J
    75 4b K
    76 4c L
    77 4d M
    78 4e N
    79 4f O
    80 50 P
    81 51 Q
    82 52 R
    83 53 S
    84 54 T
    85 55 U
    86 56 V
    87 57 W
    88 58 X
    89 59 Y
    90 5a Z
    91 5b [
    92 5c \
    93 5d ]
    94 5e ^
    95 5f _
    96 60 `
    97 61 a
    98 62 b
    99 63 c
    100 64 d
    101 65 e
    102 66 f
    103 67 g
    104 68 h
    105 69 i
    106 6a j
    107 6b k
    108 6c l
    109 6d m
    110 6e n
    111 6f o
    112 70 p
    113 71 q
    114 72 r
    115 73 s
    116 74 t
    117 75 u
    118 76 v
    119 77 w
    120 78 x
    121 79 y
    122 7a z
    123 7b {
    124 7c |
    125 7d }
    126 7e ~
    127 7f 
    1 1 1
    2 4 8
    3 9 1b
    4 10 40
    5 19 7d
    6 24 d8
    7 31 157
    8 40 200
    9 51 2d9
    a 64 3e8
    b 79 533
    c 90 6c0
    d a9 895
    e c4 ab8
    f e1 d2f
    10 100 1000
    11 121 1331
    12 144 16c8
    13 169 1acb
    14 190 1f40
    32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f 60 61 62 63 64 3b
    714
    HelloWorld
    3b
    59
    1.61803
    1.61803
    Program ended with exit code: 0
    


    Monday, September 26, 2016

    Week 4 PowerPoints


    Code:
    //
    //  main.cpp
    //  Sept26
    //
    //  Created by Mark Brautigam on 9/26/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    double pi = acos(-1.0);
    
    double squareArea (double side) {
        return side * side;
    }
    
    double degrees2radians (double degrees) {
        return (degrees * pi / 180);
    }
    
    double radians2degrees (double radians) {
        return (radians * 180 / pi);
    }
    
    void getSideAndComputeArea () {
        cout << "Please enter the length of a side: ";
        double ui;
        cin >> ui;
        cout << "The area is " << squareArea (ui) << endl;
    }
    
    double rectangle (double w, double h) {
        return w * h;
    }
    
    double triangle (double a, double b, double c) {
        double s = (a + b + c) / 2;
        double t = s * (s-a) * (s-b) * (s-c);
        if (t < 0)
            ; // ...
        return sqrt (t); // <cmath>
    }
    
    long factorial (long n) {
        if (n <= 1)
            return 1;
        else
            return n * factorial (n-1);
    }
    
    long fibonacci (long n) {
        if (n <= 2)
            return 1;
        return fibonacci (n-1) + fibonacci (n-2);
    }
    
    int main(int argc, const char * argv[]) {
        // insert code here...
        
        cout << fibonacci (5) << endl;
        cout << fibonacci (6) << endl;
        cout << fibonacci (45) << endl;
        // cout << factorial (24.5) << endl;
        // cout << triangle(2, 12, 11) << endl;
        
        // getSideAndComputeArea();
        // getSideAndComputeArea();
        // getSideAndComputeArea();
        
        /*
         cout << squareArea (12) << endl;
        cout << degrees2radians(45) << endl;
        cout << radians2degrees(0.785398) << endl;
        
        double rad = degrees2radians(57);
        cout << rad << endl;
        cout << radians2degrees(rad) << endl;
        
        double x = 17;
        double y = 42;
        cout << rectangle (x, y) << endl;
         */
        return 0;
    }
    



    Sunday, September 25, 2016

    Homework assignments 3 and 4

    These are due on Monday, Oct. 3 before class starts.

    Coding assignment 3

    Coding assignment 4

    There are no videos to go with these assignments. The first assignment asks you to write a series of if...else statements. The second assignment asks you to calculate a mathematical equation that has +, –, *, /, and square roots.


    Monday, September 19, 2016

    Week 3 PowerPoints

    Week 3 PDF

    Week 3 PPTX

    Resistor colors:

    0Black
    1Brown
    2Red
    3Orange
    4Yellow
    5Green
    6Blue
    7Violet
    8Gray
    9White


    Week 3 code. This is the code I typed in class.

    //
    //  main.cpp
    //  Sept19
    //
    //  Created by Mark Brautigam on 9/19/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    using namespace std;
    
    string getString (string s) {
        string returnValue;
        cout << s << ": ";
        cin >> returnValue;
        return returnValue;
    }
    
    double getDouble (string s) {
        double returnValue;
        cout << s << ": ";
        cin >> returnValue;
        return returnValue;
    }
    
    int getInteger (string s) {
        int returnValue;
        cout << s << ": ";
        cin >> returnValue;
        return returnValue;
    }
    
    int main(int argc, const char * argv[]) {
        // insert code here...
        // std::cout << "Hello, World!\n";
        
        int userNumber = getInteger ("Give me a number from 0 to 9");
        /*
         double anotherNumber = getDouble ("Give me a second number");
        cout << "The sum is " << userNumber + anotherNumber << endl;
         */
        /*
        if (userNumber % 2 == 1) {
          cout << userNumber << " is odd." << endl;
        }
        else {
            cout << userNumber << " is even." << endl;
        }
         */
        /*
        if (userNumber == 0) {
            cout << "Black" << endl;
        }
        else if (userNumber == 1) {
            cout << "Brown" << endl;
        }
        else if (userNumber == 2) {
            cout << "Red" << endl;
        }
        else if (userNumber == 3) {
            cout << "Orange" << endl;
        }
        else if (userNumber == 4) {
            cout << "Yellow" << endl;
        }
        else if (userNumber == 5) {
            cout << "Green" << endl;
        }
        else if (userNumber == 6) {
            cout << "Blue" << endl;
        }
        else if (userNumber == 7) {
            cout << "Violet" << endl;
        }
        else if (userNumber == 8) {
            cout << "Gray" << endl;
        }
        else {
            cout << "White" << endl;
        }
         */
        switch (userNumber) {
            case 0 : cout << "Black"; break;
            case 1 : cout << "Brown"; break;
            case 2 : cout << "Red"; break;
            case 3 : cout << "Orange"; break;
            case 4 : cout << "Yellow"; break;
            case 5 : cout << "Green"; break;
            case 6 : cout << "Blue"; break;
            case 7 : cout << "Violet"; break;
            case 8 : cout << "Gray"; break;
            case 9 : cout << "White"; break;
            default : cout << "Not recognized"; break;
        }
        cout << endl;
    
        return 0;
    }
    




    Programming Assignment 2

    Code:

    //
    //  main.cpp
    //  homework2
    //
    //  Created by Mark Brautigam on 9/18/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    /*
     Mark Brautigam - ID 123456
     CS 102 - Fall 2016 - Ohlone College
     Sept. 18, 2016
     */
    
    #include <iostream>
    #include <math.h>       /* sqrt */
    using namespace std;
    
    int main(int argc, const char * argv[]) {
        // insert code here...
        cout << "Hello, World!" << endl;
        
        cout << "What is your zip code? ";
        string zipcode;
        cin >> zipcode;
        cout << "Your zip code: " << zipcode << endl;
        
        // Arithmetic operations
        cout << "What is the length of side a : ";
        string a;
        cin >> a;
        double aa = atof(a.c_str());
        
        cout << "What is the length of side b : ";
        string b;
        cin >> b;
        double bb = atof(b.c_str());
        
        //     _  /  2   2
        // c =  \/  a + b
       
        double cc = sqrt ((aa * aa) + (bb * bb));
        cout << "The hypotenuse is " << cc << endl;
        
        char c = 320;
        cout << c << endl;
        
        short s = 12345;
        int i = 4321;
        int pi = 3.14;
        cout << pi << endl;
        
        return 0;
    }
    
    /*
     Hello, World!
     What is your zip code? asdf
     Your zip code: asdf
     What is the length of side a : 4
     What is the length of side b : 3
     The hypotenuse is 5
     @
     3
     Program ended with exit code: 0
     */
    




    Programming Assignment 1


    Code, in case you have trouble reading the video:

    //
    //  main.cpp
    //  homework1b
    //
    //  Created by Mark Brautigam on 9/18/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    /*
     Mark Brautigam - ID 123456
     CS 102 - Fall 2016 - Ohlone College
     Sept. 18, 2016
     */
    
    #include <iostream>
    using namespace std;
    
    int main(int argc, const char * argv[]) {
        // insert code here...
        cout << "Hello, World!" << endl;
        
        string name = "Mark Brautigam";
        cout << name << endl;
        
        string nick = "Mixed Up";
        string nonsense = nick + " " + name;
        cout << nonsense << endl;
        
        cout << "name = " << name << endl;
        cout << "nick = " << nick << endl;
        cout << "nonsense = " << nonsense << endl;
        
        int x = 17;
        cout << "Enter a value for x: ";
        string xstring;
        cin >> xstring;
        x = atoi(xstring.c_str());
        int xcubed = x * x * x; // x^3
        cout << xcubed << endl;
        cout << "If x is " << x << ", then xcubed = " << xcubed << endl;
        
        return 0;
    }
    

    Monday, September 12, 2016

    Online C++ Compilers

    The course materials will go way beyond the capabilities of these online resources very quickly. But you may use them in a pinch for very small projects like the ones we will do in class the first few weeks.

    Code Chef
    https://www.codechef.com/ide

    IDE One
    http://ideone.com/
    (tends to go down a lot, especially during class)

    C++ Shell
    http://cpp.sh

    Tutorials Point
    http://www.tutorialspoint.com/compile_cpp11_online.php
    (Choose C++11 from the menu if it's not chosen already)


    New Project in Xcode (Mac)

    1. Start Xcode
    2. File --> New --> Project ...
    3. Choose OS X --> Application --> Command Line Tool

    (click to enlarge)


    4. Next
    5. Product name should be whatever you like
    6. Organization name should be your name
    7. Organization identifier should be com.yourname (insert your own name)
    8. Language should be C++

    (click to enlarge)


    9. Next
    10. Choose "Desktop" for the location
    11. Create

    You'll get a project that has a main.cpp file. That file should look like this:

    //
    //  main.cpp
    //  Week3homework
    //
    //  Created by Mark Brautigam on 9/12/16.
    //  Copyright © 2016 Mark Brautigam. All rights reserved.
    //
    
    #include <iostream>
    
    int main(int argc, const char * argv[]) {
        // insert code here...
        std::cout << "Hello, World!\n";
        return 0;
    }
    

    Note that this code looks a lot like the template code I gave you in another post.


    Sunday, September 11, 2016

    Hello World Program

    This hello world program is from page 7 in the textbook. It should work on any computer you try to use.

    If you ask for an empty project in Visual Studio (Windows) or Xcode (Mac), you might get a program that has a little bit more than this, but the extra stuff is "mostly harmless." If you get a lot more stuff than this, you probably asked for the wrong kind of project.

    #include <iostream>
    using namespace std;
    
    // main: generate some simple output
    
    int main ()
    {
      cout << "Hello, world." << endl;
      return 0;
    }
    

    Thursday, August 25, 2016

    Syllabus

    Course Description

    This course is an introduction to computer programming. Its primary objective is to teach problem solving using the C++ programming language. Emphasis will be placed on structured procedural programming with an introduction to object-oriented programming.

    This course is designed primarily for computer science and related transfer majors, but it is also suitable for non-CS students.

    Instructor

    NameMark Brautigam
    Emailmbrautigam1@ohlone.edu
    Phone408-209-9641
    Office HoursMondays, NC 2318, 6:30–7:00 pm or 9:05–9:35 pm

    Lab

    The lab session is mandatory. It takes place on the Newark Campus on Monday evenings, 7:00–9:05 pm, in room NC 2318.

    Office Hours

    Like other part-time faculty, I do not have an office on campus. I will hold office hours either one half hour before class (6:30–7:00 pm) in the classroom, if the classroom is available at that time; or one half hour after class (9:05–9:35 pm).

    Contacting Me

    Please call me at my number above only in an emergency. I am teaching classes most of the day and evenings, so I rarely answer my phone or even have it turned on. If you are going to miss class for any reason, it is best to send me an email beforehand.

    I will probably not check my Ohlone email very often, so it is probably better to send (only important) email to my personal email address: markb@mixed-up.com.

    Prerequisites

    Math 152 (Algebra II) or Math 153 (Intermediate Algebra).

    Textbook

    We will be using this free online textbook: How to Think Like a Computer Scientist, which is as good as many other textbooks that cost a lot of money. Several of the other sections of CS 102 are also using this textbook.

    Attendance

    Monday evening lab attendance is mandatory. The college has limits on how many classes you can miss without being automatically dropped. Usually you can miss only as many class meetings as there are in one week. For this class, this means you can be dropped after missing only two class meetings. Please consult the official school policies for details. If you are going to miss class, it is best to let me know by email before class starts.

    You will turn in all your exams and homework online, and there will be a window of time, so you will never miss an important exam, quiz, or homework due date by missing class. But if you miss class, it is up to you to find out what we covered in class. I usually post any PowerPoint presentations online immediately before or after class.

    Canvas

    Ohlone College is no longer using Blackboard. Lectures and assignments will be posted on Canvas and you will turn in your homework using Canvas. Please make sure you know how to use it. https://ohlone.instructure.com

    Discussion Board

    The discussion board is a way of making sure you get timely answers to questions from me and from your classmates. It is also a way I gauge your participation in the online portion of this class.

    Schedule

    The folloiwing schedule is tentative. We may make changes as necessary.

    WeekDateChap.Topic
    1 Aug. 29 1 Introduction to Computers and Programming
    2 Sept. 5 2 Variables, Constants, Expressions, Statements, Assignment
    3 Sept. 12 3 Using Functions
    4 Sept. 19 4 Conditionals
    5 Sept. 26 5 Writing Functions
    6 Oct. 3 6 Loops
    7 Oct. 10 Review
    8 Oct. 17 Midterm Exam
    9 Oct. 24 7 Strings
    10 Oct. 31 8–9 Structures
    11 Nov. 7 10 Vectors
    12 Nov. 14 11 Member Functions
    13 Nov. 21 15 File I/O
    14 Nov. 28 14 Classes
    15 Dec. 5 12–13 Vectors of objects and objects of vectors
    16 Dec. 12 Final Exam

    Student Learning Outcomes

    Upon successful completion of the course, students will acquire the capability to:
    • Employ the basic syntax and semantics to write programs.
    • Manage program flow by using conditional and iterative structures.
    • Construct programs modularly from subroutines/functions.
    • Construct programs with arrays, pointers, and other structures.
    • Demonstrate basic stream and file Input/Output.
    • Apply software development methodology to programming projects.

    Assignments

    There will be programming assignments every week. Reserve 8 hours per week for this class outside of the Monday lab session.

    Quizzes

    There will be weekly quizzes. The quizzes will be available on Canvas and they will be scored by the system.

    Exams

    There will be a two-part midterm exam. One part will consist of multiple-choice questions and will be scored by computer. One part will require that you write a working C++ program.

    There will be a two-part final exam. One part will consist of multiple-choice questions and will be scored by computer. One part will require that you write a working C++ program.

    Grading

    Grading will be based on these activities:
    Weekly assignments25%
    Weekly quizzes25%
    Midterm exams20%
    Final exams20%
    Participation10%

    Grades will be assigned as follows:
    A90 –100
    B80 –  89
    C70 –  79
    D60 –  69
    F  0 –  59



    Saturday, August 13, 2016

    Welcome to CS 102

    This will be the web site for CS 102: Introduction to Programming with C++, at the Newark campus of Ohlone College in Newark, California.

    I will post videos and other instructional materials online here (and possibly in Canvas also). We will have lab time together on Monday evenings from 7:00 until 9:30 pm. Our first lab session will be on August 29, 2016. Lab attendance is mandatory and we will take attendance each Monday.

    We will be using an online textbook called How to Think Like a Computer Scientist, C++ Version, by Allen B. Downey. Most of the other C++ classes at Ohlone College will be using this textbook also. We may make some slight changes to update the book before the semester starts and during the course of the semester. We will also use the web site cplusplus.com frequently as reference material.

    I look forward to meeting you all on August 29.