F28PL1 Programming Languages Lecture 8 Programming in C - 3.

Slides:



Advertisements
Similar presentations
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Advertisements

C Language.
Lectures 10 & 11.
Computer Programming w/ Eng. Applications
Programming and Data Structure
Programming Languages and Paradigms The C Programming Language.
Single Variable and a Lot of Variables The declaration int k; float f; reserve one single integer variable called k and one single floating point variable.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 7: User-Defined Functions II
Chapter 7:: Data Types Programming Language Pragmatics
CSCI 171 Presentation 11 Pointers. Pointer Basics.
F28PL1 Programming Languages Lecture 6: Programming in C - 1.
Basic Elements of C++ Chapter 2.
F28PL1 Programming Languages Lecture 9 Programming in C - 4.
ARRAYS In this Lecture, we will try to develop understanding of some of the relatively complex concepts. The following are explained in this lecture with.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
F28PL1 Programming Languages Lecture 10: Programming in C 5.
F28PL1 Programming Languages Lecture 7 Programming in C - 2.
Values, variables and types © Allan C. Milne v
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Programming I Introduction Introduction The only way to learn a new programming language is by writing programs in it. The first program to.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CSC 2400 Computer Systems I Lecture 5 Pointers and Arrays.
Spring 2005, Gülcihan Özdemir Dağ Lecture 7, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 7 Outline 7. 1.
CSci 125 Lecture 21 Martin van Bommel. Memory Allocation Variable declarations cause compiler to reserve memory to hold values - allocation Global variables.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
DATA TYPE AND DISPLAY Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Pointers *, &, array similarities, functions, sizeof.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
F28HS2 Hardware-Software Interface Lecture 4: Programming in C - 4.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
F28HS2 Hardware-Software Interface Lecture 6 - Programming in C 6.
F28HS2 Hardware-Software Interface Lecture 12: Assembly Language 6 & Summary.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
F28PL1 Programming Languages Lecture 5: Programming in C 5.
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
© Janice Regan, CMPT 128, January CMPT 128: Introduction to Computing Science for Engineering Students Introduction to Arrays.
Pointers A pointer type variable holds the address of a data object or a function. A pointer can refer to an object of any one data type; it cannot refer.
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.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
F28HS2 Hardware-Software Interface Lecture 3 Programming in C - 3.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
1 Compiler Construction Run-time Environments,. 2 Run-Time Environments (Chapter 7) Continued: Access to No-local Names.
Java Programming Language Lecture27- An Introduction.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
Topic 5 Addresses, Pointers and Arrays. 2 Objectives (Textbook Chapter 14) You should be able to describe: Addresses and Pointers Pointer Operators Pointer.
Stack and Heap Memory Stack resident variables include:
Chapter 8 Arrays, Strings and Pointers
Computer Science 210 Computer Organization
CSE 374 Programming Concepts & Tools
ECE Application Programming
Basic Elements of C++.
Computer Science 210 Computer Organization
DATA HANDLING.
Basic Elements of C++ Chapter 2.
Computer Science 210 Computer Organization
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Lecture 18 Arrays and Pointer Arithmetic
Outline Defining and using Pointers Operations on pointers
Chapter 16 Pointers and Arrays
Data Structures and Algorithms Introduction to Pointers
Programming Languages and Paradigms
Presentation transcript:

F28PL1 Programming Languages Lecture 8 Programming in C - 3

Arrays finite sequence of elements of same type elements accessed by an integer index declaration: type name [int]; allocate int * size for type on stack elements numbered from 0 to int-1 e.g. int a[6]; - allocates 6 * 4 == 24 bytes e.g. char b[6]; - allocates 6 * 1 == 6 bytes e.g. double c[6]; - allocates 6 * 8 == 48 bytes

Array size in type name [int]; size int must be a constant cannot: – decide size at run-time – then declare correct size array must declare “too big” array during use must check not exceeding amount allocated

Array access e.g. int a[4]; a[0] == a+0*4  a a[1] == a+1*4  a+4 a[2] == a+2*4  a+8 a[3] == a+3*4  a+12 a a[0]a[1]a[2]a[3]

Array access: expression name =... exp 1 [ exp 2 ]...; 1.evaluate exp 1 to lvalue 2.evaluate exp 2 to integer 3.return *(exp 1 +exp 2 * size for type) – i.e. contents of offset for exp 2 elements of type from address of 1 st byte exp 1 is usually the name of an array

Array access: assignment exp 1 [ exp 2 ] = expression ; 1.evaluate exp 1 to lvalue 2.evaluate exp 2 to integer 3.evaluate expression to value 4.set exp 1 +exp 2 * size for type to value – i.e. address of exp 2 th element of type from address of 1 st byte

name is alias for address of 1 st byte name is not a variable i.e name == & name int a[3]; printf(“a: %x; &a: %x/n”,a,&a);  a: 80497fc; &a: 80497fc Array name and address a ’s value a ’s address

Array bounds no array bound checking if try to access array outside bounds – may get weird values from bytes outside array or – program may crash

Array type for formal parameter type name [] size not specified same as: type * name

Constant #define name text – pre-processor replaces all occurrences of name in program with text – before compilation use to define constants once at start of program e.g. #define SIZE 127

Formatted file I/O formatted input int fscanf(FILE *,” format”,exp 1,exp 2... ) – exp i == lvalue formatted output int fprintf(FILE *,” format”,exp 1,exp 2...) – exp i == rvalue

Formatted numbers can precede format character with width/precision info e.g. %3d – integer – at least 3 characters wide e.g. %4.2f – double – at least 4 chars wide – 2 chars after decimal point

Example: scalar product calculate V 0 [0]*V 1 [0]+...+V 0 [N-1]*V 1 [N-1] $ scalar vecs.txt scalar product: 217

Example: scalar product file contains: – length of vector - N – 1 st vector – V 0 [0]...V 0 [N-1] – 2 nd vector – V 1 [0]...V 1 [N-1] functions to: – read vector – print vector – calculate scalar product

Example: scalar product #include #define MAX 100 getVec(FILE * fin,int v[],int n) { int i; i = 0; while(i<n) { fscanf(fin,"%d",&(v[i])); i = i+1; }

Example: scalar product printVec(int v[],int n) { int i; i = 0; while(i<n) { printf("%2d ",v[i]); i = i+1; } printf("\n"); }

Example: scalar product int scalar(int v0[],int v1[],int n) { int s; int i; s = 0; i=0; while(i<n) { s = s+v0[i]*v1[i]; i = i+1; } return s; }

Example: scalar product main(int argc,char ** argv) { FILE * fin; int v0[MAX],v1[MAX]; int n; if(argc!=2) { printf("scalar: wrong number of arguments\n"); exit(0); } if((fin=fopen(argv[1],"r"))==NULL) { printf("scalar: can't open %s\n",argv[1]); exit(0); }

Example: scalar product fscanf(fin,"%d",&n); if(n>=MAX) { printf("scalar: %d vector bigger than %d\n",n,MAX); fclose(fin); exit(0); } getVec(fin,v0,n); printVec(v0,n); getVec(fin,v1,n); printVec(v1,n); fclose(fin); printf("scalar product: %d\n",scalar(v0,v1,n)); }

Structures finite sequence of elements of potentially different types each element identified by a field name like a Java object with no methods

Structures struct { type 1 name 1 ;... type N name N ;} name ; name i == field allocate: size of type size for type N on stack fields held left to right NB name != &name – & name is address of 1 st byte in sequence – name is value of byte sequence, depending on type context

Structure declaration: example struct {char * name, float height,int age;} chris; chris nameage height

Structure access in expression exp.name i  *(&exp + size for type size for type i-1 ) i.e. contents of offset of preceding fields from start of structure

Structure access: example struct {char * name,int age,float height;} chris; chris.name = “Chris”; - byte 0 chris.height = 1.75; - byte 0+4 == 4 chris.age = 27; - byte == 12 chris nameageheight Chris\0

Structure type definition struct name { type 1 name 1 ;... type N name N; }; struct name is type of structure defines type does not allocate space struct name 1 name 2 ; allocates stack space associate name 2 with 1st byte of new sequence of type struct name 1

Example: character count count how often each distinct character appears in a file array of struct to hold character and count for each character in file – if character already has struct in array then increment count – if unknown character then add to array with count 1

Example: character count #include #define MAX 255 struct freq {int ch;int count;}; struct freq f[MAX]; int fp; fp is index for next free entry in f chcount 0 MAX-1 fp ‘v’2 ‘,’7 ‘0’4 ‘a’3 ‘ ’17 ‘1’1

Example: character count incFreq(int ch) { int i; i=0; while(i<fp) if(f[i].ch==ch) { f[i].count = f[i].count+1; return; } else i = i+1; search f for entry for ch if found, increment count and return chcount 0 MAX-1 fp ‘v’2 ‘,’7 ‘0’4 ‘a’3 ‘ ’17 ‘1’1 e.g. ch ==‘a’ i

Example: character count incFreq(int ch) { int i; i=0; while(i<fp) if(f[i].ch==ch) { f[i].count = f[i].count+1; return; } else i = i+1; search f for entry for ch if found, increment count and return chcount 0 MAX-1 fp ‘v’2 ‘,’7 ‘0’4 ‘a’4 ‘ ’17 ‘1’1 i e.g. ch ==‘a’

Example: character count if(fp==MAX) { printf("more than %d different characters\n",MAX); exit(0); } f[fp].ch = ch; f[fp].count = 1; fp = fp+1; } if ch not found – check for free entry in f – add ch /1 to next free entry – increment fp chcount 0 MAX-1 fp ‘v’2 ‘,’7 ‘0’4 ‘a’4 ‘ ’17 ‘1’1 i e.g. ch ==‘p’

Example: character count if(fp==MAX) { printf("more than %d different characters\n",MAX); exit(0); } f[fp].ch = ch; f[fp].count = 1; fp = fp+1; } if ch not found – check for free entry in f – add ch /1 to next free entry – increment fp chcount 0 MAX-1 fp ‘v’2 ‘,’7 ‘0’4 ‘a’4 ‘ ’17 ‘1’1 i e.g. ch ==‘p’ ‘p’1

Example: character count showFreq() { int i; i = 0; while(i<fp) { printf("%c : %d\n",f[i].ch,f[i].count); i = i+1; }

Example: character count 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 = 0; ch = getc(fin); while(ch!=EOF) { incFreq(ch); ch = getc(fin); } fclose(fin); showFreq(); }

Example: character count $ freq freq.c # : 3 i : 48 n : 36 c : 32 l : 8 u : 10 d : 8 e : 27 : 185 < : 4 s : 10 t : 31 o : 12. : 9 h : 22 > : 2 : 54 b : 1 f : 35 M : 4 A : 4 X : 4 2 : 1 5 : 2 r : 23 q : 6 { : 9 ; : 29 } : 9 [ : 10 ] : 10 p : 14 F : 6 ( : 21 ) : 21 = : 19 0 : 5 w : 5 + : 4 1 : 7 " : 8 m : 2 a : 10 % : 4 \ : 3, : 6 x : 2 : : 1 g : 6 * : 3 v : 3 I : 1 L : 3 E : 2 N : 1 U : 1 ' : 1 ! : 1 O : 1

Coercions ( type ) expression 1.evaluate expression to value 2.now treat value as if type does not physically transform expression as if overlaid template for type on value also called cast

Coercions e.g. integer (4 bytes) as array of char (1 byte) int x; char * c; x = 0x c = (char *)(&x); - c now points at x’s space printf(“%x %x %x %x\n”, c[0],c[1],c[2],c[3]); 

Coercions x is 4 hex bytes – stored from most significant to least significant &x returns address of 1 st byte of int (* char) coerces address of 1 st byte of int to address of 1 st byte of array of char – c[0] is 1 st byte of x == 67 – c[1] is 2 nd byte of x == 45 etc

Structure coercion struct {char a;char b;char c;char d;} m; m.a = ‘a’; m.b = ‘b’; m.c = ‘c’; m.d = ‘d’; m 0123 ‘a’‘b’‘c’‘d’

Structure coercion printf(“m: %x; &m: %x\n”,m,&m);  m: ; &m: == ASCII ‘a’ in hex; 62 == ASCII ‘b’ in hex... struct fields held left to right but printing struct as hex: – coerces to int – accesses bytes right to left as most to least significant

String array of char last char is ‘\0’ no length information “ characters ” string constant allocates space for characters ending with ‘\0’ sets each byte to each character returns address of first character

String variables char name [int]; allocates space for int characters cannot assign string constant to name – must copy character by character char * name; allocates space for pointer to characters can assign string constant to name – changes pointer otherwise, must allocate space for characters...

Example: string length #include int slength(char s[]) { int i; i =0; while(s[i]!='\0') i = i+1; return i; }

Example: string length #main(int argc,char ** argv) { char * q; q = "how long is this string?"; printf("%s: %d characters\n",q,slength(q)); } $ slength how long is this string?: 24 characters

Example: string comparison s 0 ==s 1 – same length: n – 0 <= i <= n-1: s 0 [i]==s 1 [i] e.g. “banana” == “banana” s 0 <s 1 – 0<= i <j: s 1 [i]==s 2 [i] – s 0 [j]<s 1 [j] e.g. “banana” < “banish” e.g. “ban” < “band”

Example: string comparison s 0 >s 1 – 0<= i < j: s 1 [i]==s 2 [i] – s 0 [j]>s 1 [j] e.g. “banquet” > “banana” e.g. “bank” > “ban” int scomp(char s0[],char s1[]) – s0 == s1  0 – s0 <= s1  -1 – s0 >= s1  1

Example: string comparison #include int scomp(char s0[],char s1[]) { int i; i = 0; while(s0[i]==s1[i]) { if(s0[i]=='\0') return 0; i = i+1; } if(s0[i]=='\0' || (s0[i]<s1[i])) return -1; return 1; }

Example: string comparison main(int argc,char ** argv) { printf("banana banana %d\n",scomp("banana","banana")); printf("banana banish %d\n",scomp("banana","banish")); printf("ban band %d\n",scomp("ban","band")); printf("banquet banana %d\n",scomp("banquet","banana")); printf("bank ban %d\n",scomp("bank","ban")); } $ scomp banana banana 0 banana banish -1 ban band -1 banquet banana 1 bank ban 1