Sunday, August 19, 2012

C - counting the number of times a char appears in a string

Code: https://gist.github.com/3394648

This was a nice exercise that helped me get more familiar with malloc and pointers.  I was really happy when I got the two dimensional array pointers working on the first try!

Monday, July 23, 2012

making my own strcat() in C

As an exercise, I made my own strcat() function in C:

https://gist.github.com/3164052 for the pretty version.


#include <stdio.h>
#include <string.h>
#define STRINGSIZE 80

int cat(char *a, const char* b, const size_t max_size)
{  
    //puts("FUNCTION BEGIN");
    size_t size = strlen(a);
    a += size;
    while (*b)
    {
        if (size >= max_size)
        {  
            *a = '\0';
            printf("ERROR: function cat() has run past max_size: size = %lu\n", size);
            return -1;  // I feel like I should undo the changes
                        // since I'm returning an error.
        }
        *a++ = *b++;
        size++;
    }
    *a = '\0';
    //puts("FUNCTION FINISHED");
    return 0;
}

int main()
{
    char strA[STRINGSIZE] = "I am a small cat ";
    char strB[STRINGSIZE] = "with whiskers who likes milk.";
    printf("A: '%s'\nB: '%s'\n", strA, strB);
    puts("-= Let's call cat() =-");
    int result = cat(strA, strB, STRINGSIZE);
    if (result == -1)
        printf("main() - ERROR in function cat(): -1\n");
    printf("A: '%s'\nB: '%s'\n", strA, strB);
    printf("cat() returned: '%d'\n", result);
    return 0;
}



Sunday, July 15, 2012

Strings, Arrays, Pointers, and searching in C

After a bout of wrist pain, I'm strating to slowly ease back into programming.  Here is some C code to search through strings for words in sys args, and highlight the found words with brackets.:

Thursday, June 21, 2012

Decimal, Hexadecimal and Binary in C

A progress report on my attempt to learn C:
After doing some exercises while going through K&R, I decided to do an exercise of my own, and created a C program that converts a user-inputted decimal into hexadecimal and binary.  It was really quite fun to make.  Here is the code:


#include <stdio.h>
#include <math.h>

int main (){
    char large_text[100];
    int i = 0;
    char c;

    printf("\nInput: ");
    for (i = 0;(c = getchar()); i++){
        if ((c == '\0') | (c == 10)) {
            large_text[i] = '\0';
            break;
        }
        large_text[i] = c;
    }
    printf("The input was: ");
    int i2 = 0;
    while (i2 <= i){
        printf("%c", large_text[i2]);
        i2++;
    }
    printf("\n");

    // convert to decimal
    i2 = 0;
    int ten_to_the;
    int value;
    int decimal = 0;
    while (i2 < i){
        ten_to_the = i - 1 - i2;
        value = (large_text[i2] - '0') * (int)(pow(10,ten_to_the));
        printf("char: %c\tdec: %d\t*ten_to_the: %d\tproduct: %d\t",
            large_text[i2], large_text[i2] - '0', ten_to_the, value);
        i2++;
        decimal = decimal + value;
        printf("decimal is: %d\n", decimal);
    }

    // convert to hexadecimal
    char hex[24];
    int slice = decimal;
    int remain;
    int i3 = 0;
    while (slice > 0){
        remain = slice % 16;
        slice = slice / 16;
        switch (remain){
            case 10 : c = 'a'; break;
            case 11 : c = 'b'; break;
            case 12 : c = 'c'; break;
            case 13 : c = 'd'; break;
            case 14 : c = 'e'; break;
            case 15 : c = 'f'; break;
            default : c = remain + '0';
        }
        hex[i3] = c;
        i3++;
    }
    hex[i3] = '\0';
    // reverse the hex string for proper order
    char newhex[24];
    newhex[i3] = '\0';
    for (i = 0; (c = hex[i]); i++){
        newhex[(i3-1)-i] = c;
    }

    // convert to binary
    char bin[100];
    slice = decimal;
    remain = 0;
    i3 = 0;

    while (slice > 0){
        remain = slice % 2;
        slice = slice / 2;
        switch(remain){
            case 0 : c = '0'; break;
            case 1 : c = '1'; break;
            default : c = '!';
        }
        bin[i3] = c;
        i3++;
    }
    bin[i3] = '\0';
    // reverse the string for proper order
    char newbin[100];
    newbin[i3] = '\0';
    for (i = 0; (c = bin[i]); i++){
        newbin[(i3-1)-i] = c;
    }
    printf("==============================================\n");
    printf("Decimal:%d\tHex: 0x%s\tBinary: %s\n", decimal, newhex, newbin);
    printf("==============================================\n");
    printf("Program finished...\n");
    return 0;

Wednesday, May 30, 2012

Learning C with K&R

Recently I have begun learning C using the highly regarded K&R second edition.

I decided to take a break from the Udacity courses, with the intention of returning to finish them later.  I really wanted to get away from Python, which I've been using exclusively for the past 6 months and finally learn my 2nd programming language.

I chose C because it seems to exist at the polar opposite of Python.  It is low level, statically typed, fast and relatively old.  Python is pretty much the opposite of all those things.

I'm really glad I made this choice.  After just a couple chapters I already feel I am learning so much more about programming.  I now have a deeper understanding of just how much Python was taking care of for me in terms of memory management and abstraction.  I definately miss the ease with which I could code in Python, but I think this is an excellent learning experience.

Below is the code for exercise 2-3 in K&R which converts a hexadecimal string into a decimal value.

Codepad


#include <stdio.h>
#include <string.h>
#include <math.h>
int acceptable_input(char s[]);
int acceptable_char(char c);
int htoi(char s[]);
int main(){
    int cycle = 0;
    char text[30];
    int i;
    char c;
    while(cycle < 10){
        cycle++;
        i = 0;
        printf("enter hexademical (0x prefix optional): ");
        while((c = getchar()) != 10){
            text[i] = c;
            i++;
        }
        text[i] = '\0';
        printf("your input: %s\n", text);
        printf("DECIMAL VALUE: %d\n", htoi(text));
    }
    return 0;
}
int htoi(char s[]){
    printf("------------------\n");
    printf("s: %s (before strip)\n", s);
    // strip 0x or 0X
    int haszero = (s[0] == '0');
    char old_s[50];
    strcpy(old_s, s);
    int hasx = (s[1] == 'x' || s[1] == 'X');
    if (haszero && hasx){
        int i;
        for (i = 2; s[i] != '\0'; i++)
            s[i-2] = s[i];
        s[i-2] = '\0';
    }
    printf("s: %s\n", s);
    int okay = acceptable_input(s);
    printf("acceptable string?: %d\n", okay);
    if (okay == 0){
        printf("Input unacceptable.\n");
        return 9999;
    }
    int length = strlen(s);
    printf("length: %d\n", length);
    int x;
    int mult;
    int num;
    int result = 0;
    for(x = 0; x < length; x++) {
        mult = (int)pow(16,length-(x+1));
        num = (int)s[x] - (int)'0';
        if(s[x] == 'a' || s[x] == 'A') num = 10;
        if(s[x] == 'b' || s[x] == 'B') num = 11;
        if(s[x] == 'c' || s[x] == 'C') num = 12;
        if(s[x] == 'd' || s[x] == 'D') num = 13;
        if(s[x] == 'e' || s[x] == 'E') num = 14;
        if(s[x] == 'f' || s[x] == 'F') num = 15;
        printf("char: %c\tnum: %d\tmult: %d\tvalue: %d\n",
            s[x], num, mult, num * mult);
        result = result + num * mult;
    }
    return result;
}
int acceptable_char(char c){
    char good[] = "0123456789abcdefABCDEF";
    int i;
    for(i = 0; good[i] != '\0'; i++){
        if (c == good[i])
            return 1;
    }
    return 0;
}
int acceptable_input(char s[]){
    int i;
    for (i = 0; s[i] != '\0'; i++){
        if(acceptable_char(s[i]) == 0)
            return 0;
    }
    return 1;
}

Tuesday, May 8, 2012

Recursion and Multiple Argument Functions

So in Unit 3 of CS212 at Udacity I had to create a function that takes a binary argument function as an argument and returns a function that can accept n-arguments. Let's look at it in detail.

The original function:

 def herp(x,y):
     return x, y

The converting function that returns a new function:


def n_ary(f):
    """Given binary function f(x, y), return an n_ary function such
    that f(x, y, z) = f(x, f(y,z)), etc. Also allow f(x) = x."""
    def n_ary_f(x, *args):
        return x if not args else f(x, n_ary_f(*args))
    return n_ary_f




So the following can be done:

herp_n = n_ary(herp)
herp_n(1)
herp_n(1,2)
herp_n(1,2,3)
herp_n(1,2,3,4)




Recursion has sometimes been a difficult thing for me to get the hang of.  I understand perfectly how it works, but when faced with a problem where it could be used I still struggle with figuring out how to implement it.  This was good practice in that regards.

Programming, Concentration, and Lack of Sleep

I'm off work on Tuesdays, so usually it's a very productive day for me.  Today, unfortunately, I had much less sleep than usual, and it made it nearly impossible for me to keep my brain focused on the difficult concepts being presented in CS212 at Udacity.

It's tempting to just say "I can do this" and push oneself, trying to just "make it happen" through sheer willpower, but I haven't been able to do this since my early-20s, and I suspect even then it was much less effective than I thought it was.

According to a WebMD article from 2000, the brain-recovery aspect of sleep happens mostly in the early hours of sleep, not so much in the later parts, which suggests that a nap during the day would be better for brain-power than just trying to get more sleep at night.  This seems like a good strategy to try out.