Lecture 2

Just some questions I had, answers from Google/Stack Overflow

++i vs i++ (Pre-increment vs Post-increment)

++i will increment the value of i, and then return the incremented value.
 i = 1;
 j = ++i;
 (i is 2, j is 2)
i++ will increment the value of i, but return the original value that i held before being incremented.
 i = 1;
 j = i++;
 (i is 2, j is 1)

For a for loop, use

++i

, as it's slightly faster.

i++

will create an extra copy that just gets thrown away.

Pre-increment vs Post-Increment in Array indices

{ 
 int a[5] = { 5, 1, 15, 20, 25 } ; 
 int i, j, k = 1, m ; 
 i = ++a[1] ; 
 j = a[1]++ ; 
 m = a[i++] ; 
 printf ( "\n%d %d %d", i, j, m ) ; 
}
First:

i = ++a[1];
At this point we know a[1] = 1 (remember arrays are zero indexed). But we increment it first. Therefore i = 2.

j = a[1]++;
Remember we incremented a[1] before, so it is currently 2. We set j = 2, and THEN incremented it to 3. 
So j = 2 and now a[1] = 3.

m = a[i++];
We know i = 2. So we need to set m = a[2], and then increment i. At the end of this expression, m = 15, and i = 3.

In summary,

i = 3, j = 2, m = 15.

O(log n) time

int func3(int n) {
    int sum = 0;
    for (int i = n; i > 1; i / 2) {
        sum += 1;
    } // for
    return sum;
} // func3()

Fast Binary Functions with O(log n) time

// count Trailing Zero Bits
unsigned ctz(unsigned n) {
    if (n == 0) return 0; // Base case
    unsigned r = 0;
    while (n % 2 == 0) {
        n /=2, r++;
    } // while
    return r;
} // ctz()
// count nonzero bits
unsigned onecount(unsigned n) {
    unsigned r = 0;
    for( ; n; n &= (n - 1))  // what is &= ??
        r++;
    return r;
} // onecount()

/*  
    "&=" Bitwise AND assignment operator    
    C &= 2 is same as C = C & 2
    Compares each bit of the first operand to the corresponding bit of the second operand. 
    If both bits are 1, the corresponding result bit is set to 1. 
    Otherwise, the corresponding result bit is set to 0.
*/
// find binary log, round up
unsigned logB(unsigned n) {
    // find binary log, round up
    unsigned r = 0;
    while (n > 1) {
        n /= 2;
        r++;
    } // while
    return r;
} // logB()
// NEEDS OPTIMIZATION
// find position of val between lo,hi
int* bsearch(int* lo, int* hi, int val) {
    while (hi >= lo) {
        int* mid = lo + (hi - lo) / 2;
        if (*mid == val) return mid;
        else if (*mid > val) hi = mid - 1;
        else lo = mid + 1;
    } // while
    return nullptr;
} // bsearch()

results matching ""

    No results matching ""