User Tools

Site Tools


opus:spring2012:cforman:part2

Part 2

Entries

Entry 5: March 6, 2012

Today we learned about typedef. I still don't know more then the basics of it but it allows you to create an alias for a function like “ typedef int i” allows the user to now say “i x” instead of “int x”. This is just the tip of what it can do i would guess. We also learned about union and struct containers along with a class but that is not a container. These containers are heterogeneous and don't have to contain the same type of data. they can hold ints and chars. Arrays are homogeneous meaning they can only hold one type of data. We also learned that adding -g to our gcc we can allow for debugging when we type gdb ./progname . this is useful because everyone likes to debug.

Entry 6: March 13, 2012

Today we manipulated our first C++ program into file separation and rejoined them up making our original program and script shorter. This idea allows us to sepperate the functions of a program into smaller pieces that may seem more manageable and make our final script look just that much nicer. this is good for working in groups so that each person can take a chunk and work on it then piece it all together again later.

Entry 7: March 15, 2012

Today we discussed the project2 and the importance of Paper. Why is paper important. (i use a whiteboard at home and a camera) Paper helps one organize their thoughts and visually see the code in their head before typing it all out. Paper also helps you run through problems to see an exact process you think it will follow. It doesn't help with syntax but it will help with your logic. Object oriented programming teaches us that paper is key and it never hurts to make some psuedocode and a uml document sometimes.

Entry 8: March 1, 2012

(yes this is out of order)

Today we discussed ways to fix project 1 by either flipping the letters back to the beginning of the alphabet or by changing all letters to their ASCII chart equivalent numbers allowing for a lot more flexibility. We also looked at a project that was multifunctioned or had more then one function in the script that contained it. The program took a number and ran it through a series of tests to check and see if it was even or odd. This was a a huge change because it gave us a hint into how to better organize our data within a script.

Keywords

cprog Keywords

Pointers(address of, assignment, dereferencing

Definition

A pointer is basically something that contains a memory address of whatever it is pointing at. When you assign a pointer it will then point at that objects memory location. It is possible to use these pointers in another way like in arrays after you dereference it. The following code and result will show how this is done.

Demonstration

Demonstration of the chosen keyword.

If you wish to aid your definition with a code sample, you can do so by using a wiki code block, an example follows:

#include <stdio.h>
int main ()
{
        int v=17;
        int *p1=NULL;
        printf("v is %u\n", v);
        p1=&v;
        printf("*p1 is %u\n", *p1);
        *p1=53;
        printf("v is %u\n", v);
        printf("*p1 is %u\n", *p1);
        v=7;
        printf("v is %u\n", v);
        printf("*p1 is %u\n", *p1);
        return(0);
 
 
}

Alternatively (or additionally), if you want to demonstrate something on the command-line, you can do so as follows:

lab46:~/src/cprog$ ./arrows
v is 17
*p1 is 17
v is 53
*p1 is 53
v is 7
*p1 is 7

Selection Structures(if,case/switch)

Definition

Selection structures allow for variation. When most beginning programs tend to be linear Selection Structures allow for branches within a program to form. The first type is an if statement which is usually just understood. If this then that else go there type program. say if (a < b) {

do this stuff

}

if it is not true it just goes around it. There can be nested if statements creating a messier but deeper program. The next type is called Switch and it can be used when one needs to have a series of options that can be selected. This is useful when we write code based on a variable. The following is not my code but code i found that shows what it is.

Demonstration
switch(var) {
    case  constant1:
          statement;
          ...
          break;
    case constant2:
         statement;
         ...
         break;
    default:
         statement;
         ...
         break;
    }

This shows just a basic idea of how to use it but i am still not familiar with it.

File Access(Read,Write,Append)

Definition

This can be done in or outside of a program. We read and write in files whenever we go near a program. The availability to read, write or append is based on ones settings in chmod.

#	Permission
7	full
6	read and write
5	read and execute
4	read only
3	write and execute
2	write only
1	execute only
0	none

(taken from Wikipedia under Chmod) the other way is to use fopen (“thisisfile.txt”, permission) here is a list of permissions taken from http://www.cplusplus.com/reference/clibrary/cstdio/fopen/

"r"	Open a file for reading. The file must exist.
"w"	Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
"a"	Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.
"r+"	Open a file for update both reading and writing. The file must exist.
"w+"	Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
"a+"	Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

Typedef, enum, union

Definition

I really only understand typedef in its most basic form but can be very convenient.

 typedef int i
 i x

the i now stands for int allowing you to waste less time typing it. Typedef can be used on much larger function like long long int and such creating a easier way to do tings. Enum is a lot more complicated and i am having a difficult time grasping it right now but aperently it can be used as a glorified number say (not my code) public static final in SEASON_WINTER = 0; could be a enum while enums can also be used in this way( i do not know how to do this this is from java but is pretty cool in how it is used. http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html)

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO   (1.27e+22,  1.137e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    public double mass()   { return mass; }
    public double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}
 public static void main(String[] args) {
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413
Your weight on PLUTO is 11.703031

epic (this is java use but shows what it is capable in some languages.) This is a version in C from http://msdn.microsoft.com/en-us/library/whbyts4t(v=vs.80).aspx

enum DAY            /* Defines an enumeration type    */
{
    saturday,       /* Names day and declares a       */
    sunday = 0,     /* variable named workday with    */ 
    monday,         /* that type                      */
    tuesday,
    wednesday,      /* wednesday is associated with 3 */
    thursday,
    friday
} workday;

this is good in its own way but is just placing numbers into variable in a simpler fashion then doing it the long way by separating them all and adding = blah to it. Union is the final type. Union is a container that can hold multiple variables of different types but cant use both variables at the same time because one will get all screwy. They allow for really easy data manipulation and with typedef make for short work when it comes to typing things out.

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

int main()
{
        int i;
        union var {
                int x;
                float f;
        };
        typedef union var Uif;
        Uif value;
        value.x=0;
        for(i=0;i<24;i++)
        {
                value.x=value.x+rand()%51+1;
        }
        printf("total is: %d\n", value.x);
        value.f=0.0;
        for(i=0;i<73;i++)
        {
                value.f=value.f+rand()%27+0.1;
        }
        printf("total is: %f\n",value.f);
        return(0);
lab46:~/src/cprog$ ./union
total is: 734
total is: 937.299438
lab46:~/src/cprog$

Arrays (standard notation, pointer arithmetic, single-dimensional, multi-dimensional)

Identification of chosen keyword (unless you update the section heading above).

Definition

STANDARD FORM The standard form of an array that we were taught in class is as follows. arr1 = (int *)malloc( sizeof(int) * (sizea-1)); What this does is it takes the array “arr1” and gives it the size of one int or relatively the ability to hold one int, but we then malloc that array to increase its size by the number we desire allowing it to hold a set number of anything.

POINTER ARITHMETIC c = arr1[i-1]; or arr[ i ] == * ( arr + i )

both add using pointers. Subtraction will have the same results but in the opposite direction. This allows you to change the location of the array you wish to access.

SINGLE DIMENSIONAL This array can only hold one thing in each slot of the array. int[] myArray = new int[] {1, 3, 5, 7, 9}; each piece separated by a comma is in its own block within the array. This makes more sense next.

MULTIDIMENSIONAL ARRAYS This array can hold multiple things in each block of the array and i don't mean digits that are multiple numbers long. int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; now each thing in {} is in a different block so array2D[0] would contain 1 and 2 and so forth for each block of the array. This is useful because say you input one thing and expect a set of something else. Each set can be stored into one block of an array and then your distinction would point to which block to get the data from.

Structures (Declaration, Accessing Elements, Pointers to)

Definition

DECLARATION

typedef struct {

        char name[64];
        char course[128];
        int age;
        int year;
} student;

This usually comes after the #include of a program. A Struct basically allows the user to set variables usable in multiple locations through out a script.

ACCESSING ELEMENTS

st_rec.name

using this we can use the variable in struct. This in general is just a variable name for the element in the struct. This is longer but if you have multiple functions inside one script you will not have to redefine each variable within each code block.

POINTERS TO

st_ptr -> name

The → indicates that you are selecting from a structure pointer.

• I/O Streams (cin, cout, cerr, stream operators) [C++]

Definition
#include <iostream>
  3     cout  // standered out in c
  4     cin   // standard in in c
  5     cerr  // standard error in c
  6
  7     printf("Hello, Workd!\n");
  8     cout << "hello, world!" << endl;
  9
 10     a=4,b=2;
 11     printf("a is %d, b is %d\n", a,b);
 12     cout << "a is" << a << "b is" << b << endl;
 13     cout << "a is" << hex << a<< endl;
 14                       bin
 15                       oct
 16                       dec
 17
 18
 19
 20     cin >> a;
 21     scanf("%d", &a);

 23
 24
 25     cerr << "ERROR! RABID CHICKENS!" << endl;
 26
 27
 28 // if i want to use these i need to declair a namespace. i do this by ....
 29
 30 using namespace std;
 31 before my main will allow them to be used in main
 32
                                 

the above shows I/O stream functions and their C equivalent. The operators are « and ». There are other operations or manipulators that can be placed in the I/O stream

endl 	"end line": inserts a newline into the stream and calls flush.
ends 	"end string": inserts a null character into the stream and calls flush.
flush 	forces an output stream to write any buffered characters
dec 	changes the output format of number to be in decimal format
oct 	changes the output format of number to be in octal format
hex 	changes the output format of number to be in hexadecimal format
ws 	causes an inputstream to 'eat' whitespace
showpoint 	tells the stream to show the decimal point and some zeros with whole numbers

• Namespaces [C++]

Definition

This is referring to the above key word ^^^^^^^^^^. At the end of the first cli block it says to use “namespace std”. “std” stands for standard. This is reffering to standard (input output, library[most likely]). How to use this. Here is an example from http://www.cplusplus.com/doc/tutorial/namespaces/

// using namespace example
#include <iostream>
using namespace std;

namespace first
{
  int x = 5;
}

namespace second
{
  double x = 3.1416;
}

int main () {
  {
    using namespace first;
    cout << x << endl;
  }
  {
    using namespace second;
    cout << x << endl;
  }
  return 0;
}

What this demonstrates is that one can creat their own namespaces like std and use them throughout the program. Downside is that you have to keep saying what namespace you are using but this can be a great aid with some programs.

cprog Objective

cprog Objective

State the course objective

Definition

In your own words, define what that objective entails.

Method

State the method you will use for measuring successful academic/intellectual achievement of this objective.

Measurement

Follow your method and obtain a measurement. Document the results here.

Analysis

Reflect upon your results of the measurement to ascertain your achievement of the particular course objective.

  • How did you do?
  • Is there room for improvement?
  • Could the measurement process be enhanced to be more effective?
  • Do you think this enhancement would be efficient to employ?
  • Could the course objective be altered to be more applicable? How would you alter it?

Experiments

Experiment 4

Question

Can I use OCT, HEX, and DEC work in an printf if they work in an I/O stream?

Resources

man 3 printf

Hypothesis

Yes i can convert things into HEX,DEC,and OCT format. This is because C++ is a more simplified version of C so therefore C must have the functionality to do what C++ can but in a possibly harder format.

Experiment

How are you going to test your hypothesis? I am going to test my hypothesis through attempting to give a variable “a” a value and convert that value in a printf statement into a different base.

Data

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3
  4 int main()
  5 {
  6     int a = 4923523;
  7     printf("This is a in HEX : %x\n", a);
  8
  9     printf("This is a in OCT: %o\n", a);
 10
 11     printf("This is a as a plain DEC: %u\n",a);
 12     return(0);
 13 }

Here is the results.

lab46:~/src/cprog$ ./expiremnt4
This is a in HEX : 4b2083
This is a in OCT: 22620203
This is a as a plain DEC: 4923523
lab46:~/src/cprog$ vi expiremnt4.c
lab46:~/src/cprog$

Analysis

Based on the data collected:

  • Was your hypothesis correct?
    • yes
  • Was your hypothesis not applicable?
    • no
  • Is there more going on than you originally thought? (shortcomings in hypothesis)
    • no none that i could see.
  • What shortcomings might there be in your experiment?
    • it is possible i exclueded some factor like what if the number was already in hex and i tried to print it as hex would it still recognize it?(next expirement <(^^,)> )

Conclusions

It is possible to convert the results to different formats within the actual printf statement as one would do in a cout stream in c++.

Experiment 5

Question

Based on experiment 4. Would %x stay the same or change if i enter in a already HEX number?

Resources

experiment 4.

Hypothesis

I believe that it will remain the same.

The developers must have thought this idea through if they allowed for the conversion to take place at all. %u doesn't try and convert when a decimal number is already existent.

Experiment

I am going to change a in the above program and see if it can run the same three printf statements and comvert from hex and see if %x can recognize a hex digit and keep it the same.

Data

 1 #include <stdio.h>
  2 #include <stdlib.h>
  3
  4 int main()
  5 {
  6     int a = 0x4b2083;
  7     printf("This is a in HEX : %x\n", a);
  8
  9     printf("This is a in OCT: %o\n", a);
 10
 11     printf("This is a as a plain DEC: %u\n",a);
 12     return(0);
 13 }

This is my attempt at trying to input a hex digit. I tried it the first time and it did not like the numbers but i looked up some possible solutions and learned that the computer won't recognize a hex digit without 0x infront of it else it will just complain about the letters. Here are the results.

lab46:~/src/cprog$ ./expiremnt4
This is a in HEX : 4b2083
This is a in OCT: 22620203
This is a as a plain DEC: 4923523

as you can see this matches the above projects results.

Analysis

Based on the data collected:

  • Was your hypothesis correct?
    • yes
  • Was your hypothesis not applicable?
    • no
  • Is there more going on than you originally thought? (shortcomings in hypothesis)
    • i dont think so.
  • What shortcomings might there be in your experiment?
    • none that i can see

Conclusions

The way C was designed keeps it from excepting just letters as part of a number but with the right deffinitions on the number it can be seen as what the letters represent as with the 0x allowing letters up to f to be in a number as it is part of the hex digit system. The computer can also recognize and convert a hex digit to a dec or oct equivalent.

Retest 2

Perform the following steps:

State Experiment

Whose existing experiment are you going to retest? Provide the URL, note the author, and restate their question.

Resources

Evaluate their resources and commentary. Answer the following questions:

  • Do you feel the given resources are adequate in providing sufficient background information?
  • Are there additional resources you've found that you can add to the resources list?
  • Does the original experimenter appear to have obtained a necessary fundamental understanding of the concepts leading up to their stated experiment?
  • If you find a deviation in opinion, state why you think this might exist.

Hypothesis

State their experiment's hypothesis. Answer the following questions:

  • Do you feel their hypothesis is adequate in capturing the essence of what they're trying to discover?
  • What improvements could you make to their hypothesis, if any?

Experiment

Follow the steps given to recreate the original experiment. Answer the following questions:

  • Are the instructions correct in successfully achieving the results?
  • Is there room for improvement in the experiment instructions/description? What suggestions would you make?
  • Would you make any alterations to the structure of the experiment to yield better results? What, and why?

Data

Publish the data you have gained from your performing of the experiment here.

Analysis

Answer the following:

  • Does the data seem in-line with the published data from the original author?
  • Can you explain any deviations?
  • How about any sources of error?
  • Is the stated hypothesis adequate?

Conclusions

Answer the following:

  • What conclusions can you make based on performing the experiment?
  • Do you feel the experiment was adequate in obtaining a further understanding of a concept?
  • Does the original author appear to have gotten some value out of performing the experiment?
  • Any suggestions or observations that could improve this particular process (in general, or specifically you, or specifically for the original author).
opus/spring2012/cforman/part2.txt · Last modified: 2012/04/01 03:58 by cforman