teaching machines

CS 330 Lecture 9 – C as Assembly++

February 11, 2013 by . Filed under cs330, lectures, spring 2013.

Agenda

TODO

Outlook

Code

our_first_c_program.c

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {

  /*
  char (1 byte), int, short, long
  float double
   */

  printf("sizeof char: %d\n", sizeof(char));
  printf("sizeof short: %d\n", sizeof(short));
  printf("sizeof int: %d\n", sizeof(int));
  printf("sizeof long: %d\n", sizeof(long));
  printf("sizeof long long: %d\n", sizeof(long long));

  printf("sizeof unsigned char: %d\n", sizeof(unsigned char));
  printf("sizeof unsigned short: %d\n", sizeof(unsigned short));
  printf("sizeof unsigned int: %d\n", sizeof(unsigned int));
  printf("sizeof unsigned long: %d\n", sizeof(unsigned long));
  printf("sizeof unsigned long long: %d\n", sizeof(unsigned long long));

  printf("sizeof float: %d\n", sizeof(float));
  printf("sizeof double: %d\n", sizeof(double));

  return 0;
}

string_test.c

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {

  char numberish[] = "9509";
  /* char numberish[] = { */
    /* '9', */
    /* '5', */
    /* '0', */
    /* '9', */
    /* '\0' */
  /* }; */

  int n = 0;
  for (int i = 0; numberish[i] != '\0'; ++i) {
    n = n * 10 + (numberish[i] - '0');
  }
  printf("n: %d\n", n);
  printf("n + 1: %d\n", n + 1);

  return 0;
}

cards.c

#include <stdio.h>
#include <stdlib.h>

enum rank_t {
  ACE = 1,
  DEUCE,
  THREE,
  FOUR,
  FIVE,
  SIX,
  SEVEN,
  EIGHT,
  NINE,
  TEN,
  JACK,
  QUEEN,
  KING
};

int main(int argc, char **argv) {
  enum rank_t card1 = SEVEN;  
  enum rank_t card2 = JACK;  

  int ncards = 3;
  enum rank_t hand[] = {
    /* 42, */
    ACE,
    JACK,
    ACE
  };

  int naces = 0;
  int score = 0;

  // Add up all the non-ACE cards first...
  for (int i = 0; i < ncards; ++i) {
    if (hand[i] == ACE) {
      ++naces;
    } else if (hand[i] == KING || hand[i] == QUEEN || hand[i] == JACK) {
      score += 10;
    } else {
      score += hand[i];
    }
  }

  // See if adding one "power ace" on would shoot us past 21. If not, let's
  // power up that ace to 11 and treat all others as 1. Otherwise, treat all
  // aces as 1.
  if (score + 11 + (naces - 1) <= 21) {
    score += 11 + (naces - 1);
  } else {
    score += naces;
  }
  printf("score: %d\n", score);

  return 0;
}

Haiku

my wife’s plan
enum husband_t
{FARMER, PASTOR, NATURE_BOY}
Even so, I’m her type