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