F28PL1 Programming Languages Lecture 5: Programming in C 5.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Pointers.
Question Bank. Explain the syntax of if else statement? Define Union Define global and local variables with example Concept of recursion with example.
Elementary Data Structures: Part 2: Strings, 2D Arrays, Graphs
1 Compiler Construction Intermediate Code Generation.
Computer Science C++ High School Level By Guillermo Moreno.
F28PL1 Programming Languages Lecture 8 Programming in C - 3.
R-1 University of Washington Computer Programming I Lecture 17: Multidimensional Arrays © 2000 UW CSE.
Introduction of Arrays. Arrays Array form an important part of almost all programming language. It provides a powerful feature and can be used as such.
Arrays and Pointers in C Alan L. Cox
Command line arguments. – main can take two arguments conventionally called argc and argv. – Information regarding command line arguments are passed to.
F28PL1 Programming Languages Lecture 9 Programming in C - 4.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
F28PL1 Programming Languages Lecture 10: Programming in C 5.
Review C++ exception handling mechanism Try-throw-catch block How does it work What is exception specification? What if a exception is not caught?
F28PL1 Programming Languages Lecture 7 Programming in C - 2.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
A.Abhari CPS1251 Multidimensional Arrays Multidimensional array is the array with two or more dimensions. For example: char box [3] [3] defines a two-dimensional.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
Dynamic Memory Allocation Conventional array and other data declarations An incorrect attempt to size memory dynamically Requirement for dynamic allocation.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
0 Chap. 5 Pointers and Arrays 5.3Pointers and Arrays 5.4Address Arithmetic 5.5Character Pointers and Functions 5.6Pointer Arrays; Pointers to Pointers.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Array, Structure and Union
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
Addressing Modes Chapter 6 S. Dandamudi To be used with S. Dandamudi, “Introduction to Assembly Language Programming,” Second Edition, Springer,
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
POINTERS.
CSE 326: Data Structures Lecture #6 From Lists to Trees Henry Kautz Winter 2002.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
Data Structures - Part I CS 215 Lecture 7. Motivation  Real programs use abstractions like lists, trees, stacks, and queues.  The data associated with.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
Assembly - Arrays תרגול 7 מערכים.
EGR 115 Introduction to Computing for Engineers MATLAB Basics 1: Variables & Arrays Wednesday 03 Sept 2014 EGR 115 Introduction to Computing for Engineers.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
F28HS2 Hardware-Software Interface Lecture 4: Programming in C - 4.
CS 1704 Introduction to Data Structures and Software Engineering.
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
F28HS2 Hardware-Software Interface Lecture 12: Assembly Language 6 & Summary.
ECE 103 Engineering Programming Chapter 23 Multi-Dimensional Arrays Herbert G. Mayer, PSU CS Status 6/24/2014 Initial content copied verbatim from ECE.
POINTERS IN C Pointer Basics, Pointer Arithmetic, Pointer to arrays and Pointer in functions.
MULTI-DIMENSIONAL ARRAYS 1. Multi-dimensional Arrays The types of arrays discussed so far are all linear arrays. That is, they all dealt with a single.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
1 Linked List. 2 List A list refers to a sequence of data items  Example: An array The array index is used for accessing and manipulation of array elements.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
F28HS2 Hardware-Software Interface Lecture 3 Programming in C - 3.
Computer science C programming language lesson 3.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
Windows Programming Lecture 03. Pointers and Arrays.
APS105 Malloc and 2D Arrays (text Ch6.4, Ch10.2).
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
Chapter 8 Arrays, Strings and Pointers
Lecture 7 Arrays 1. Concept of arrays Array and pointers
Lecture Trees Chapter 9 of textbook 1. Concepts of trees
Week 7 Part 2 Kyle Dewey.
Module 2 Arrays and strings – example programs.
CSCE 210 Data Structures and Algorithms
Lecture 6 C++ Programming
CS 240 – Lecture 18 Command-line Arguments, Typedef, Union, Bit Fields, Pointers to Functions.
بنام خدا زبان برنامه نویسی C (21814( Lecture 11 Pointers
CS111 Computer Programming
Binary Trees (and Big “O” notation)
C Programming Pointers
Files Chapter 8.
Presentation transcript:

F28PL1 Programming Languages Lecture 5: Programming in C 5

Macro: text substitution #define name text replace name with text throughout file text can include spaces very useful for struct types

Example: character frequency binary tree #include #define FREQ struct freq * struct freq {int ch;int count;FREQ left;FREQ right;}; FREQ fp; chcountleftright

Example: character frequency binary tree fpNULL

Example: character frequency binary tree NULL 1m fp

Example: character frequency binary tree NULL1m fp NULL 1e

Example: character frequency binary tree 1m fp NULL 1e 1s

Example: character frequency binary tree 1m fp 11 NULLe 1s 1c

Example: character frequency binary tree 1m fp 11 eNULL 1s 1c 1h

Example: character frequency binary tree FREQ newFreq(char ch) { FREQ f; f = (struct freq *) malloc(sizeof(struct freq)); f->ch = ch; f->count = 1; f->left = NULL; f->right = NULL; return f; }

Example: character frequency binary tree incFreq(int ch) { FREQ f; if(fp==NULL) { fp = newFreq(ch); return; } f = fp; while(1) if(f->ch==ch) { f->count = f->count+1; return; } else if root empty then add first node if found node then increment count

Example: character frequency binary tree if(f->ch>ch) if(f->left==NULL) { f->left = newFreq(ch); return; } else f = f->left; else if(f->right==NULL) { f->right = newFreq(ch); return; } else f = f->right; } if empty left then add new to left else try left branch if empty right then add new to right else try right branch

Example: character frequency binary tree showFreq(FREQ f) { if(f==NULL) return; showFreq(f->left); printf("%c:%d\n",f->ch,f->count); showFreq(f->right); } print left branch print character & count print right branch

Example: character frequency binary tree main(int argc,char ** argv) { int ch; FILE * fin; if((fin=fopen(argv[1],"r"))==NULL) { printf("can't open %s\n",argv[1]); exit(0); } fp = NULL; ch = getc(fin); while(ch!=EOF) { incFreq(ch); ch = getc(fin); } fclose(fin); showFreq(fp); } NB tree not balanced...

Multi-dimensional arrays type identifier[int 1 ][ int 2 ]; allocates space for int 1 rows of int 2 columns * size for type e.g int a[2][3]; a[0][0]a[0][1]a[0][2]a[1][0]a[1][1]a[1][2]

Multi-dimensional arrays allocated: – as int 1 * int 2 continuous locations for type – by row a[0][0]a[0][1]a[0][2]a[1][0]a[1][1]a[1][2] a

Multi-dimensional access in expression exp [ exp 1 ][ exp 2 ]  *( exp + (exp 1 *int 2 + exp 2 ) * size for type) i.e. start at exp and skip exp 1 rows of int 2 columns and then skip exp 2 columns e.g. a[1,1] == a+(1*3+1)*4 == 16 a[0][0]a[0][1]a[0][2]a[1][0]a[1][1]a[1][2] a

Example: Matrix multiplication integer matrices matrix held in file as: matrix1: row 1/col 1... matrix1: row 1/col n... matrix1: row m/col 1... matrix1: row m/col n

Example: Matrix multiplication use 2D array representation #include #define MAXR 1000 #define MAXC 1000 must specify maximum dimension sizes

Example: Matrix multiplication readMatrix(FILE * fin, int M[][MAXC],int m,int n) { int i,j; for(i=0;i<m;i++) for(j=0;j<n;j++) fscanf(fin,"%d",&(M[i][j])); } must specify size of column for 2D array parameter &(M[i][j]) for address of element i/j in fscanf

Example: Matrix multiplication writeMatrix(FILE * fout,int M[][MAXC],int m,int n) { int i,j; for(i=0;i<m;i++) { for(j=0;j<n;j++) fprintf(fout,"%d ",M[i][j]); putc('\n',fout); }

Example: Matrix multiplication matrixProd(int M1[][MAXC],int M2[][MAXC], int M3[][MAXC],int m,int n) { int i,j,k; for(i=0;i<m;i++) for(j=0;j<m;j++) { M3[i][j]=0; for(k=0;k<n;k++) M3[i][j] = M3[i][j]+M1[i][k]*M2[k][j]; }

Example: Matrix multiplication e.g. multiply m*n matrix by n*m matrix file holds: m n matrix 1: row 1/col 1... matrix1: row 1/col n... matrix 1: row m/col 1... matrix1: row m/col n matrix 2: row 1/col 1... matrix2: row 1/col m... matrix 2: row n/col 1... matrix2: row n/col m

Example: Matrix multiplication main(int argc,chr ** argv) { FILE * fin; int m1[MAXR][MAXC]; int m2[MAXR][MAXC]; int m3[MAXR][MAXC]; int m,n; fin = fopen(argv[1], "r"); fscanf(fin, "%d %d",&m,&n); readMatrix(fin,m1,m,n); readMatrix(fin,m2,n,m); fclose(fin); writeMatrix(stdout,m1,m,n); putchar(‘\n’); writeMatrix(stdout,m2,n,m); putchar('\n'); matrixProd(m1,m2,m3,m,n); writeMatrix(stdout,m3,m,m); }

Example: Matrix multiplication $ matrix1 m55.data

Pointers and multi-dim arrays type * name [ int ] allocates array of int pointers to type e.g. int * a[2]; must use malloc to allocate 2 nd dimension arrays in 2 nd dimension can be any sizes – need not all be same size! a[0] a[1] a[0][0]a[0][1]a[0][2]a[1][0]a[1][1]a[1][2] a

Pointers and multi-dim arrays type ** name ; allocates pointer to pointer to type must use malloc to allocate 1 st and 2 nd dimension 1 st and 2 nd dimension can be any size! can access all three forms as identifier [ exp 1 ][ exp 2 ]

Example: Matrix Multiplication 2 disadvantages of 2D array representation have to allocate worst case space use array of arrays int * makeVector(int n) { return (int *)malloc(n*sizeof(int)); } returns array of n int s

Example: Matrix Multiplication 2 int ** makeMatrix(int m,int n) { int ** newm = (int **)malloc(m*sizeof(int *)); int i; for(i=0;i<m;i++) newm[i] = makeVector(n); return newm; } returns array of m arrays of n int s

Example: Matrix Multiplication 2 in other functions, only need to change “matrix” type from [][] to ** readMatrix(FILE * fin, int ** M,int m,int n)... writeMatrix(FILE * fout,int ** M,int... matrixProd(int ** M1,int ** M2, int ** M3,int m,int n)...

Example: Matrix Multiplication 2 main(int argc,char ** argv) char ** argv; { FILE * fin; int ** m1; int ** m2; int ** m3;... m1 = makeMatrix(m,n); m2 = makeMatrix(n,m); m3 = makeMatrix(m,m);... }

Union type to construct pointers to different types union name { type 1 name 1 ;... type N name N ;}; definition union name is the name of a new type can take different types of value at different times can be: – type 1 accessed through name 1 – type 2 accessed through name 2 etc

Union type union name 1 name 2 ; declaration name 2 is a variable of type union name 1 space is allocated for the largest type I other types are aligned within this space NB no way to tell at run time which type is intended – use an explicit tag

Example: syntax tree e.g. (1+2)*(3-4) ‘*’ ‘+’‘-’ ‘I’ 1234

Example: syntax tree struct binop{struct exp * e1, struct exp * e2;}; b b.e1b.e2

Example: syntax tree union node{ int value; struct binop b; } ; node is: – leaf int value, or... – branch struct binop b value and b.e1 are same 4 bytes b b.e1b.e2 value

Example: syntax tree can’t tell what arbitrary union represents use an explicit tag field struct exp {char tag; union node n;}; tagn

Example: syntax tree tag == ‘I’ ==> leaf for integer tag == ‘ op ’ ==> branch for operator NB this is our convention – no necessary connection between tag and node contents

Example: syntax tree struct * exp e; e = (struct * exp) malloc(sizeof(struct exp)); e e->tage->n

Example: syntax tree struct * exp e; e = (struct * exp) malloc(sizeof(struct exp)); I e e->tage->n e->n.value

Example: syntax tree struct * exp e; e = (struct * exp) malloc(sizeof(struct exp)); op e e->tage->n.b

Example: syntax tree struct * exp e; e = (struct * exp) malloc(sizeof(struct exp)); op e e->tage->n.b e->n.b.e1e->n.b.e2

Example: syntax tree struct exp * newInt(int i) { struct exp * e; e = (struct exp *) malloc(sizeof(struct exp)); e->tag = 'I'; e->n.value = i; return e; }

Example: syntax tree struct exp * newBinop (char op,struct exp * e1, struct exp * e2) { struct exp * e; e = (struct exp *) malloc(sizeof(struct exp)); e->tag = op; e->n.b.e1 = e1; e->n.b.e2 = e2; return e; }

Example: syntax tree main(int argc,char ** argv) { struct exp * e; e = newBinop ('*',newBinop ('+', newInt(1), newInt(2)), newBinop ('-', newInt(3), newInt(4))); printTree(e,0); }

Example: syntax tree newBinop ('*', newBinop ('+', newInt(1), newInt(2)), newBinop ('-', newInt(3), newInt(4))); I1

Example: syntax tree newBinop ('*', newBinop ('+', newInt(1), newInt(2)), newBinop ('-', newInt(3), newInt(4))); I1 I 2

Example: syntax tree newBinop ('*', newBinop ('+', newInt(1), newInt(2)), newBinop ('-', newInt(3), newInt(4))); + I I 1 2

Example: syntax tree newBinop ('*', newBinop ('+', newInt(1), newInt(2)), newBinop ('-', newInt(3), newInt(4))); +- I I I I

Example: syntax tree newBinop ('*', newBinop ('+', newInt(1), newInt(2)), newBinop ('-', newInt(3), newInt(4))); * +- I I I I

Example: syntax tree display tree left to right like a folder tree keep track of node depth at each node – depth spaces – print tag – print left node at depth+1 – print right node at depth+1

Example: syntax tree printTree(struct exp * e, int depth) { int i; for(i=0;i<depth;i++)printf(" "); switch(e->tag) { case 'I': printf("%d\n",e->n.value); return; default: printf("%c\n",e->tag); printTree(e->n.b.e1,depth+1); printTree(e->n.b.e2,depth+1); }

Example: syntax tree $ exp *

Pointers to functions functions are code sequences in memory – so functions have memory addresses function name is an alias for the address #include sq(int x){ return x*x; } main(){ printf("sq: %d, &sq: %d\n",sq,&sq); }  sq: , &sq:

Pointers to functions type (* name )() name is a pointer to function that returns a type main() { int (*f)(); f = sq; printf("%d\n",f(3)); }  9

Higher Order Functions function that takes another function as argument e.g. map: apply arbitrary function to all elements of array map(int (*f)(),int * a,int n) { int i; for(i=0;i<n;i++) a[i] = f(a[i]); }

Higher Order Function #include #define MAX 5 inc(int x){ return x+1; } twice(int x){ return 2*x; } show(int * a,int n) { int i; for(i=0;i<n;i++) printf("%d ",a[i]); printf("\n"); } main() { int a[MAX]; int i; for(i=0;i<MAX;i++)a[i] = i; show(a,5); map(inc,a,5); show(a,5); map(twice,a,5); show(a,5) } 

Higher Order Function HOFs basis of algorithmic skeletons for parallelism e.g. for map, can run each f on a separate processor on one array element at same time basis of Google map-reduce for filtering www searches – on farms of hundreds of thousands of core – map to search lots of different subsets of www – reduce to find common/most frequent hits