Lab 9 Source Code

Lab 9.1

Either cut-and-paste the following into your lab, or

lab-9.1.c

#include <stdio.h>
#include <string.h>
#include <math.h>
 
/* Header */
 
char COLOR_CODES[10][7] = {"black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "gray", "white"};
 
int readColor(int bandNumber) {
  int colorNumber = -1;
  int i;
  /* Declare a string to hold the color name typed in at the keyboard. */
 
  do {
        /* Prompt to read color name for the indicated band. */
 
        /* Read a color band name as a string. */
 
        /* Make sure the color band name is lower case */
 
        /* Change "purple" to "violet", and "grey" to "gray" */
 
        /* Search for the color name, */
        /* if found, set colorNumber to array index matching the color */
 
        /* If the color typed in was not found, print an error message */
 
  } while (colorNumber == -1);
 
  return(colorNumber);
}
 
 
void outputResistance(double resistance) {
  printf("Resistance is: ");
 
  /* Print ohms, kilo-ohms, or Mega-ohms. Use if, else-if structure. */
  if (resistance <= 999.95) {
        /* Print resistance in ohms */
  } else if (/* Fill this in*/) {
        /* Print resistance in kilo-ohms */
  } else {
        /* Print resistance in Mega-ohms */
        printf("%.1f Mega-ohms.\n", resistance/1000000.0);
  }
}
 
 
int main(void) {
  int band1, band2, band3;
  double resistance;
  char yesNoAnswer[20];
 
  do {
        printf("Enter the three color bands of a resistor, ");
        printf("one at a time as prompted.\n");
        band1 = readColor(1);
        band2 = readColor(2);
        band3 = readColor(3);
 
        /* Calculate the resistance from the bands entered. */
        /* Use the "pow" function. */
 
 
        outputResistance(resistance);
 
        printf("\n\nDo you want to decode another resistor? ");
        printf("[answer Y or N] ");
 
        /* Read answer as string */
 
        /* Make sure answer is lower case before comparing it */
 
  } while (/* Compare answer for "yes" */);
 
  return(0);
}

Lab 9.2

Either cut-and-paste the following into your lab, or

lab-9.2.c

void readAccountInfo(void) {
    FILE * accountfile_p;
    int i, items;
    int accountID;
    double balance;

    accountfile_p = fopen("accounts.txt", "r");

    if (accountfile_p != NULL) {
        for (i = 0; i < MAX_ACCTS; ++i) {
            items = fscanf(accountfile_p, "%d %lf", &accountID, &balance);

            if (items != EOF) {
                accounts[i] = accountID;
                balances[i] = balance;
            } else {
                break;
            }
        }

        numOfActiveAccts = i;
        fclose(accountfile_p);
    }
}