EE319K Homework 7


Due Date: April 5th Tuesday 2:00 AM (Monday night)

You are required to submit your solution (Code) to Exercise 4 and the result of running it (output) put together as a single document (pdf or word) on Blackboard. For practice with C coding, you should solve the other 3 exercises as well, though you are not expected to submit the code. Go to http://codepad.org and try out the following simple C Programs and their suggested modifications.

As we mentioned in the syllabus you should read the later parts of Dr. Patt's EE306 textbook for help with the basics of C. If you do not have the text or you are looking for more information. We have a C Primer for you that is specifically towards Embedded Systems (using Metrowerks) at the following URL:
                http://users.ece.utexas.edu/~ryerraballi/CPrimer/

The concepts covered in this primer apply to C programming in general but with a few exceptions like, the lack of input/output library support for functions like printf, scanf and no support for floating point types.

In this set we will look at simple subroutines and flow control using conditionals (if-then-else statements which we saw in the last set) and loops. We will also look at basics of arrays. If you are referring to Yale Patt's  book, you may want to read chapters 13, 14 and 16. If you are referring to the C Primer, you should read chapters 6, 7, 8 and 10.

Example 1: A simple count down using a while loop and the same concept implemented using a for loop    
void main(void){
  unsigned char count;

  count = 10; // Initialize the loop control variable, (count)

  while (count > 0){
    printf("%d ",count);
    count = count - 1;   //update count and repeat
  }
  printf("Lift Off\n"); // When count becomes zero we get out of the loop

  for (count=10; count > 0; count--){ //count-- is short for count = count-1
    printf("%d ",count);
  }
  printf("Lift Off\n");

}

Exercise 1: Write C code to do the following:
Nested Loops: The body of a for or while loop may itself contain a for or while loop.

Example 2: Say we want to print the multiplication table for numbers between 2  to 9:
void main(void){
  unsigned char number, count, result;

  for (number = 2; number <= 9; number++){
    printf("\nMultiplication Table for %d\n", number);
    for (count = 1; count <= 10; count++){
      result = number*count;
      printf("%d X %d = %d\n", number, count, result);
    }
  }
}

Exercise 2: Write C code to do the following:

Arrays

To declare an array of a particular type of size N we use the declaration:
        type arrayname[N]; // type indicates what each value in the array can be (for example unsigned char).
                      // arrayname is the variable name to which the array will be referred
Examples:
    unsigned char anums[5];     // array of 5 8-bit unsigned numbers
    signed char bnums[8];       // array of 8 8-bit signed numbers
    unsigned short scores[25];  // array of 25 16-bit unsigned numbers

To access individual elements of the array you use the square brackets with the index of the element you wish to access. Note that
indexes start from 0.  So, the first element's index is 0 and the last element's index is (Size-1).

Example 3: Lets say Sum(n) refers to the sum of the numbers n down to 1. For example (Sum(5) is 5+4+3+2+1 which equals 15). We wish to compute theses sums for the first 25 numbers and store them in an array Sum. We have another array FSum that computes these same sums by using a formula instead. We will check if the formula is correct by comparing elements of Sum  against elements of FSum.

#define true 1
#define false 0
#define N 25     // The Size of the Array
void main(void){
  unsigned short num, partialsum, count;
  unsigned short Sum[N], FSum[N]; //Declared arrays to store 16-bit values
  unsigned char correct;

  for (num = 0; num < N; num++){
    partialsum = 0; // partialsum will hold the running sum as we compute it
    for (count = num+1; count >= 1; count--){
      partialsum += count;
    }
    Sum[num] = partialsum; //Note Sum[0] holds Sum(1); Sum[1] holds Sum(2) and so on
  }

  for (num = 1; num <= N; num++){
    FSum[num-1] = (num * (num + 1))/2;
       // Note FSum[0] holds FSum(1); FSum[1] holds FSum(2) and so on
       // The formula is Sum(n) = (n * (n+1))/2
  }

  // Check if the formula and computation agree
  correct = true; // Assume that they match and change it to false if
                  //  there is a mismatch
  for (num = 0; num < N; num++){
    if (Sum[num] != FSum[num]) {
      correct = false;
    }
  }
  if (correct) {
    printf("Formula Works");
  } else {
    printf("Formula Wrong");
  }
}

Exercise 3: Write C code to do the following:
Subroutines (aka Functions)

Subroutines work in C very much like in assembly except they are called functions in C.  

The key elements to note about functions are:
Example 4: Lets rewrite the code from Exercise 3 by modularizing it using subroutines:
#define true 1
#define false 0
#define N 25     // The Size of the Array

unsigned short Sum[N], FSum[N]; //Declared arrays to store 16-bit values
                                // These are now Global so all sub-routines including
                                // main can manipulate them

//Declare function prototypes here so compiler can check if we are
// calling them correctly
unsigned short hardway(unsigned char);
unsigned short formula(unsigned char);
void Check(void);

// The main program uses a modular decomposition of the problem into
// sub-problems that are implemented as functions that are called
int main(void){
  unsigned char num;

  for (num = 0; num < N; num++){
    Sum[num] = hardway(num); //Call the hardway function by passing it num
                               // put the returned sum in the corresponding location
                               // in the array Sum
  }

  for (num = 1; num <= N; num++){
    FSum[num-1] = formula(num);
  }
  Check();
}

unsigned short hardway(unsigned char number ){
  unsigned short sum = 0; // partialsum will hold the
                          //  running sum as we compute it
  unsigned char num, count;

  for (count = number+1; count >= 1; count--){
    sum += count;
  }
  return sum;   // sum holds the result so return it 
}

unsigned short formula(unsigned char number ){

  return (number * (number+1))/2;   // formula
 
}

void Check(void){
  unsigned char correct, num;

  // Check if the formula and computation agree
  correct = true; // Assume that they match and change it to false if
                  //  there is a mismatch
  for (num = 0; num < N; num++){
    if (Sum[num] != FSum[num]) {
      correct = false;
    }
  }
  if (correct) {
    printf("Formula Works");
  } else {
    printf("Formula Wrong");
  }
}
   
Exercise 4: Write a subroutine that counts the number of instances of letter in a string. All strings are 11 characters long (12 bytes including null.) Complete the implementation of the subroutine Count, and test it using the following main program. You may use pointer or index syntax to access data from the string. Make a printout from http://codepad.org showing your code and the output results of running your code. Turn in this printout with your name at the top.     
const struct countTestCase{
unsigned char Letter;        // Letter for which to search
unsigned char Buffer[12];    // String in which to search
unsigned short CorrectCount; // proper result of Count()
};
typedef const struct countTestCase countTestCaseType;
countTestCaseType countTests[7]={
{ 'o', "Hello World", 2},
{ 'b', "Bill Bard  ", 0},
{ 'V', "Jon Valvano", 1},
{ 'a', "Yerraballi ", 2},
{ 's', "Mississippi", 4},
{ '2', "21212121212", 6},
{ '1', "11111111111", 11}};
unsigned short Count(unsigned char letter, unsigned char string[12]){
  return 1000; // replace this line with your code
}
int main(void){
  unsigned short i,result;
  unsigned short errors=0;
  for (i = 0; i < 7; i++){
    result = Count(countTests[i].Letter,countTests[i].Buffer);
    if (result != countTests[i].CorrectCount){
      errors++;
      printf("i=%d, result=%d\n",i,result);
    }
  }
  if (errors==0){
    printf("Program works");
  } else {
    printf("Does not work");
  }
  return 0;
}