User Tools

Site Tools


opus:spring2012:cforman:cprogpart2

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?
opus/spring2012/cforman/cprogpart2.txt · Last modified: 2012/03/31 23:14 by cforman