Notes from 12/3

arrays.cpp

#include <iostream>
using namespace std;

int main()
{
    const int SIZE = 10;
    int xs[SIZE];

    // Let array contain the squares of its indices.
    for(int i = 0; i < SIZE; i++) {
        xs[i] = i * i;
    }

    // Print it out
    for(int i = 0; i < SIZE; i++) {
        cout << i << ": " << xs[i] << "\n";
    }

    // Initialize everything to 0 now, using pointer notation and
    // arithmetic
    for(int* p = xs; p < xs + SIZE; p++) {
        *p = 0;
    }
    for(int* p = xs; p < xs + SIZE; p++) {
        cout << (p - xs) << ": " << *p << "\n";
    }


    return 0;
}

ptrs.cpp

#include <iostream>
using namespace std;

int main()
{
    // cout << 0x25 << "\n";       // prints in decimal by default
    // cout << hex << 175 << "\n"; // can specify to print in hex
    // cout << dec << 0xCAFE << "\n"; // switch back to base 10
    // cout << "An int is " << sizeof(int) << " bytes.\n";
    // cout << "A double is " << sizeof(double) << " bytes.\n";
    // cout << "A char is " << sizeof(char) << " bytes.\n";
    // cout << "A long is " << sizeof(long) << " bytes.\n";
    // cout << "A float is " << sizeof(float) << " bytes.\n";

    int x = 13;
    double d = 3.1415;
    int y = 20;

    cout << "x is at " << &x << "\n";
    cout << "d is at " << &d << "\n";
    cout << "y is at " << &y << "\n";

    int* p = NULL;
    cout << "p is " << p << "\n";
    p = &x;
    cout << "p is now " << p << "\n";
    *p = 99; // changes x
    cout << "x is now the value " << x << "\n";

    p = &y;
    cout << "p is now " << p << "\n";
    *p = 44; // changes y
    cout << "y is now the value " << y << "\n";

    // Pointers and arrays
    int a[3];
    cout << "a is " << a << "\n";
    cout << "a[0] is at " << &(a[0]) << "\n";
    cout << "a[1] is at " << &(a[1]) << "\n";
    cout << "a[2] is at " << &(a[2]) << "\n";

    cout << "a + 2 is " << a+2 << "\n";

    double* q = &d;
    cout << "q + 5 is " << q+5 << "\n";

    return 0;
}

strings.cpp

#include <iostream>
using namespace std;
int main()
{
    char s[] = "Hello";
    cout << s[1] << "\n"; // e
    s[3] = 'p';
    cout << s << "\n"; // Helpo
    s[4] = '!';
    cout << s << "\n"; // Help!
    s[4] = '\0';       // NUL character terminates string
    cout << s << "\n"; // Help
    s[2] = '\0';
    cout << s << "\n"; // He

    double x = 3.14159;
    char t[] = "Testing";
    double y = 9.999999;
    // remove terminating NUL! (dangerous)
    t[7] = '!';
    cout << t << "\n";

    // Process strings using pointer arithmetic
    char mesg[] = "the quick brown fox jumps over the lazy dog.";
    char* p = mesg;
    int shift = 5;
    while(*p) {
        if(*p >= 'a' && *p <= 'z') {
            int k = *p - 'a';
            *p = 'a' + (k + shift) % 26;
        }
        p++;
    }
    cout << mesg << "\n";
}