.2009| Introduction to Mathematical Software | 44
la n f o r to d a y s tr in g s i n C lo g ic a l a n d c o m p o s it e l o g ic a l e x p re s s io n s lo c a l v a ri a b le s fu n c ti o n s re c u rs iv e f u n c ti o n s b u n d lin g a n d e n c a p s u la ti n g d a ta , a v e ry b it C + + D is c u s s io n a n d o u tl o o k ( M a p le )
| Introduction to Mathematical Software | 45
g ra m m in g l a n g u a g e C
Strings in C are nothing else than zero-terminated arrays of char. “HelloWorld”-Stringinmemory: ac= intstrlen(char*s) { intn; for(n=0;*s!=‘\0’;s++) //sameass!=0,notthesameass!=‘0’ n++; returnn; } letusreplacethe“H”bei“0”: c[0]='0'; rintf("%c%d%d\n",ac[0],ac[0],strlen(“HelloWorld”); enerates the following output: 48 11H 72e 101l 108o 111W 87r 114d 100‘\0‘ 032l 108o 111l 108
.2009| Introduction to Mathematical Software | 46
ro g ra m m in g l a n g u a g e C p le L o g ic a l E x p re s s io n s
ses logical expressions in while and for loops and in if statements. ogical expression evaluates to either True or False! gical operators must compare terms of the same type! e binary logical operators are: > yx is greater than y >= yx is greater or equal to y < yx is less than y <= yx is less or equal to y == yx is equal to y (attention!!! two =) != yx is not equal to y is a logical expression then!lehas the opposite true/false value| Introduction to Mathematical Software | 47
g ra m m in g l a n g u a g e C p o s it e L o g ic a l E x p re s s io n s
r more simple logical expressions can be combined with the logical operators ‘!’, ‘and r’ into a single compound expression. Let l1 and l2 be logical expressions. the C operator for ‘or’ ample: l1 || l2is true if eitherl1 is trueorl2 is trueor bothare true s the C operator for ‘and’ ample: l1 && l2is true if eitherl1 is trueonly if bothl1 and l2 are true the C operator for ‘not’ ample: !l1 is true if and only if l1 is false.2009| Introduction to Mathematical Software | 48
ro g ra m m in g l a n g u a g e C
Flow control: Alternative program flow if)expressionstatement( else statement if(i<3)printf(“iissmallerthan3“); elseif(i>3)printf(“iislargerthan3.“); elseprintf(“iisequalto3.“);| Introduction to Mathematical Software | 49
Flow control: while loops
g ra m m in g l a n g u a g e C
while)expressionstatement( while(i<3){ printf(“iis%d“,i); i=i+1; i++; }do);expressionstatementwhile ( do{ printf(“iis%d“,i); i=i+1; i++; }while (i < 3); statement1;while(expr){statements;laststatement;} is equivalent to for(statement1;expr;laststatement){statements;}
mark:
.2009| Introduction to Mathematical Software | 50
ro g ra m m in g l a n g u a g e C
Flow control II: Blocks: a block is a sequence of statements, grouped by brackets {} definition of variablesstatement #include <stdio.h> int main(void) { printf("Hello World\n“); return 0; }block
| Introduction to Mathematical Software | 51
Functions(procedures, methods), --> named blocks
g ra m m in g l a n g u a g e C
voidreturn typefunction name block
parameter typeparameter name
)( , int square(int x) { int result = x*x; return result; }
usage in main: .... int a; a = square(x); ...
.2009| Introduction to Mathematical Software | 52
ro g ra m m in g l a n g u a g e C
Functions •There are only very few functions pre-built in C. We have to write our functions ourselves. •There are some rules for functions in C: •Functions may return a value, i.e. they may be declared to be of a specific type as float or int. Functions declared to be void return nothing. •All arguments to a function are passed „by value“and are uneffected by the function call. A copy of the original data is passed.| Introduction to Mathematical Software | 53
g ra m m in g l a n g u a g e C E x a m p le : R e a l R o o ts
We want to write a function which calculates the roots of a realquadratic equation. Idea: Input: A, B, C of the equation A*x2 + B*x + C = 0 Returned value: -1 if A = 0 0 if there are two distinct real roots 1 if a pair of complex roots exists 2 if the two roots are identical and: the roots for the 4 cases in two variables r1 and r2A
AC B B r 2
4
2 2,1− ± − =
.2009| Introduction to Mathematical Software | 54
ro g ra m m in g l a n g u a g e C
Example: Real Roots of A*x2 + B*x + C = 0 introots(doubleA,doubleB,doubleC,double*r1,double*r2){ doubled,dr; if(A==(double)0.0){*r1=-C/B;return-1;} d=B*B–(double)4.0*A*C; if(d>(double)0.0){ dr=sqrt(d); *r1=(-B-dr)/((double)2.0*A); *r2=(-B+dr)/((double)2.0*A); return0; }elseif(d==(double)0.0){ *r1=*r2=(-B-dr)/((double)2.0*A); return2; }else{ /*noimplementation*/ return1; }| Introduction to Mathematical Software | 55
g ra m m in g l a n g u a g e C
Example: Real Roots clude<math.h> clude<stdio.h> roots(doubleA,doubleB,doubleC,double*r1,double*r2); main(void){ doubleA,B,C,result1,result2; switch(roots(A,B,C,&result1,&result2)){ case-1:printf(“Linearcase,oneroot.r=%lf\n”,result1); break; case2:printf(“Oneroot.r=%lf\n”,result1); break; case0:printf(“Tworealroots.r=%lfandr=%lf\n”, result1,result2); break; default:printf(“Complexrootsnotimplemented.\n”); } return0;.2009| Introduction to Mathematical Software | 56
ro g ra m m in g l a n g u a g e C M a th e m a ti c a l F u n c ti o n s C k n o w s o n ly b a s ic a ri th m e ti c s . H o w e v e r, t h e re i s a n A N S I S ta n d a rd C l ib ra ry o f m a th e m a ti c a l fu n c ti o n s . T h e lib ra ry h a s i ts o w n h e a d e r fi le : < m a th .h > D o n o t fo rg e t to lin k – lm ( g c c m y p ro g .c – o m y p ro g - lm ) T h e s ta n d a rd C m a th e m a ti c a l fu n c ti o n s w o rk o n ly w it h th e t y p e d o u b le .
–doublein anddoubleoutS o m e o f th e s ta n d a rd f u n c ti o n s a re : s in (x ) a s in (x ) s in h (x ) e x p (x ) c o s (x ) a c o s (x ) c o s h (x ) lo g (x ) ta n (x ) a ta n (x ) ta n h (x ) lo g 1 0 (x ) s q rt (x ) a ta n 2 (x ,y ) p o w (x ,y ) fa b s (x )
| Introduction to Mathematical Software | 57
g ra m m in g l a n g u a g e C
Variables, visibility: -global variables are accessible everywhere; are defined outside any block -local variables have a “scope”. They are only valid in those blocks, where they have been defined. Examples: { inti; i=2; { intj,k; j=3; k=i+j; } i=k;//Error! }{ inti,j; i=0; { inti; i=1;//newdefinitionofi //shadowsoldone } j=i;//j=0 }
.2009| Introduction to Mathematical Software | 58
ro g ra m m in g l a n g u a g e C
Memory allocation static global variable allocation: outside of any procedure -global: accessible from everywhere -static: is fixed with the start of the program local variable allocation: inside blocks or functions -only accessible in the currently alive blocks dynamic allocation: with the help of malloc(size_t s) and free() e.g. int*a=(int*)malloc(sizeof(int)*1000); //useainthesamewayasanarray free(a);| Introduction to Mathematical Software | 59
g ra m m in g l a n g u a g e C
Recursion Observation: gcd(a, b) = gcd(b, a mod b) Claim: The set of divisors of a and b is equal to the set of divisors of b and (a mod b). (Therefore, especially the greatest common divisor is the same.) “=>”Let t be a divisor of a and b, i.e. there exist positive integers x and y witha = xt and b = yt Now, let r := a mod b. Then there is a positive integer z with a = zb + r = zyt + r => (a = ) xt = zyt + r => t(zy-x) + r = 0 =>r = t(x-zy) thus: r is a multiple of t, and: t is a divisor of r.2009| Introduction to Mathematical Software | 60
ro g ra m m in g l a n g u a g e C
Recursion Observation: gcd(a, b) = gcd(b, a mod b) Claim: The set of divisors of a and b is equal to the set of divisors of b and (a mod b). (Therefore, especially the greatest common divisor is the same.) “<=”Let t be a divisor of b and of r := a mod b. Then there exist positive integers x and y with b=xt and r=yt. Because r = a mod b, there is a positive integer z with a=zb+r =b =r => a = z xt + yt = (zx+y)t thus: a is a multiple of t, and: t is a divisor of a| Introduction to Mathematical Software | 61
g ra m m in g l a n g u a g e C
Recursion Observation: gcd(a, b) = gcd(b, a mod b) C function, Euklid’s algorithm: unsigned int gcd(unsigned int a, unsigned int b) { if (b == 0) return a; else return gcd(b, a % b); }.2009| Introduction to Mathematical Software | 62
ro g ra m m in g l a n g u a g e C
Euklid’s algorithm, number of function calls We inspect the sequence of parameters to the function gcd: (a,b) = (a 0,b 0) (a 1,b 1) ... (a k-1,b k-1) (a k,b k) Observation: for all i < k-1 is valid: b i> 2b i+2 Proof: It is a i+1=b iand b i+2=a i+1mod b i+1 from b i+2=a i+1mod b i+1follows there is a positive integer x with a i+1= xb i+1+ b i+2 => b i= a i+1= xb i+1+ b i+2 Because x ≥1 and b i+1> b i+2it follows that b i> 2b i+2 Therefore, b 0> 2(k-1)/2 ·b k-1≥2(k-1)/2 and the number of function calls to gcd is less than k < 1 + 2 log(b 0)| Introduction to Mathematical Software | 63
g ra m m in g l a n g u a g e C
Keywords: autobreakcasecharconstcontinue defaultdodoubleelseenumextern floatforgotoifintlong registerreturnshortsignedsizeofstatic structswitchtypedefunionunsignedvoid volatilewhile.2009| Introduction to Mathematical Software | 64
+ + c la s s e s
e switch to another compiler tool: g++ and another source-file suffix .cc class is a bundle of variables (attributes) and functions (methods) yntaxExample: lass <classname> {class A { [public, protected, private:]public: variable declaration1;int a; variable declaration2; int b; ... int add(int a, int b) { method1 return a+b; method2 ...} }; ccess over „.“ or „->“, instantiation via „new“ . * p_o = new A; o; = o.a; = p_o->a; elete p_o;9| Introduction to Mathematical Software | 65
+ c la s s e s
ntegers have 32 or 64 bits. We want to build our own arithmetics in order to l with bigger integers. a: Take two integers and interprete them as one number, and use the system metics as far as possible. s BiggerInt { vate: ng high_bits; nsigned long low_bits; blic: iggerInt *add(BiggerInt *a, BiggerInt *b) ; // add two numbers iggerInt *sub(BiggerInt *a, BiggerInt *b) ; // subtract number b from a iggerInt *mul(BiggerInt *a, BiggerInt *b) ; // multiply twonumbers iggerInt *div(BiggerInt *a, BiggerInt *b) ; divide a by b iggerInt(long a); // “constructor”; aim: create a long valiable and initialize it iggerInt(long h, unsigned long l); // “constructor”; aim: create a new BiggerInt oid PrintBits(void) ; BiggerInt();.2009| Introduction to Mathematical Software | 66
+ + c la s s e s
iggerInt *add(BiggerInt *a, BiggerInt *b) { int carry; unsigned long low_sum; long high_sum; low_sum = a->low_bits + b->low_bits; if (low_sum < a->low_bits || low_sum < b->low_bits) carry = 1; else carry = 0; high_sum = a->high_bits + b->high_bits + carry; return new BiggerInt(high_sum, low_sum); gerInt(long a) { if (a < 0) high_bits = -1; else high_bits = 0; low_bits = (unsigned long) a; iggerInt(long h, unsigned long l) { high_bits = h; low_bits = l;9| Introduction to Mathematical Software | 67
+ c la s s e s w o b je c ts a re a c c e s s e d
main(void) iggerInt *bi1 = new BiggerInt(73); // get memory for a BiggerInt and call // constructor iggerInt *bi2 = new BiggerInt(73); iggerInt *bi3 = bi1->add(bi1,bi2); // (*b1).add(bi1,bi2); ->PrintBits(); ->PrintBits(); lete b1; lete b2; lete b3;.2009| Introduction to Mathematical Software | 68