Thursday, January 31, 2008

CSE2031 Lecture 8

  • When creating a struct no space is allocated
  • typedef
    • Make a new type name
  • Typedef double grade
    • "grade" is now a new type
    • grade g1 = 3.5
      • Grade can be used whenever double is used
    • Typedef unsigned int size_t;
    • Typedef void (*_sighandler_t)(int)
  • Pointers to structs
    • Structpoint p1;
    • Structpoint* pp;
    • pp = &p1;
    • the name of a struct is not a pointer to the beginning of the variable
    • p1.x = 9
    • *pp.x = 9 //doesn't work
      • Because dot operator has precedence over *
    • (*pp).x = 9
      • // will properly dereference the struct
    • ppàx = 9
      • same as (*pp).x =9 only this is proper
  • self referential structures
  • if you don't use malloc calloc etc it is put on the stack not the heap
  • look in back of the book under IO
    • c library IO(buffered)
    • this is the buffer which input and output is written to
    • int getChar(void)
    • int putchar(int)
    • scanf
    • printf
  • file access
    • FILE
      • The way you create one is
        • FILE * fp
        • fp = fopen("filename", mode);
        • mode is
          • read write and append
          • a 2 character string
          • char*
        • instead of filename you can use
          • "rb"
          • "wb"
          • Ab"
          • "rt"
          • "wt"
          • "at"


 


 


 

//creating a structpoint//

--------------------

structpoint{

    int x;

    int y;


 

    }

---------------------------


 

structpoint p1;

p1.x = 5;

p1.y = 6;

------------

or


 

structpoint p1 = {5,6};

----------------------------------

or

structpoint{

int x;

int y;

}

p1;

p1.x = 5

p1.y = 6;

//you can make a new struct doing it this way

--------------------------------------

struct{

int x;

int y;

}

p1.x = 5;

p1.y = 6;

//cannot make a second struct doing it this way

---------------------------------------

typef unsigned int size_t;

typedef void (*_sighandler_t)(int)

--------------------------------------

typedef structpoint {

int x;

int y;

}

point;

/*now "point" is the name of a type

* it can have pint p1;

*instead of structpoint p1

*/

--------------------------------

/* self referential structures*/

struct listNode{

int value;

struct listNode* next;

}

--------------------------------

struct treeNode{

int value;

struct treeNode* left;

struct treeNode* right;

}

------------------------------------

or

--------------------------------------

typedef structTNode* TreePtr

typedef structTNode{

int value;

TreePtr left;

TreePtr right;

}TreeNode


 

-----------------------------------------

TreePtr root = (TreePtr)malloc(sizeof(TreeNode));         // - do not do this instead - sizeof(int) + 2*sizeof(TreePtr)

root->value = 5;

root -> right = (TreePtr)malloc(sizeof(TreeNode));

root -> right ->value=2;

root -> right->right =null;

root -> right ->left = null;

/*creates a binaryTree with root starting point at 5 pointing to a 2 on its right side that has no strings after it*/

--------------------

struct item{

double price;

char name[50];

}

item x1;

strcpy(x1,name, "Notebook");

---------------------------

struct item{

double price;

char* name;

}

item x1;

x1.name = "notebook";

-----------------------------------

fprintf(fp,...);

fscanf(fp,...);

fclose(fp);

ferror(fp);

intfeof(fp); //if you reached end of file on that file

fflush(fp);

fseek(fp,...);

fsetpos(fp,...);

--------buffered standard output under this line--

stdin

stdont

stderr

---------unbuffered under this line---


 

STDIN_FILENO         0

STDOUT_FILENO        1

STDERR_FILENO        2

--------------------------------------------------

#include <stdio.h>

#include <unistd.h>

int main(void)

{

printf("a");

write(1, "X", 1);

fprintf(stdout, "B");

write (1,"Y", 1);

printf("C");

write(1, "Z\n", 2);

printf("\n");

return 0;

/*output is

XYZ

ABC

this is becuase it's buffered

/*

}

                        

Tuesday, January 29, 2008

CSE2031 Lecture 7

void* ß malloc (int n)

int *p;

p = malloc (50 * sizeof(int));

Or

p = (int*) malloc(50*sizeof(int));

if((p=malloc(..) ) == null)

{

…exit(1)

}

free(p); //deallocate this space;

  • calloc enters 0's in memory for allocated space
  • go to man 3 malloc
    • talks about malloc calloc and realloc
    • realloc
      • allows you to resize memory partition previously allocated
  • arrays in C don't know how long they are

int x //declares an int

int f(int a , double b) // function that returns an int

int *f(int a, double b) //pointer to a unction that returns an int

int (*f)(int a, double b )//declares a function that takes parameters and returns an int


 


 


 


 


 


 


 


 


 

#include <stdlib.h>

#include <stdio.h>

#include <string.h>


 

int strCompare(const void *, const void *);

int intCompare(const void* p1, const void* p2);

int main(void)

{

char* A[] = {"30","3","20","2","0","5","10","1","40","4", "5"};

    for (i = 0;i<11;i++)

{

printf("%s ", A[i[);

}

putchar('\n');

qsort(A, sizeof(A)/sizeof(char *), sizeof(char *), strCompare);

return 0;

}

int strCompare(const void*p1,const void*p2)

{

int n = strcmp(*(char**)p1, *(char**)p2); //

if (n<0) return -1;

if (n>0) return 1;

return 0;

}

int intCompare(const void*p1, const void*p2)

{

int n1 = atoi(*(char**)p1);

int n2 = atoi(*(char**)p2); // atoi casts string to integer

if (n1<n2) return -1;

if (n1>n2) return 1;

}


 

(A, ... , cmp)

//int cmp(const void *p1, const void *p2)

//{int n1 =

int n2 =

if(n1<n2) return -1;

if(n1>n2) return 1;

return 0;


 


 

c struct

  • struct point {int x, int y};
    • point is the structure tag

CSE2011 Lecture 8

Loop invariants

  • What is the loop invariant
    • In general it is an extremely difficult question to answer. It contains the essential difficulty in programming
    • Fundamentally it is the following
      • LI = totalWork = workToDo + workDone
    • Question a: does the loop terminate?
    • Question b: is the postcondition of OP true at loop end

Loop Design

  • Find the loop invariant
  • After consulting an oracle we have determined that the following is an appropriate loop invariant
    • This is the create part of programming
  • Question 1
    • Make the loop invariant true at the start
  • Question 2
    • Is the loop invariant still true after operation 2 is executed?
    • After operation2 show li first part is true
    • See effect of moving data from workToDo to workDone while maintaining the invariant

EATS1011 Lecture 8

Clouds

  • Clouds to fall but then they fall into warmer air and evaporate
  • CCN: 100%
    • Cloud condensation Nuclei (CCN)
  • Newton's first law
    • The droplet of radius r
    • The droplet's going down
    • And friction of particles in the air
    • Eventually balance out
    • Friction force
      • 6πR(eta) V
        • Eta is viscosity (missing symbol)
    • Gravitational force
      • M*g
        • M ass of the droplet
        • G ravity
        • = 4/3πR3
    • These two forces equal each other out
    • Get formulas from website
    • This only applies to 'small' droples (< 100microns)
    • Terminal Velocity




    • VT = 6x103 R(m) m/s (R> 100 mm)
  • Condenstation -> growth
    • 1/R
  • 1) collision and coalescence
    • Warm
  • 2) bergeon process
    • Mixed phase clouds
      • (liquid water + ice)
    • The difference in vapour pressure drives the growth of the droplets
  • Size spectrum
    • 1 micron -> 5 microns -> 10 microns – 15 microns – 50 microns
    • The small ones fall slower than the large ones
    • The large one sweep up the smaller ones under them
      • Until the droplet gets even bigger and falls faster
      • If there are enough small particles you can see how we get very large droplets

Thursday, January 24, 2008

CSE 2031 Lecture 6

Arrays and pointers

  • An array name by itself is
    • An address
    • A pointer value
  • A pointer is
    • A variable taking addresses as values
  • An array name is
    • A particular fixed address
    • Like a constant pointer
  • When an array is declared, the compiler allocates
    • A base address
      • The address of element 0
  • And sufficient memory allocation for the rest of the elements

Array indexing and pointer arithmetic

#define MAXSIZE 1024

int A[MAXSIZE], *p;

/*

*space allocated for A

* but p – has not been given a value , even if it did here wouldn't necessarily be any space allocated *where it pointed

*/

Equivalent Statements

  • P = A;
  • P = A+I;
  • P = &A[0];
  • P=&A[i];
  • P[0]
    • is the same as saying *p
  • p[3]
    • is the same as saying *(p+3)

Summing the Array

  • 4 forms
  • 1

    sum =0;

    int i;

    for (i=0; i<maxSize; i++)

    sum += A[i];


     

  • 2

sum = 0;

for(p=A; p<&A[MAXSIZE];p++)

sum+= *p;

  • 3

sum = 0;

For(i=0;i<MAXSIZE;i++

sum += *(A+i);

  • 4

Sum = 0;

P=A;

For(i=0 i<MAXSIZE;i++)

Sum += p[i]; /*no dereferencing*/

  • Practice adding pointers and casting them
  • When you minus the two you get how many blocks of allocated memory exist between them
  • If you cast them and minus them you get the mem address casted to ints then you get the difference between that

Arrays as function parameters

  • In a function header
    • An array isn't declared w/ a fixed size in a function header
    • Int A[] is equivalent to int *A
      • This ONLY applies to a function parameter
    • Otherwise Int A[] is is NOT equivalent to int *A
      • Int *A; creates a pointer variable
      • Int A[] creates a constant pointer and no storage

Pointers and strings

  • Strings are arrays of char and are ended with \0
    • \0 is a null character
  • "ABC"
    • Type is char*
    • Value is address of the 'A'
  • Char word[] = "xyz"
    • Is the same as char word[] = {'x','y','z','\0'};
  • Char *p = "xyz";
    • Word is an array of length 4.
    • P is a pointer and points (for now) to an array with 4 elements
    • P can change reference
    • *p doesn't allocate new space

Dynamic Memory Allocation

  • Memory allocated while the program is running
  • Stack
    • When there is a function call there are parameters and local variables
    • Space set aside to hold the values for returns when functions are called
      • Stacks grow during recursion
      • Goes from the top down
      • LIFO
    • A stack grows and shrinks automatically
  • Heap
    • Declares space and the space remains allocated

Malloc

  • Void *malloc ( size_T n) /* memory allocation*/
    • Returns pointer to n bytes
    • Parameter is an integer type
      • Signed or unsigned
    • Sets aside an amount of space
    • Set aside contiguously , like an array
    • What is returned is a pointer to the space allocated
    • If space cannot be allocated a null pointer is returned
    • The storage is uninitialized
      • Not necessarily emptied space
    • Returns NULL if it can't be done
  • Void *calloc (size_t n, size_t element_size)
    • Allocate enough space for this many elements that take 'so much space'

Algorithm assessment

  • Is the algorithm running in constant time?
    • Runs the same amount of time no matter when 'n' is
    • O(1)
      • No loops or constant time loops
  • Linear time
    • Does the problem run exactly proportional to the size of 'n'?
    • Dominant single loop dependant linearly on n
  • Logarithmic
    • The algorithm divides the size of the problem by a constant
      • Runs in O(log n)
        • Dominant single lop is a divide by 2 on each iteration

Assertions

  • Boolean expressions or predicates that evaluate to true or false
  • In a program they express constraints on the state that must be true at that point
  • Associate with
    • Individual program statements
    • Functions
    • Classes
  • Specify clearly, precisely and succinctly
    • What is expected and guaranteed by each component
      • Class function and statement
    • The essence of documentation
    • Essential for debugging
    • Aids in fault tolerance
  • Result
    • Result of a query but only in ensure assertions
  • Current
    • @ Current object
  • Void
    • Not attached
  • Name
    • Value of the variable name before a routine starts
  • Name'
    • Value of the name after a routine terminates
    • Alternate name 'old name' instead of Name'
  • **study textual notation**
    • From online notes, cannot type all this

Tuesday, January 22, 2008

CSE 2031 Lecture 5

void makeDouble(int* x)

{

    *x = 2* *x;

}


 

* modifies a pointer

This in English is makeDouble takes an integers pointer

Then the integers pointer is modified.

An '&' sign is a pointer. int I, *p; /* means that there is an integer I and an integer memory reference *p;

An expression has a type and value.

*(r=&j) *= *p

**p dereferences p


 

Pointer to void

  • Why do pointers have types?
    • So we can dereference them