Notes 1 - Review CMPS 2010

References:

Arrays

int array[3];
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[3] = 999; // out of bounds

int arr1[3] = {0,1,2}; // initialization list
int arr2[] = {0,1,2};  // implicit array w/ init list
int arr3[99] = {0};    // partial array
int arr4[2][3];        // 2D array [row][colm]

initializing arrays, processing arrays, running total, multi dimensional arrays


Functions and Parameters

returnType funcName(parameter, list); // prototype
returnType funcName(parameter, list) {
  // definition
  // return
}

void sayHello() {
  cout << "Hello\n" << endl;
  return();
}

int sum(int a, int b) {
  return(a + b);
}

bool isPositive(int num) {
  if(num > 0)
    return(true);
  //else
  return(false);
}

void increment(int &num, int val=1) {
  num+=val;
} 

void printArr(int arr[], int size) {
  for(int i=0; i<size; i++)
    cout << arr[i] << endl;
}

passing parameters: pass by value, pass by &reference
function overloading
default arguments
boolean functions
passing an array as an argument


Pointers

int x = 3; int *ptr = &x;
cout << ptr << endl;
cout << *ptr << endl;
ptr++; ptr = ptr - 1;
pointer declaration, pointer initialization, dereferencing a pointer, pointer arithmetic.


Dynamic Memory Allocation

int *p = NULL;
p = new int;
*p = 3;
cout << *p << endl;
delete p;
p=NULL;

int *q = NULL;
q = new int[2];
q[0] = 3;
*(q+1) = 4;
cout << q[0] << endl;
cout << *(q+1) << endl;
delete [] q;
q=NULL;
new, delete, NULL, segmentation fault
intro to try-catch block - allocating the safe way

Structured Data and Objects

struct Square {
  int length;
  int width;
};
...
Square s1;   // one object
s1.length = 2;
s1.width = 2;

Square squares[2]; // static array of objects

Square* dynSqrs = NULL;
try{                        // try
  dynSqrs = new Square[3];  //  to allocate 3 Square objs dyncamically
}catch(bad_alloc) {         // if allocation failed, bad_alloc excpt. caught
  cout << "bad allocation\nexiting program";
  exit(EXIT_FAILURE);       //   close the program
}
if(dynSqrs!=NULL) {         // good habit to check if pointer != NULL
  // process dynSqrs
}