Notes for Nov 30

pal2.cpp

Two ways to detect a palindrome.

#include <iostream>
using namespace std;
int main()
{
    string input;
    cout << "Enter string: ";
    getline(cin, input);

    string reversed(input.rbegin(), input.rend());

    cout << reversed << endl;
    if(input == reversed) {
        cout << "PALINDROME!\n";
    }

    // More complex technique
    int i = 0;
    int j = input.length()-1;
    while(i < j && input[i] == input[j]   )
    {
        cout << "i=" << i << ", j=" << j
             << ", matched '" << input[i] << "'\n";
        i++;
        j--;
    }
    if(j <= i) {
        cout << "PALINDROME (loop technique)\n";
    }


    return 0;
}

call-by-val.cpp

// demonstrating call by value
#include <iostream>
#include <vector>
using namespace std;

void print_data(string varName, string vecName,
                int val, vector<int> vec)
{
    cout << varName << ": " << val << endl;
    cout << vecName << ": ";
    for(int j = 0; j < vec.size(); j++)
    {
        cout << vec[j] << " ";
    }
    cout << endl;
}

void frob(int a, vector<int> b)
{
    a++;
    b[0] *= 2;
    b[1] *= 3;
    print_data("a", "b", a, b);
}

int main()
{
    int i = 8;
    vector<int> v;
    v.push_back(9);
    v.push_back(3);
    v.push_back(2);

    // Print values
    print_data("i", "v", i, v);

    // Call frob -- it will make a COPY of the parameters
    frob(i, v);

    // Print the unchanged results
    print_data("i", "v", i, v);

    return 0;
}

call-by-ref.cpp

// demonstrating call by reference
#include <iostream>
#include <vector>
using namespace std;

void print_data(string varName, string vecName,
                int val, vector<int> vec)
{
    cout << varName << ": " << val << endl;
    cout << vecName << ": ";
    for(int j = 0; j < vec.size(); j++)
    {
        cout << vec[j] << " ";
    }
    cout << endl;
}

void frob(int& a, vector<int>& b)
{
    a++;
    b[0] *= 2;
    b[1] *= 3;
    print_data("a", "b", a, b);
}

int main()
{
    int i = 8;
    vector<int> v;
    v.push_back(9);
    v.push_back(3);
    v.push_back(2);

    // Print values
    print_data("i", "v", i, v);

    // Call frob -- it will make a COPY of the parameters
    frob(i, v);

    // Print the unchanged results
    print_data("i", "v", i, v);

    return 0;
}