Wednesday, October 18, 2017

Day 15 - Higher Dimensional Arrays and pointers

AGENDA:

  1. Brainstorm and begin project 2.
  2. Complete pointers assignment.
  3. Finish Motor Lab.

OVERVIEW:
Today we learned about the concept of higher dimensional arrays and how they can be utilized to store different types of information---such as x-, y-, and z-coordinates. We also learned about the relationship between variables, pointers, and addresses.

CLASSWORK:
Variables, Pointers, & Addresses:

This program demonstrates the relationship between pointers, variables, and addresses. It displays the contents and addresses of ints a and b as well as the pointer ptr;


This is the ouput for the aforementioned program in Repl.it. I ran it three more times to see if there was a difference.



Things I noticed:
  1. The pointer ptr always points to the value addressed to a, which is 1.
  2. The memory address for integers appears to be nine digits long.
  3. Only the last 2 digits of each address appear to be changing.
  4. The value of ptr is the memory address of a.
  5. The address of ptr is uniquely different from the addresses of a and b.
I also ran this program in Virtual C. Here are the results.

I ran the program four times, but the address numbers stayed the same. 
Conclusion:
Different compilers have different methods for assigning address numbers to data types.


HOMEWORK:
Pointers HW:
Given this information:
int i1, i2;
int *p1, *p2;
...
i1 = 5
p1 = &i1;
i2 = *p1/2 + 10;
p2 = p1;

What is the value of il, i2, *p1, and *p2?
First, I edited the program we wrote during class. Then I analyzed the code.

Prediction:
In line 10, i1 is assigned the value 5. In the next line, p1 is assigned the value of the integer memory address associated with il. This implies that *p1 points to the value associated with i1, which is 5. In line 12, the integer i2 will be assigned a value ten more than half the value pointed to by *p1. Since *p1 points to the value of 5, i2 would be assigned the value (5/2) + 10 = 12.5. However, since i2 is an integer, the program will either round it up to 13 or round it down to 12 depending on the compiler. Line 13 asserts that p2 will be assigned to the value of p1, which is the integer memory address of i1. This statement implies that *p2 will also point to the value pointed to by p1. Therefore,  *p2 point the value i1=5.


I ran this program three more times in Repl.it to see how it would change.




Similar to the program we analyzed during class, the last two integers in the addresses change, while the numbers assigned to each variable i1 and i2 remain the same. I also ran this program in Virtual C. Unsurprisingly, the outcome was extremely similar to the program we ran during class as well.


Much like the program we ran during class, both the address numbers and the values assigned to each integer i1 and i2 remained the same.



Monday, October 2, 2017

Day 2 - Input/Output

AGENDA:

  1. Modify the massgrave.c program
  2. Complete Amino Acid Molecular Weights program
OVERVIEW:
Today we learned about the priority of operators. Priority of operators is important because much like the order of operations in mathematics(PEMDAS), the way that we write an equation in C can drastically change the way it is evaluated. As of today, the following graph illustrates the precedence of the operators we have been introduced to thus far:
This chart means that parentheses are evaluated first. If there are other operations within the parentheses, then those operations take precedence over anything outside them. The next items evaluated are unary operators. These include the increment and decrement operators: n++ and n--. The next items evaluated are the binary operators such as multiplication(*), division(/), and the modulus operator(%); where binary addition and subtraction are evaluated last. 

We also learned about the concepts of overflow and underflow. These concepts are pertinent to coding in C because our computer only allows a specific range of values for computations. If we exceed those limits, then we may get an error, a zero, or a nonsensical integer in our program. For example, we learned in class that integers in C can only go from -32,768 to 32,768. These values correspond to 16 bits of information---or 2^16 numerical values. If our calculations exceed the specified values, then we receive an overflow error. If our calculations are below the specified range, then we receive an underflow error.

Our class also learned more about the proper syntax behind printf() statements and scanf() statements. Consider the following example:

/*-Degrees2Radians----------------------------------*/
/*----This program takes user input in degrees and--*/
/*----computes the angle measure in radians---------*/
//Call the necessary preprocessing directives
#include <stdio.h>
#include <math.h>
//Declare a symbolic constant for pi
#define PI 3.141593

int main (void) {
//Declare and initialize variables
double angle_rad, angle_deg;
//Ask for user input from keyboard in degress
printf("Input values in degrees: \n");
scanf("%lf", &angle_deg);
//Compute the angle measure conversion
angle_rad = (angle_deg*PI)/180;
//Print out the angle measure in radians
printf("Angle = %5.4f radians \n", angle_rad);
//Ends program
return 0;
}

Let's break it down below:
Consider the scanf() statement highlighted in green. scanf() statements are utilized to take user input from the keyboard. In essence, it takes values inputted by the user and stores them into a variable of the coder's choosing. It takes two arguments: a control string in double quotation marks and memory location---indicated by the ampersand(&) symbol---for the variable itself. In the control string, the coder must input a type specifier---e.g. %i for int, %f for float,%u for unsigned int, etc--- to determine the type of variable the user will type. I chose %lf for long float because my variable angle_deg is a double. I used the following chart to find the appropriate  type specifiers for my variables:

Now consider the printf() statement in blue. As the name suggests, this function's purpose is to print out statements of the coder's choosing. Much like scanf(), the printf() statement also has a control string; the major difference being that you can input text to be displayed within the control string. The \n at the end of the control string is called the newline operator. This lets the program know to move over to a new line in the display window after that part of the code has been run. The number in front of the type specifier---%5.4f--- does two things: (a) the 5 tells the program the width of the number and (b) the 4 tells the number of decimal places after the decimal point. After the control string, there is a comma to separate itself from the next argument: the variable itself. More specifically, it tells the program that you want it to display the value stored in the variable angle_rad in place of the type specifier in the control string.

So using this information, we can predict exactly what the program will display given these statements and a degree measure of 30.

Input values in degrees: from printf()
30                       from scanf()
Angle = 0.5236 radians   from printf()

Let's see if repl.it agrees with out prediction:

Looks like our prediction was correct.


CLASSWORK:
Height from Bone Length:
In class, we created and examined a program that estimated the height of a human being based on the  length of their femur and the length of their humerus. First, we created a decomposition outline. Next, we wrote pseudocode that emulated the steps we would take to write the program. Lastly, we wrote the program.




HOMEWORK:
Bone to Height Modifications:
For homework, I made five different modification to this program from class. However, I just want to share one modification in this blog because I think it was the most interesting. The goal:  Modify the program so that it reads the input values in inches and then estimates the output heights using feet and inches. (Note that you are printing two output values for each height estimate).

/*----------------------------------------------------------------*/
/*  Bone2Height  HW 2 - #3                                        */
/*  This program estimates the height                             */
/*  of a person based on bone length                              */
#include <stdio.h>
#include <math.h>

int main(void)
{
  /*  Declare and initialize variables. */ 
  float humerus, femur;
  /* m = male, f = female, ht = height, in = inches, ft = feet, 
     rem = remainder */

  /* These variables give the whole height in inches */
  float m_femur_ht_in, m_humerus_ht_in, f_femur_ht_in,                   f_humerus_ht_in;
  /* These variables give the leftover height in inches */
  float m_femur_rem_in,m_humerus_rem_in, f_femur_rem_in,                 f_humerus_rem_in;
  /* These variables give the whole number height in feet */
  float m_femur_ht_ft, m_humerus_ht_ft, f_femur_ht_ft,                   f_humerus_ht_ft;
  
  /*  Receive user input from keyboard. */
  printf("Enter Values in Inches: \n");
  printf("Length of femur? \n");
  scanf("%f", &femur);
  printf("Length of humerus? \n");
  scanf("%f", &humerus);
  
  /*  Height estimation from femur length in Inches */
  m_femur_ht_in = ((femur * 1.88) + 32);
  f_femur_ht_in = ((femur * 1.94) + 28.7);
  /*  Height estimation from humerus length in Inches */
  m_humerus_ht_in = ((humerus * 2.9) + 27.9);
  f_humerus_ht_in = ((humerus * 2.8) + 28.2);
  
  /* Remainder of height in Inches */
  m_femur_rem_in = fmod(m_femur_ht_in, 12);
  f_femur_rem_in = fmod(f_femur_ht_in, 12);
  m_humerus_rem_in = fmod(m_humerus_ht_in, 12);
  f_humerus_rem_in = fmod(f_humerus_ht_in, 12);
  
  /* Height estimation from femur in Feet */
  m_femur_ht_ft = (m_femur_ht_in - m_femur_rem_in) / 12;
  f_femur_ht_ft = (f_femur_ht_in - f_femur_rem_in) / 12;
  /* Height estimation from humerus in Feet */
  m_humerus_ht_ft = (m_humerus_ht_in - m_humerus_rem_in) / 12;
  f_humerus_ht_ft = (f_humerus_ht_in - f_humerus_rem_in) / 12;
  
  /*Print out height estimations */
  printf("\nHeight Estimates in Feet and Inches:\n");
  printf("Femur Male Height: %5.1f feet %5.1f inches\n",                 m_femur_ht_ft, 
     m_femur_rem_in);
  printf("Femur Female Height: %5.1f feet %5.1f inches\n",               f_femur_ht_ft, 
     f_femur_rem_in);
  printf("Humerus Male Height: %5.1f feet %5.1f inches\n",               m_humerus_ht_ft, 
     m_humerus_rem_in);
  printf("Humerus Female Height %5.1f feet %5.1f inches\n",               f_humerus_ht_ft, 
     f_humerus_rem_in);
  /*  Exit program */
  return 0;
}

This program took me the longest to complete out of all of the modifications because I had trouble trying to calculate the remainder of a floating point value. First, I tried the modulus operator, but it wouldn't work with floating point values. So I searched online for other methods when I came across this function called fmod(). It functioned just like the modulus operator only that it worked with floating point values. Much like the modulus operator, it takes two arguments A and B. In practice, I've found that:

fmod(A,B) = A%B where A and B are floats for fmod and ints for %.

Here is the output of the program:
If we compare the values we obtained from the previous iteration---under classwork section--- to this program, we can see that our height estimates are exactly the same, but in a different form.

Amino Acid Molecular Weights:
This program asks for the user to input the number of atoms of each of the five elements (O, C, N, S, H) and output the molecular weight of its corresponding amino acid. I used this chart for reference.

Below is the code I used wrote for this assignment:

/*----------------------------------------------------------------*/
/*  Molecular_Weight HW 2.5 #1                                    */
/*    This program computes the molecular                         */
/*    weight of glycine                                           */
#include <stdio.h>
#include <math.h>

/*  Assigns the molecular weights of common elements on periodic table*/
#define O 15.9994
#define C 12.011
#define N 14.00674
#define S 32.066
#define H 1.00794

int main(void)
{
  /*  Define and initialize variables */
  int oxygen, carbon, nitrogen, sulfur, hydrogen;
  double mol_weight;
  /*  Get user input from keyboard */
  printf("Enter Whole Number Values:\n");
  printf("Number of Oxygen atoms?\n");
  scanf("%i",&oxygen);
  printf("Number of Carbon atoms?\n");
  scanf("%i",&carbon);
  printf("Number of Nitrogen atoms?\n");
  scanf("%i",&nitrogen);
  printf("Number of Sulfur atoms?\n");
  scanf("%i",&sulfur);
  printf("Number of Hydrogen atoms?\n");
  scanf("%i",&hydrogen);
  /*  Calculate the molecular weight */
  mol_weight = (O*oxygen) + (C*carbon) + (N*nitrogen) + (S*sulfur) + (H*hydrogen); 
  /*  Print molecular weights */
  printf("\nAmino Acid Molecular Weight:\n");
  printf("Glycine: %f grams", mol_weight);
  return 0;
  
Here is the code in action within the display window:

Right now, it only displays Glycine. However, if I add the following lines of code into the aforementioned program, then it should output the molecular weight with the name of its corresponding amino acid. This excerpt of code assigns each amino acid a unique 5 digit code based on the number of molecules for each of the five elements.

int code;
code = (oxygen*10000) + (carbon*1000) + (nitrogen*100) + (sulfur*10) + hydrogen

if (code==23107) {
printf("Alanine: %f grams", mol_weight);

else if (code==26415) {
printf("Arginine: %f grams", mol_weight);

...
else if (code==26113) {
printf("(Iso)leucine: %f grams", mol_weight);

...
else if (code==25121) {
printf("Methionine: %f grams", mol_weight);

...
else if (code==31211) {
printf("Tryptophan: %f grams", mol_weight);

... etc.

I tried out my code in repl.it, and made a few tweaks:

The final else statement on line 97 is there to ensure that the program knows what to print out if none of the other else if statements are true. I added a second condition to some of my if statements to ensure that users didn't type an erroneous combination of elements and also yield a molecular weight.
It works just as I intended it to:
Working correctly
Redundancy Check




Sunday, October 1, 2017

Day 2 - Lab: Knight Rider LEDs

OVERVIEW:
Today, we set up our Arduino by downloading the necessary software to our computers. We also wrote our first computer program in the Arduino software. Our task was to make an LED blink on and off. For homework, we have to figure out how to wire multiple LEDs to our breadboard and make them interact with the Arduino. More specifically, we have to make our LEDs blink similar to the way the KITT car from Knight Rider blinks. Here is a preview of the materials we used:

Note: Those are 1k ohm resistors


IN CLASS LAB:
The lab we did in class was relatively simple. All we had to do was wire a single LED to our breadboard and make it blink using the Arduino. This is the sample code we analyzed and compiled for the in-class lab:

void setup() { 
pinMode(10,OUTPUT); //Initialize Pin 

void loop() { 
digitalWrite(10,HIGH); //Set the LED On 
delay(1000); //Wait for 1000 ms 
digitalWrite(10,LOW); //Set the LED Off 
delay(1000); //Wait for 1 second 

LED wired to Arduino

LAB HOMEWORK:
In class, we learned how to wire one LED to a breadboard. Our task for homework was to wire several LEDs to a breadboard and see if we could light them up like the KITT car. A quick Google search revealed that the way the LEDs blinked and moved on the show was much more complicated than I had imagined. At first, I just tried getting the LEDs to move back and forth in a straight line.

Here is the corresponding LED circuit in action with the code uploaded to the Arduino:

This worked out alright, but it wasn't exactly what I was hoping for. With this code, the LEDs only turned on and off sequentially. However, in the TV show, the car had several lights on at a single time with varying brightness around the "center point". In other words, there were always other LEDs leading and following the brightest one in the sequence. With this in mind, I began to write a modified version of the aforementioned code that would incorporate these "trailing" LEDs.




I liked this way much better, so I decided to keep it for the next class. In hindsight, I think I could have made my code much neater and less repetitive by making my LED pin number a variable and using it as a counter in a few for() statements. For example, the Blinking_LED_2 code from above could have been rewritten as the following:

int LEDpin = 10;
int LEDonTime = 200;
int LEDoffTime = 200;

void setup() {
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
pinMode(7, OUTPUT);
pinMode(6, OUTPUT);
pinMode(5, OUTPUT);
}

void loop() {
for (LEDpin=10; LEDpin>=5; k--) {
digitalWrite(LEDpin, HIGH);
delay(LEDonTime);
}

for (LEDpin=10; LEDpin>=7; k--) {
digitalWrite(LEDpin, LOW);
delay(LEDoffTime);
}

for (LEDpin=7; LEDpin<=10; k++) {
digitalWrite(LEDpin, HIGH);
delay(LEDonTime);
}

for (LEDpin=5; LEDpin<=8; k++) {
digitalWrite(LEDpin, LOW);
delay(LEDoffTime);
}
}

I was curious to see if this code would actually work, so I decided to upload it to the Arduino.


Here is a video clip of the modified code in action. The results are very similar to the original.

As you can see, the results of this modified code are almost exactly the same as its previous iteration. Therefore, my modified code is definitely more efficient than the old one.