Notes for Nov 9

squares.cpp

// perfect squares
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    const int NUM_SQUARES = 200;
    const int NUM_COLUMNS = 9;
    int squares[NUM_SQUARES];
    // calculate squares
    for(int i = 0; i < NUM_SQUARES; i++) {
        squares[i] = i*i;
    }
    // print results
    for(int i = 0; i < NUM_SQUARES; i++) {
        cout << setw(8) << squares[i];
        if(i%NUM_COLUMNS == NUM_COLUMNS-1) {
            cout << endl;
        }
    }
    cout << endl;
    return 0;
}

squaresvec.cpp

// perfect squares
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
    const int LIMIT = 1000000;
    const int NUM_COLUMNS = 9;
    vector<int> squares;
    // calculate squares
    for(int i = 0; i*i < LIMIT; i++) {
        squares.push_back(i*i);
    }
    // print results
    for(int i = 0; i < squares.size(); i++) {
        cout << setw(8) << squares[i];
        if(i%NUM_COLUMNS == NUM_COLUMNS-1) {
            cout << endl;
        }
    }
    cout << endl;
    return 0;
}

maxvec.cpp

// Find maximum number in vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> numbers;
    numbers.push_back(-37);
    numbers.push_back(-42);
    numbers.push_back(-15);
    numbers.push_back(-64);
    numbers.push_back(-18);
    numbers.push_back(-91);
    numbers.push_back(-22);
    numbers.push_back(-50);
    // Find biggest
    int biggest = numbers.at(0);  // Biggest seen so far
    for(int i = 1; i < numbers.size(); i++)
    {
        if(numbers.at(i) > biggest) {
            biggest = numbers.at(i);
        }
    }
    cout << "Biggest number is " << biggest << endl;
    return 0;
}

count-odds.cpp

// Count number of odd numbers in vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> numbers;
    numbers.push_back(37);
    numbers.push_back(42);
    numbers.push_back(15);
    numbers.push_back(64);
    numbers.push_back(18);
    numbers.push_back(91);
    numbers.push_back(22);
    numbers.push_back(50);
    // Count
    int odd_count = 0;
    for(int i = 0; i < numbers.size(); i++)
    {
        if(numbers.at(i)%2 == 1)
        {
            odd_count++;
        }
    }
    cout << "It has " << odd_count
         << " odd numbers." << endl;
    return 0;
}