C1320prespost
Upcoming SlideShare
Loading in...5
×
 

C1320prespost

on

  • 423 views

 

Statistics

Views

Total Views
423
Views on SlideShare
423
Embed Views
0

Actions

Likes
0
Downloads
5
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

C1320prespost C1320prespost Presentation Transcript

  • Sticky Bits in C
    • Diverse topics of interest and confusion to new users of the C programming language
    • Topics include:
    • Control structures
    • Variable types
    • Pointers!
    • Arrays and structs
    • Linked lists
    • Recursion
    • Debugging
  • Sticky Bits in C Control Structures
  • Control Structures
    • Sequential
      • Assignment statements
    • Selection
      • if / if else
      • switch
    • Test determines execution of clause
    • Else condition or default case used for execution only on test failure
    • No guaranteed execution of clause following ‘if’ or switch
    • Iteration (Repetition)
      • for
      • while / do while
    • Loop conditions at end or beginning of iteration
    • Index can control the number of iterations
    • No minimum number of iterations
    • Recursion is a form of iteration
  • Sticky Bits in C Variable Types And Pointers!
  • Data Types
    • Variables hold values
    • Integer types
      • long int (or long)
      • int
      • short int (or short)
      • char (itty-bitty integer)
    • Floating point types
      • long double
      • double
      • float
    • Pointer variables hold addresses
    • Pointers have a base type of any legal C type including another pointer. Examples:
      • long * (pointer-to-long-int)
      • float * (pointer-to-float)
      • int ** (ptr-to-ptr-to-int)
      • char * (ptr-to-char / string)
      • double ***** (ptr-to-ptr-to- ptr-to-ptr-to-ptr-to-double)
      • You get the idea
  • Pointer Variable Notes
    • How To
    • Declare a pointer variable:
    • int *ptrnum;
    • Assign an address to a pointer variable:
    • ptrnum = #
    • Retrieve the value in the address that a pointer points to (and saving it):
    • othernum = *ptrnum;
    • The asterisk *
      • Dereferencing operator
      • Defines a pointer type in a declaration, e.g. int *
      • Dereferences a pointer vairable to get the contents at the address pointed to, when used in a statement, e.g. = *ptrnum
    • The ampersand &
      • Addressing operator
      • Retrieves the address of a variable, e.g. &othernum
  • Using Pointers to Allocate Space
    • The computer gives your program memory when you declare variables.
    • YOU can give your program more memory by using pointer variables!
    • You can request additional memory space by using malloc or calloc with a pointer variable
    • int *tenspaces; /* this is just the pointer, not the actual spaces */
    • tenspaces = (int *) malloc ( 10 * sizeof (int) );
    • /* cast to int *, the address of 10 integer sized memory locations */
    • /* Now you can put stuff in those spaces */
    • tenspaces[0] = 42;
    • *(tenspaces + 1) = 1024;
    • for (i=2, i < 10, i++)
    • tenspaces[i] = i;
  • Sticky Bits in C Recursion Recursion Recursion Recursion Recursion Recursio Recurs
  • Recursion Development
    • “ Recursive functions typically implement recurrence relations which are mathematical formula in which the desired expression (function) involving a positive integer, n , is described in terms of the function applied to corresponding values for integers less than n .” Foster & Foster, C by Discovery
      • The function written in terms of itself is a recursive case
      • The recursive case must call the function with a decreasing n
    • Initial conditions or starting values for the function must also be given. This is used as the termination condition for the recursive function.
      • The function with a defined output value for a specific input is a base case
  • Recursion - Example
    • Fibonacci Sequence
    • 1, 1, 2, 3, 5, 8, 13, 21, …
    • 1 st 2 nd 3 rd 4 th 5 th 6 th 7 th 8 th
      • Let us call the 1st Fibonacci number, Fib(1), the 2nd Fib(2)… This gives us n .
      • Fib(1) = 1 defined base case
      • Fib(2) = 1 defined base case
      • Fib(3) = 2 = 1 + 1
          • = Fib(2) + Fib(1)
      • Fib(7) = 13 = 8 + 5
          • = Fib(6) + Fib(5)
    • Fib( n ) = Fib( n -1) + Fib( n -2)
    • Fibonacci Algorithm using Recursion
      • int Fib (int n)
      • {
      • int temp = 1; /* handles base cases */
      • if ( n > 2)
      • temp = Fib ( n -1) + Fib ( n -2);
      • return temp;
      • }
    It should be noted that one of the most difficult things about recursion with Fibonacci is the magical decision to number the Fibonacci elements and then to use that number as n . This is akin to mathematical proofs where the author says “So now we let k stand for a+*m%r#p^t …”
  • Recursion - What is it doing!?@#!
      • int FibCaller(void)
      • {
      • int fibval= 5 ;
      • if (fibval > 0)
      • fibval = Fib (fibval);
      • }
      • int Fib (int n)
      • { /* handles base cases of */
      • /* Fib(1) and Fib(2) */
      • int temp = 1 ;
      • if ( n > 2) /* other cases */
      • temp = Fib ( n -1) + Fib ( n -2);
      • return temp;
      • }
    Fib(5) = 5 Fib(4) = 3 Fib(3) = 2 Fib(3) = 2 Fib(2) = 1 Fib(2) = 1 Fib(1) = 1 Fib(2) = 1 Fib(1) = 1 = + + + + = = = 2 2 5 3 Notice that the recursion isn’t finished at the bottom -- It must unwind all the way back to the top in order to be done.
  • Recursion - Should I or Shouldn’t I?
    • Pros
      • Recursion is a natural fit for some types of problems
    • Cons
      • Recursive programs typically use a large amount of computer memory and the greater the recursion, the more memory used
      • Recursive programs can be confusing to develop and extremely complicated to debug
  • Sticky Bits in C Arrays and Structs
  • Aggregate Data Structures
    • Array s combine many pieces of data into one structure which is easy to access.
      • All of the data elements in an array must be of the same type
    • Struct s combine many pieces of data into a single data type
      • The data elements of the struct can be of different types
      • Data elements are accessed by variable name and selected by member name
  • Aggregate Data Types - Structures
    • Hold multiple data values
    • Group multiple data types
    • Ex: UTA student data
      • Student ID number
      • Last name
      • First name
      • GPA
      • Major
    • Structure - keyword struct
    • Defines an aggregate type & member subcomponents
    • struct uta_student {
    • unsigned ID_num;
    • char *last_name,
    • *first_name;
    • float GPA;
    • char major[4] = {‘U’,’N’,’D’,’E’};
    • };
  • Structure Operations and Member Accessing
    • To access a component of a structure, a variable (for ex. stdt_1 ) of the struct type must be declared. Then the components of that variable are accessed with the selector (.) construct.
    • The ANSI standard operations that work on structures are:
      • Select members
      • Assign the contents of one structure variable to another
      • Address ( & ) structure variables
      • Sizeof() structure variables
    • /* variable declaration */
    • struct uta_student
    • stdt_1, stdt_2, *stdt_ptr;
    • stdt_1 .ID_num = 608469999;
    • stdt_1 .last_name = “Smith”;
    • stdt_1 .first_name = “Snuffy”;
    • stdt_1 .GPA = 2.15;
    • stdt_2 = stdt_1; /* struct assignment */
    • stdt_ptr = & stdt_2; /* struct pointer */
    • int stdt_size= sizeof (struct uta_student);
  • Arrays and Pointers and Structures Oh My!
    • An array of structures means that each element of the array is an entire structure. Ex:
    • struct uta_student cse1320[3];
    • cse1320 points to head of the array
    • cse1320[2] is the third structure (element) in the array
    • cse1320[2].ID_num is the id_num member of the third structure
    • cse1320[2].major[0] is the first letter of the major
    • A pointer to a structure is typically used when structures are allocated dynamically such as in a linked list. Structures may also contain pointers as structure members.
    • struct uta_student *new_stdt;
    • new_stdt can hold the address of a uta_student structure
    • (*new_stdt).ID_num or new_stdt->ID_num is the id_num for the struct the new_stdt points to
    H E T D S A E C M 3.95 Imad Tibi 744521111 E 4.0 Rose Axel 000003789 P 3.4 Marta Luitania 654903211 major[4] GPA first_nm last_nm ID_num
  • Sticky Bits in C Linked Lists
  • Data Structures built with Structs
    • Multi-element storage structures are created from individual structs
    • Each struct must be able to point to another struct of the same type
    • struct uta_student {
    • unsigned ID_num;
    • char *last_name,
    • *first_name;
    • float GPA;
    • char major[4];
    • struct uta_student *next_stdt;
    • };
    • The most common structure then is a linked list in which each element of the list is a struct which has at least one pointer linking it to another struct in the same list.
    UTA UTA UTA UTA ->next_stdt ->next_stdt ->next_stdt
  • Linked Lists
    • A linked list is a good data structure to use when the amount of data to be stored is unknown or can fluctuate.
    • Building a simple unsorted singly-linked list requires at least:
      • Dynamic memory allocation to a struct pointer for each new element (or ‘node’) to be added to the list
      • A pointer to the head of the list
      • A pointer that can travel through the list elements
    UTA UTA UTA ->next_stdt ->next_stdt ->next_stdt head travel UTA new UTA
  • Linked Lists
    • A singly-linked list is built by making a loop that
      • Allocates a new list element and puts the new data in it (from a file or from the user, etc.),
      • Determines where in the list the new element should go [beginning (head), middle or end of the list], then
      • Adds the new element to the list
    UTA pi A list element might consist of a uta_student struct with a last_name value of pi along with other member values UTA UTA UTA UTA ->next_stdt ->next_stdt ->next_stdt head travel UTA new alpha phi nu tau zeta
  • Linking the List
    • A singly-linked list is built by making a loop that
      • Allocates a new list element and puts the new data in it (from a file or from the user, etc.),
      • Determines where in the list the new element should go [beginning (head), middle or end of the list], then
      • Adds the new element to the list
    • Allocating a new struct in C means using malloc or calloc to create space and assign it to a pointer variable. Then values would be assigned to the members of the struct. Ex:
    new = (struct uta_student *)malloc (sizeof (struct uta_student)); new->last_name = “pi”; /* other data initialized */ (*new).next_stdt = NULL;
  • Linking the List
    • A singly-linked list is built by making a loop that
      • Allocates a new list element and puts the new data in it (from a file or from the user, etc.),
      • Determines where in the list the new element should go [beginning (head), middle or end of the list], then
      • Adds the new element to the list
    • Determining where the new element should go is either
    • a) defined for the list, e.g. all new elements go at the head of the list , or
    • b) it is determined by some kind of test or comparison to each element in the list.
    • The travel pointer moves through the list pointing to each element in turn. Ex:
    /* in some sort of loop */ if ( new->last_name < travel->last_name) /* then new goes in the list before travel */ else travel = travel->next_stdt; UTA UTA UTA UTA ->next_stdt ->next_stdt ->next_stdt head travel alpha UTA new phi nu tau zeta
  • Linking the List
    • A singly-linked list is built by making a loop that
      • Allocates a new list element and puts the new data in it (from a file or from the user, etc.),
      • Determines where in the list the new element should go [beginning (head), middle or end of the list], then
      • Adds the new element to the list
    • Adding an element to the list means hooking up the pointers correctly. To put an element in the middle of a singly-linked list takes the most steps. Ex:
    /* using the travel pointer and a follow pointer which is one link behind the travel pointer */ if ( new->last_name < travel->last_name) { /* insert node */ new->next_stdt = travel; follow->next_stdt = new; }
  • Doubly Linking the List
    • All the preceding applies to singly- linked lists. In a doubly-linked list, each element has pointers to the links before it AND after it. Thus each element now contains:
    • struct uta_student {
    • unsigned ID_num;
    • char *last_name, *first_name;
    • float GPA;
    • char major[4];
    • struct uta_student *prev_stdt, *next_stdt ;
    • };
    UTA UTA UTA UTA ->next_stdt ->next_stdt ->next_stdt head travel UTA new alpha phi nu tau zeta ->prev_stdt ->prev_stdt ->prev_stdt follow
  • Doubly Linking the List if ( new->last_name < travel->last_name) { /* insert node */ new->next_stdt = travel; new->prev_stdt = follow; follow->next_stdt = new; travel->prev_stdt = new; }
    • A doubly-linked list is built by making a loop that
      • Allocates a new list element and puts the new data in it (from a file or from the user, etc.),
      • Determines where in the list the new element should go [beginning (head), middle or end of the list], then
      • Adds the new element to the list
    • Adding an element to the list means hooking up the pointers correctly. To put an element in the middle of a doubly-linked list takes the most steps.
    • Example below: /* using the travel pointer and a follow pointer which is one link behind the travel pointer */
    UTA UTA UTA ->next_stdt ->next_stdt follow travel tau ->prev_stdt ->prev_stdt new nu phi
  • Sticky Bits in C Debugging. Ugh.
    • Approaches to writing code that is easier to debug
    • Write small blocks of code , then compile them and test them before writing another block
      • Small means less than a page - half a page is better
    • When two choices exist for how to write something, choose the one that is simpler for you
      • Obviously, some assignments will require other choices but in any case, simpler to write usually means simpler to document and simpler to understand and fix if necessary
    • If you can write it without pointers it will usually be easier to debug
      • But often less efficient <there are always trade-offs>
    • Put in comments and document the code as you go
      • It reminds you why you made certain choices and it helps others who may be helping you debug.
    Debugging. Ugh.
  • Debugging. Ugh.
    • Approaches to locating a bug in a program
    • Print, print, print
      • The only way to really find out what the program does at every point
    • Comment out
      • Reduce the complexity of the program by commenting out large sections and checking bit by bit to see what works
    • Insert early returns
      • Execute smaller parts of the code. If it works, move the ‘return’ further along. If not, you have more closely isolated the problem.
    • Arm yourself with info
      • When asking for help, provide as much info as possible to the person who is helping
    • What could it mean when it…
    • Gives segmentation fault?
      • Pointer problems - almost always you are trying to access outside your program space or access non-existent space
      • NOTE: Segmentation faults can “eat” the output in the output queue so sometimes you may be trying to print info to locate the fault but the info doesn’t get to the screen because of the fault. 
    • Won’t run my function?
      • Probably doesn’t really get to the function call at all. Check what is happening in the calling routine.
    • Won’t print the data I read in?
      • Maybe it didn’t really read it in at all - have you checked the input function?
    Debugging. Ugh.