C-programming Goal To give basic knowledge of the C language. Some previous experiences in programming are assumed. Litterature I Bilting, Skansholm: Vägen till C, in Swedish, I Kernighan, Ritchie: The C Programming Language, Second edition, I Oualline: Practical C programming On the net you can nd several tutorials, eg http://computer.howstuworks.com/c.htm http://www2.its.strath.ac.uk/courses/c/ http://www.cs.cf.ac.uk/dave/c/ce.html (2009-10-29 1.1 )
What is C? I An imperative programming language I Statements (commands) that are executed in sequence I Data (variables) that are manipulated I Functions with possible side eects I Iterations (loops) I Low level but platform independent (hmm... ) I memory addresses, address arithmetic I bit manipulation I... I Small, primitive I Similarities with Java, Pascal and Fortran (2009-10-29 1.2 )
History I Originally developed by Dennis Ritchie 1972 for implementation of operating systems and other system software I Unix was mostly written in C I ANSI-standard from 1989 (ANSI-C) I Revised standard from 1999 (C99) I Inspired languages like C++ and Java (2009-10-29 1.3 )
Some features I C uses static typing: all variables has a type that cannot be changed I C uses weak typing: some type conversions are done automatically and uncontrolled and inconsistent conversions are allowed I In C you may works directly with memory addresses I Explicit manual memory handling I C is compiled to machine code while Python and Java are interpreted I There is a minimum of runtime checks while running your program. (uncontrolled pointers, limits of an array, undened variables... ) (2009-10-29 1.4 )
When, for what and why is C used I To be close to the hardware (parts of OS, drivers,... ) I Embedded system I Time- and/or memory critical applications I When there is no other choice, a naked system without OS I Programming of parallel systems (Typical with C, C++ or Fortran). (OpenMP is only available in these languages) (2009-10-29 1.5 )
Example A program that prints Hello, world /* hello.c A first, classic example of a C-program */ #include <stdio.h> int main() { printf("hello, world\n"); return 0; (2009-10-29 1.6 )
Example: iteration, variables /* squares.c Program that writes a table over squares of the numbers 1, 2,... 10 */ #include <stdio.h> int main() { int i = 1; while ( i<=10) { printf( "%d \t %d\n", i, i*i ); i = i + 1; return 0; (2009-10-29 1.7 )
Compiling bellatrix$ ls squares.c bellatrix$ cat squares.c /* squares.c Program that writes a table over squares of the numbers 1, 2,... 10 */ #include <stdio.h> int main() { int i = 1; while ( i<=10 ) { printf( "%d \t %d \n", i, i*i); i = i + 1; return 0; bellatrix$ gcc squares.c bellatrix$ ls a.out* squares.c (2009-10-29 1.8 )
Execution bellatrix$ a.out 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100 bellatrix$ (2009-10-29 1.9 )
Example: several functions /* factorial.c */ Program that tabulates the faculty function #include <stdio.h> int factorial(int n) { int result = 1; while ( n > 0 ) { result = result*n; n = n - 1; return result; int main() { int i = 0; while ( i<=15 ) { printf( "%2d %12d \n", i, factorial(i)); i = i + 1; return 0; (2009-10-29 1.10 )
Example: recursion, conditional statements /* factorialrec.c Program that tabulates the faculty function Recursive version. */ #include <stdio.h> int factorial(int n) { if ( n<=0 ) return 1; else return n*factorial(n-1); int main() { int i = 0; while ( i<=15 ) { printf( "%2d %12d \n", i, factorial(i)); i = i + 1; return 0; (2009-10-29 1.11 )
Example: Read and write characters /* cat1.c Copy standard input to standard output */ #include <stdio.h> int main() { int c; c = getchar(); while ( c!= EOF ) { putchar(c); c = getchar(); return 0; (2009-10-29 1.12 )
Example: Read and write characters version 2 /* cat2.c Copy standard input to standard output, version 2 */ #include <stdio.h> int main() { int c; while ( (c = getchar())!= EOF ) putchar(c); return 0; (2009-10-29 1.13 )
Example: A program that counts characters and lines #include <stdio.h> int main() { int c; int nchars = 0, nlines = 0; while ( (c = getchar())!= EOF ) { ++nchars; if ( c == '\n' ) { ++nlines; printf( "Characters: %d \nlines: %d \n", nchars, nlines ); return 0; (2009-10-29 1.14 )
Conclusions I A C-program consists of one or more function that are stored in one (or more) le I Comments are delimited with /* and */. In C99 // can be used for oneline comments, (as in C++ and Java) I #include <stdio.h> to use library functions for I/O (printf, getchar, putchar, EOF) I A C-function has a return type, a name, a parameter list and a function body I The function body can hold declarations of variables and statements I Semicolon (;) is used to terminate declarations and statements. I Vaiables can also be declared outside a function. They then become global in some sense. (2009-10-29 1.15 )
Conclusions continued I Each le must be compiled before the program can be executed I The execution starts in the function named main I Variables must be declared with type and name I Variables are assigned values (of the proper type) with assignments I Statements in a function are executed in sequence I Statements for selections: if (and switch) I Statements for iterations: while (and for and do-while). (2009-10-29 1.16 )
Exercises 1. Write a program that reads characters from standard input, and counts the number of sentences if the text. A sentence is terminated with a period, an exclamation mark or a question mark. 2. Write a C-function that computes the harmonic sum 1 + 1=2 + 1=3 + 1=4::: + 1=n What parameters and what return type should the function have? 3. Write a C-program that tabulates the above sum for n = 1; 2; : : : ; 10 4. Write a C-program that computes how many terms are required to get a sum that is greater than 10. 1 + 1=2 + 1=3 + 1=4::: + 1=n (2009-10-29 1.17 )
The if-statement Two variants: and if ( u ) s where if ( u ) s 1 else s 2 I u is an expression of any type I each of s, s 1, s 2 is a statement The expression u is interpreted as false if its value is 0, 0.0, or NULL (for pointers) otherwise as true. If more that one statement is required for any of s, s 1, s 2, you build a compund statement using { and (2009-10-29 1.18 )
The for statement An iteration statement with the syntax: for ( u 1 ; u 2 ; u 3 ) s You get the same functionality using the while-statements: u 1 ; while ( u 2 ) { s; u 1 ; Common idiom to iterate something a number of times for ( i = 1; i<10; i++ ) { s; (2009-10-29 1.19 )
Operators (incomplete) binary aritmetical : + - * / unary aritmetical : + - ++ -- assignment : = += -= *= /= relations : == < > <= >=!= logical : &&! (2009-10-29 1.20 )
Data types I void I scalar types I arithmetic types I integer types: char, short int, long int, long long int (optional, unsigned) I oating point types: float, double, long double I pointers I arrays (not really a type, rather a pointer) I compound types struct Note: No type for logical values (true, false)! (2009-10-29 1.21 )
Integer types Common sizes and numerical ranges: long int 4 2 31 to 2 31 1 short int 2 2 15 to 2 15 1 unsigned long int 4 0 to 2 32 1 unsigned short int 2 0 to 2 16 1 signed char 1-128 to 127 unsigned char 1 0 to 255 The type int is usually equivalent to long or short int (implementation dependent) The type char is usually equivalent to unsigned char (2009-10-29 1.22 )
Constants Integer constants decimal form 3, 8, -255 octal form 003, 010, -0377 Floating point constants Notation with decimal point and/or exponent -1.5,.26, 100., 0.57721566 1e10, 0.5e2, 1e-10 (2009-10-29 1.23 )
The type char The type char is an integer type and character constants are a way to represent both characters and small integer numbers. Thus you can do arithmetic on characters: char toupper(char c) { /* If c is in lower case, it is converted to upper case */ if ( c>='a' && c <='z' ) return c + 'A' - 'a'; else return c; (2009-10-29 1.24 )
The library ctype.h This library contains representation independent functions to classify characters: #include <ctype.h> int isalpha(int c); int isdigit(int c); int isalnum(int c); int isspace(int c); int isupper(int c); int islower(int c); int isprint(int c); int iscntrl(int c); int tolower(int c); int toupper(int c); (2009-10-29 1.25 )
Example: Print an ascii-table /* A program that prints a table of character codes */ int main() { char c; for ( c = ' '; c<127; c++ ) printf( "%d \t %c \n", c, c ); return 0; (In the ascii code, space is the rst printable and (126) is the last printable) (2009-10-29 1.26 )
Exercises 1. Write a program that reads characters from standard input and that counts the number of words. A word is dened as a sequence of characters. 2. Modify the program so that it also prints the length of the longest word. 3. Write a function int isequal(char c1, char c2) that returns 1 if the characters c1 and c2 are equal, otherwise 0. If the characters are letters, they should be treated as equal regardless of case (upper/lower). 4. Write a program that reads a line from standard input and that prints the line translated to rövarspråket. In the translation, a consonant like x is replace with xox while vowels are left unchanged. For example: The text Don't panic becomes Dodonon'tot popanonicoc. 5. Write a function that reads a line of arbitrary length from standard input and that prints the line backwards, i. e. with the last character rst. The function need not use arrays or lists. (2009-10-29 1.27 )
All variables have to be declared Exempel: int i, j, k; float x, y; char c; short int p, q; unsigned short int r; unsigned char ch; int start = 0, stop = 10; char c=getchar(); The declarations must be placed at the top in a block. A block is dened by a { - pair (The C99-standard allows a more free placement of declarations) (2009-10-29 1.28 )
Type conversions I Operands with dierent types are automatically converterted from narrow types to wider types, eg short to long. I Assignments from wide types to narrower types can give warnings but are not illegal. I Explicit type conversions with casts : (type) expression Exempel: y = power( (float) i, n ); (2009-10-29 1.29 )
Formatted output printf( format string, value, value,... ) Some format specications: %d int %ld long int %u unsigned int %lu unsigned long int %o int octal form %x int hexadecimal form %c char %f double decimalform %e double exponential form %g double decimal- or exponential form %s character string (2009-10-29 1.30 )
Formatted output continued The specications can have attributes to specify eld width, number of decimals, justication etc. /* formatexample.c - Demonstrates the use of format codes */ #include <stdio.h> int main() { float x; for (x=0; x<=10.; x++) { printf(" %2.0f %8.4f %12.4e\n", x, sin(x), exp(x)); /* Output: 0 0.0000 1.0000e+00 1 0.8415 2.7183e+00 2 0.9093 7.3891e+00 3 0.1411 2.0086e+01 4-0.7568 5.4598e+01 5-0.9589 1.4841e+02 6-0.2794 4.0343e+02 7 0.6570 1.0966e+03 8 0.9894 2.9810e+03 9 0.4121 8.1031e+03 10-0.5440 2.2026e+04 (2009-10-29 1.31 )
Input of numbers The function scanf for formatted input Example: #include <stdio.h> int main() { float x; int n; printf("give x and n: "); scanf("%f %d", &x, &n ); printf( "%f raised to %d is %f", x, n, power(x,n) ); return 0; (2009-10-29 1.32 )
Some facts about functions I All functions are declared at the same level, i. e. a function cannot contain functions. I A function has zero or more parametrars of arbitrary type I At call time, the parameters must match in order, number and type. Automatical type conversion may occur if some cases, e. g. int -> double. I Parameter transmission uses call by value I A function can be of the type void if it has no return value. (2009-10-29 1.33 )
I Functions can return any scalar type or structure(struct) but not arrrays. I Functions returns a value of the type int if no explicit type is specied. I Local variables dies at return (if not static) I To use a function, if has to be known. To be known it must be introduced either through a denition or a declaration: typ name( parameter list ); typ name( void ); (2009-10-29 1.34 )
Exercises 1. The series is called Fibonaccis numbers. 0; 1; 1; 2; 3; 5; 8; 13 : : : 1.1 Write a program that reads a number n, calculates and prints the n rst Fibonaccinumbers. 1.2 Write a program that reads a number m and calcutes how many Fibonacci numbers that are less than or equal to m. 1X 2. The exponential function e x can be approximated with the ininite series i=0 x i 2 i! = 1 + x 1 + x 2 + x 6 + x 24 + Write a function double exp( double x) that calculates and returns (an approximation) to e x using the above formula. 3. Write a recursive function void printb(int x, int b) that prints x in the base b. For simplicity, assume that b <= 10. 3 4 (2009-10-29 1.35 )
Example: prime number control Problem: Write a program that reads a sequence of positive integers, and for each of these, tests whether it is a prime number or not. int isprime(int n) { int answer = 1; int i; for (i = 2; i<n; i++) { if ( n%i == 0 ) { answer = 0; return answer; I A new operator: % (2009-10-29 1.36 )
Better: int isprime(int n) { /* Precondition: n is an integer >= 0 * Returns: 1 if n is a prime number else 0 */ int answer = 1; int i; for (i = 2; i <= sqrt(n) && answer; i++) { if ( n%i == 0 ) { answer = 0; return answer; I A new operator: && I The function sqrt I 0 is interpreted as false, everything else as true (2009-10-29 1.37 )
The program: /* checkprimes.c Reads a sequence of integer numbers and tests if these are a prime number or not. Terminates when the number 0 is read. */ #include <stdio.h> #include <math.h> int isprime(int n) {... // As above int main() { int number=1; // Number to check while (number!=0) { printf("number to test: "); scanf("%d", &number); if (number!=0) { if (isprime(number)) { printf("%d is a prime number\n", number); else { printf("%d is not a prime number\n", number); return 0; (2009-10-29 1.38 )
Execution: kursa$ gcc -o checkprimes checkprimes.c Undefined first referenced symbol in file sqrt /var/tmp//cczwizdu.o ld: fatal: Symbol referencing errors. No output written to checkprimes collect2: ld returned 1 exit status kursa$ gcc -o checkprimes -lm checkprimes.c kursa$ checkprimes Number to test: 2 2 is a prime number Number to test: 4 4 is not a prime number Number to test: 12 12 is not a prime number Number to test: 13 13 is a prime number Number to test: 4731 4731 is not a prime number Number to test: -4-4 is a prime number Number to test: 0 kursa$ (2009-10-29 1.39 )