C Programming and Prolog Test Summary

Imperative Procedural Language

·         Comparison C to Java:

http://introcs.cs.princeton.edu/java/faq/c2java.html

Introduction

•          Program file structure

–        #include <>  or “ “

–        Main function

•          Variables

–        int, float, char

–        unsigned keyword

–        No String type: String defined as char array : char name[26]  or char * name - see later notes

–        For bool, include stdbool.h

–        Constant:

•          #define name value

•          const type  name = value

–        Get address of variable with &

–        Cast with (type) var

•          Read from screen and print to screen

–        Scanf (control string, variable addresses)

–        Printf(string, variables to insert)

–        Format strings %2f, %d, %s

–        #include <stdio.h>

•          Decisions

–        If / else if / else

–        switch

•          Loops

–        For

•          counter must be created before loop starts)

–        While

–        Do while

Functions

•       Create a function

–      <return type> <function name> (<type> <var> …)

•       Call a function (can call it recursively)

–      <function name> (<var>…) 

–      Use math functions - #include "math.h"; call without Math.

•       Pass by reference

–      Argument accepts address: *<var name>

–      Caller sends address: &<var name>

•       Variable life

–      Local vs global

•       Random – 

–      Seed with srand(time(NULL)); means you need to #include <time.h>

–      rand() % choices and maybe add 1 - ex: rand() % 9 gives 0-8.

•        

Arrays:

•       Define an array single or multi subscript

•       Access an array element

•       Pass an array as a function – by reference

•       Get an array size

•       Special character array

•       Static keyword for array

Pointer and Dynamic Array Summary:

·         General:

o   A pointer variable holds an address.

o   A pointer variable that points to a pointer variable holds an address that in turn points to an address.

o   A Multi-dimensional array variable is a pointer to a pointer, because each row is referred to by a pointer.

o   Print addresses with %p format character.

·         Declare a pointer:

o   Read backwards:  double * p means: p is a pointer to a double

o   Not dynamic:  point to a variable that was created with a normal <type> <variable name> declaration

§  double x

§  double * p = &x

o   Dynamic:

§  Create a pointer with a null value, and then assign a block of memory using malloc in the heap and then store the starting address in your pointer:

·         double * p1;

·         p1 = (double *) malloc(sizeof(int));

o   (note cast of void pointer malloc returns to the type of pointer you want.)

o   If malloc returns NULL, no memory was assigned. - You must check

§  When you are done using memory you grabbed with malloc, you must free it.

·         free(p1);

§  Set pointer to NULL when it point to nothing: p2 = NULL;

·         Use a pointer:

o   Use the address: Just the variable name : ptr

o   Set pointers to either the value of another pointer (such as an array) or the address of another variable (any type, even a pointer).

o   Use the value at the address: deference the pointer : *ptr

o   Get the address of another variable: &varname 

o   Remember that the array variable is a pointer, and the cells inside the array are not (unless you declare an array of pointers).

o   You cannot dereference a value variable : cannot int x  and then *x = 6

o   Know whether you are dealing with a pointer or a value variable, and be able to set address or value as appropriate for the problem you are solving

§  Ex: scanf does not need the & for a pointer

§  Ex: printf does need a * for a pointer when not using %p so the pointed at value can print

·         Pass to functions:

o   Passing a pointer is called passing by reference

o   Nothing in C passes by reference without you insisting that a pointer be passed (except you can say arrays naturally pass by pointer because arrays are pointers).

·         Pointers and arrays

o   An array variable is a pointer, but it also knows the full size of the array

o   Making a pointer to an array (such as when you pass an argument to a function) only knows the size of the pointer and the address of the first element of the array.

o   Pointers to arrays can use pointer arithmetic, moving through elements by adding 1.

o   A dynamic array is created by using malloc to allocate the memory for the array, and then putting the address malloc returns into a pointer.

o   For multidimensional dynamic arrays, malloc the memory for the array of pointer to each row, and then malloc each row. Remember to free all that you create.

o   Malloc many characters: int *ptr = malloc(sizeof(int) * 10);  

o   Malloc is part of stdlib.h

 

Typedef:

·         Like creating a variable type name, but really just substitute words

o   Ex:

§  In heading of program: typdef int * IntPtr

§  Later use: IntPtr x

§  Means: int * x

String Handling

String is an Array ending in NULL - ‘\0’

string.h and stdlib.h;  - string functions

ctype.h; - character functions

Initialize using array or pointer notation:

·         char *s = "abc";

·         char       yourString[11] = "Do Be Do";

·         char       myString[] = "Do Be Do";

Copying strings:

·         char s[20]  -- means you created an array and allocated space for 19 char + 1 NULL

§  then Not: s = “Hello”  later

§  Instead, strcpy or strncpy or sprintf

·         char *  s  -- means you created a pointer  that can be pointed to a char array - no space!

§  then  later  s = “Hello” 

§  Before anything other attempt to point to a string, either malloc or point to a char array.

·         (char * )    (malloc(sizeof(char) * 30));

Comparing strings:

·         Not s1 == s2

·         Instead strcmp or strncmp ; 0 = equal;

Length:

·         strlen – up to first null

·         printf: remember %s prints the string up to the null; watch nulls inside strings or missing null at end of string

Extract parts  from string: sscanf

sscanf(pointer to a string, format string in double quotes, one variable address for each % in the format string);

ex: sscanf(mystr, "%d-%d",&x,&y)  MEANS:   if mystr contains 1-2 this sscanf will put 1 into x and 2 into y

Create a string using : sprintf

sprintf (pointer to a string, format string in double quotes, one variable  for each % in the format string);

ex: sprintf(mystr, "%d-%d"x,y)  MEANS:   if x = 1 and y = 2, this sprintf will put "1-2" into mystr

 

Convert string to number:

·         atoi – returns an integer stopping at the first non digit

·         strtod, strtol,strtoul – send both a pointer to the string and a pointer to a pointer to a string. It returns a pointer to the unconverted portion of first string.

Command line arguments: character array, with 0 as program path

Read String from Standard Input:

·         getchar: get characters one at a time  until equal EOF integer (waits for Enter)

·         fgets: read one string from input, up to newline character, appending NULL

·         scanf: remember “%19s” to not get to limit input, and you place the NULL

·         scanf_s: safer, pass the length

Write string to Output:

·         putchar to put a single character and

·         puts to print one unformatted string

·         printf – formatted output

 Structures:

What is a structure:

·         Data type you create with parts

·         Can contain an array / Can be contained by an array

·         Passes by value unless explicitly by pointer

Defining a struct:

·         struct workerstuff {                int rate, hours, gross;} ;

·         Use Typedef

o   just the tag: typedef struct workerstuff Worker;

o   the entire structure typedef struct  { int rate, hours, gross;} Worker ;

Declaration

·         single struct variable

o   option 1 with combined def : struct workerstuff { int rate, hours, gross;}  worker;

o   option 2 referencing earlier definition: struct workerstuff  worker;

o   If typedef used: Worker worker;

·         Array of a structure

o   struct workerstuff  workerArr[];

·         Pointer to a structure

o   struct workerstuff  * workerPtr;

Access variable:

·         single struct variable – dot :  worker.rate;

·         Array of a structure - Access via dot and subscript:  WorkerArr[1].rate

·         Pointer to a structure - Access via arrow :   workerPtr->rate or (*workerPtr).rate

 

PROLOG: for the C Programming Test

Declarative Logic Programming

 

Facts: made of functors and arguments in the form of functor(argument 1 ,argument 2 ,argument 3).

·         ex: loves(Vincent,mia).

 

Rule: a rule consisting of a head and body, separated by :- . When the body is true, the rule is true. (When working with variables in your query, the unification that causes the body to be true means that the head is true.)

·         ex: jealous(X,Y):- loves(X,Z), loves (Y,Z).

·         Implementing an OR rule:  make two independent rules

·         Implementing and AND rule: make one rule, and put a comma between the two facts that must be true.

Variable: any uppercase Atom

·         Unification fills the variable values.

 

Query: A statement that asks which values would make the statement true.

·         Execute a query inside the prolog session. 

o   Load the rules and facts from the prolog fact and table file. ex: [pl1].

o   Type your query 

§  Syntax: functor (arguments). ex: isHorizontal(Ax,Ay,Bx,By). or woman(mia).

o   See true or false answer along with the value of any variables in your query

o   Type semi-colon after a valid answer to get another true answer or be told no more true answers.

·         Unification to solve a query:

o   Unifies by matching functor(arguments..) to  facts and rule headers. Matching to a rule header requires matching the rule body entirely.

o   Unifying a variable (uppercase start) to a fact or rule causes instantiation of the variable.

o   Unifying a query with only one variable:

§  Attempts to unify to a fact or rule header in your knowledgebase.

§  Prolog Progresses through lines matching the query to each fact or rule header in the knowledgebase, branching out to see whether a rule is true.  

o   Unifying a query with multiple variables: Unification creeps one variable at a time, and using one variable instantiation to move forward to the next variable. When it goes down a path that cannot bind, it unwinds to try to unify with another variable value.

 

Atom:  building block of prolog facts, queries and rules. A string that cannot be divided into parts and beginning with a lower case letter or an operator such as :- or  =

 

Arity: how many arguments (Arity counts in unification).

Unification:

 

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

NOTHING BELOW HERE WILL BE ON THE C PROGRAMMING TEST, THOUGH IT WILL BE ON THE C++ PROGRAMMING TEST:

 

Union

·         Definition by choices, not parts

·         Takes on the size of the largest possible choice

·         Definition:  union number {int x; int * p;};

·         Declaration and use have the same syntax as structure.

Enum:

·         Naming constants, integer underlies it

·         Use it to create a variable with only those possible choices

·         Definition: enum days { SUN, MON, TUE, WED, THUR, FRI, SAT};

·         Declaration: enum days day;

·         Use: day = SUN;

Buffered File I/O :

Specifier format:  %w.pt (width, precision, data type)

Specifier types:

d, i                          integer in decimal format

o                                             integer in octal format

x                                              integer in hexadecimal format

u                                             unsigned integer in decimal format

c                                             integer in character format

s                                              char *; prints all characters until the '\0'

f                                              double [-]m.dddddd – by default 6 decimal places

e, E                         double [-]m.dddddde±xx or mddddddE±xx

g, G                        double; uses (e, E) if exponent is less than -4 or greater than or equal to precision; otherwise uses f format.

scanf  also uses set [ ] or everything but the set with [^ ].

File Pointer creation: File *fp

File opening modes: r, w, a, rb, wb, ab (b = binary) (r  = read; w = write; a = append)

Open command: fopen(filename, opening mode);

·         returns a pointer to the file or NULL if cannot open

·         Sample:                FILE *ifp

if ((ifp = fopen(ifilename, "r")) == NULL)             {
                                fprintf(stderr, "Cannot open %s\n", ifilename); }

Close command: fclose(fp);

 

Text File read / write commands:

 

Direction

Screen interaction

File interaction

Response

Purpose

write

putchar(c);

putc(fp, c);

returns the character written (as an int); On error returns EOF (defined in stdio.h as -1)

write one character at a time

read

getchar();

getc(fp);

returns the character read (as an int);

On error returns EOF (defined in stdio.h as -1)

read one character at a time

write

printf("…", …);

fprintf(fp, "…", …);

returns the number of characters written. On error returns a negative number that indicates the particular error

write string formatted by first parm with one variable per %

read

scanf("…", …);

fscanf(fp, "…", …);

returns the number of variables parsed;

on error returns EOF (defined in stdio.h as -1)

read input string parsed by first parm with one variable per %

write

puts(s);

fputs(fp, s);

on error returns EOF (defined in stdio.h as -1)

write a string and append new line character automatically.

read

gets(s); (NOT RECOMMENDED)

fgets(fp, s)

returns a pointer to s. On error returns a  NULL pointer

read a string up to the new line. gets does not store the new line character in the buffer and fgets does.  Parameter s must have memory allocated.

 

 

Fixed file layout read / write commands:

 

     Binary file is not usually human readable. It often contains fixed record layouts.

 

Direc-tion

 Func-tion

parameters

Sample

Response

Purpose

read

fread

pointer to read buffer var, object size, # objects, file pointer

fread(&person, sizeof(person), 1, ifp)

returns the number of items read as a size_t object.  If less than 3rd  parm returned, consider it an error.  On Error or end of file, returns 0. To determine if EOF, must follow with feof using feof(file pointer).

read one structure of variable at file read offset. (can read array as well)

write

fwrite

pointer to write buffer var, object size, # objects, file pointer

fwrite(&person, sizeof(person), 1, ofp)

 

returns the number of items  written as a size_t object.  If less than 3rd  parm returned, consider it an error.   Find error using ferror(file pointer), and if it is true,  use perror ( ) to print the error.

write one structure or variable at file write offset. (can write array as well)