We use cookies to give you the best experience possible. By continuing we’ll assume you’re on board with our cookie policy

See Pricing

What's Your Topic?

Hire a Professional Writer Now

The input space is limited by 250 symbols

What's Your Deadline?

Choose 3 Hours or More.
Back
2/4 steps

How Many Pages?

Back
3/4 steps

Sign Up and See Pricing

"You must agree to out terms of services and privacy policy"
Back
Get Offer

Programming in C

Hire a Professional Writer Now

The input space is limited by 250 symbols

Deadline:2 days left
"You must agree to out terms of services and privacy policy"
Write my paper

Programming in C ! ! ! Programming in C Prof. Gustavo Alonso Computer Science Department ETH Zurich [email protected] ethz. ch http://www. inf. ethz. ch/department/IS/iks/ A brief history of C C as a programming language C Programming “main function “constants, variables, data types “operators, control structures “functions “data structures “pointer arithmetic “structures “dynamic memory allocation ©Gustavo Alonso, ETH Zurich. Programming in C 2 A brief history of C ! ! C as a programming language ! ! ! Programming languages are used to specify, design, and build software systems.

Programming languages evolve with the systems they are used to construct. C is a good example of how this process takes place. UNIX was developed at around 1969. It first version was programmed in assembler and run on a DEC PDP-7. The second version was ported to a PDP-11 in 1971 and it was a great success: “16 KB for the system “8 KB for user programs “disk of 521 KB “limit of 64 KB per file !

Don't use plagiarized sources. Get Your Custom Essay on
Programming in C
Just from $13,9/Page
Get custom paper

While writing a FORTRAN compiler for UNIX, a new programming language was developed: B B was interpreted (like Java) and, therefore, slow.

To solve the performance problems of B, a new language was created: C “allowed generation of machine code (compilation) “declaration of data types “definition of data structures In 1973 UNIX was rewritten in C something that was never done before “C is much easier to handle than assembler but “first C version of UNIX was 20 to 40 % larger and slower than assembler version Programming in C 3 ! C has been standardized (ANSI C) and spawned new languages (C++, Stroustrup, 1986) that improve C The basic characteristics of C are: “small in size “loose typing (lots of freedom, error prone) “structured (extensive use of functions) “designed for systems programming (i. e. , low level programming of the type needed to implement an operating system) “C is higher level than assembler but still close to the hardware and allows direct manipulation of many system aspects: pointers, memory allocation, bitwise manipulation … ! !

As we will see when we study assembler, C is not very far from the assembler language but it provides higher level language constructs (functions, data structures) that facilitate programming without loosing too much performance Being a low level language, C gives a lot of freedom to the programmer: “it has the advantage that good programmers can implement very efficient programs in a compact manner “it has the disadvantage that most of us are not good programmers and the freedom C grants is usually translated in error prone, messy code Gustavo Alonso, ETH Zurich. ©Gustavo Alonso, ETH Zurich. Programming in C 4 This is C #include main(t,_,a) char *a; {return! 0= 3) { a = a – 3; if ( a == 3) a = a * 3;} else a = a * 5; Programming in C 18 ©Gustavo Alonso, ETH Zurich. Programming in C 17 ©Gustavo Alonso, ETH Zurich. switch statement (1) ! Switch statement (2) Switch using break selector int–value 1 = selector false int–value 2 = selector false int–value 2 = selector false Statement 4 true Statement 3 true Statement 1 !

The switch statement is used to conditionally perform statements based on an integer expression (selector) switch (selector) { case int-value1 : statement1; break; case int-value2 : statement2; break; case int-value3 : statement3; break; default: statement4; } The exact behavior of the switch statement is controlled by the break and default commands “break continues execution after the switch statement “default is executed if no other match is found Switch without break selector true Statement 2 witch (selector) { case int-value1 : statement1; case int-value2 : statement2; case int-value3 : statement3; default: statement4; } /* fall through */ int–value 1 = selector false int–value 2 = selector false int–value 2 = selector false Statement 4 true Statement 1 true Statement 2 true Statement 3 ©Gustavo Alonso, ETH Zurich. Programming in C 19 ©Gustavo Alonso, ETH Zurich. Programming in C 20 Switch (example) char a = ‘A’; switch (a) { case ‘A’: x *= x; break; case ‘B’: x /= x; break; default: x += 5; } ! for statement a = ‘A’; switch (a) { case ‘A’: x *= x; case ‘B’: x /= x; default: x += 5; } !

The for statement provides a compact way to iterate over a range of values. for (initialization; termination; increment) { statement } ! ! ! initialization ! Once the case ‘A’ is found, x *= x is executed and then we continue after the switch statement. in all cases, only one case will be executed (either ‘A’ or ‘B’ or ‘default’) Note that a is of type char. It does not matter, char is treated as an integer using type conversion Once case ‘A’ is found, x *= x is executed. However, there is no break. This means we continue executing statements while ignoring the cases (the check is not performed anymore).

Thus, the following statements will also be executed x /= x; x += 5; Programming in C 21 ! All elements in the for loop are optional: for (; ; ); break can be used to interrupt the loop without waiting for the termination condition to evaluate to true continue can be used to skip execution of the body of the loop and re-evaluate the termination condition true termination false increment statement for (int x =0; x < 100; x = x + 3){ if (x == 27) continue; else printf(“%d”,x); } ©Gustavo Alonso, ETH Zurich. ©Gustavo Alonso, ETH Zurich. Programming in C 22 while statement ! Do-while statement !

The while statement is used to continually execute a block of statements while a condition remains true. while (expression) { statement } As before, break and continue can be used to terminate the loop or to finish an iteration and go back to the evaluation of the expression for and while are equivalent (can you do it? write a for loop using the while statement and vice versa) expression false true statement The do-while is similar to the while statement except that the loop is always executed once and the condition is checked at the end of each iteration. do { statement } while (expression) break and continue have the same effect as before tatement true ! expression false ! main() { char t; while((t = getchar()) ! = ‘! ’) { if (t >= ‘A’ && t no error, 1 -; not found, 99 -; crash exit() is a very primitive way to terminate a program and one that leaves only very limited chance to deal with failures. More modern programming languages use exceptions and exception propagation mechanisms to indicate the occurrence of an error without having to terminate the program ! Goto C was written as a language that is one step above assembly language. This can be seen, for instance, on the existence of a goto statement Do not use goto when programming.

There are very good reasons to avoid it: “Style: avoid spaghetti code “Use of stack frames ! ! ! ! if (! (buf = AllocMem (BufSize);)) { printf(“kein Speicher vorhanden”); exit(NO_MEM); } ©Gustavo Alonso, ETH Zurich. Programming in C 25 An array is a finite set of variables of the same basic type Instead of giving each variable a name, we use enumeration and group all of them in an array The enumeration of elements within an array always starts with 0. If the array has N elements, the last element is in position N-1 The C compiler does not check the array boundaries “this is a very typical error that t is very difficult to find (usually happens inside loops that traverse the array) “always check the array boundaries before accessing a variable in an array #include float data[5]; /* data to average and total */ float total; /* the total of the data items */ float average; /* average of the items */ main() { data[0] = 34. 0; data[1] = 27. 0; data[2] = 45. 0; data[3] = 82. 0; data[4] = 22. 0; total = data[0] + data[1] + data[2] + data[3] + data[4]; average = total / 5. 0; printf(“Total %f Average %f
“, total, average); return (0); } ©Gustavo Alonso, ETH Zurich. Programming in C 26 Multi-dimensional arrays int a[3][3]

MEMORY Array traversals (examples) 5 6 7 8 9 1 2 3 4 a[0][0] a[0][1] a[0][2] a[1][0]a[1][1] a[1][2]a[2][0] a[2][1] a[2][2] int array[5][5]; for (int i=0; i < 5; i++) for (int j=0; j < 5; j++) array[i][j] = 1; inner loop traversal j outer loop traversal int array[5][5]; for (int i=0; i < 5; i++) for (int j=0; j < i; j++) array[i][j] = 1; inner loop traversal j i 0 0 1 2 3 4 1 2 3 4 int a = 1; for (i=0; i < 3; i++) for (j=0; j < 3; j++) matrix[i][j] = a++; 1 2 3 4 5 6 7 8 9 0 1 2 3 4 int a = 1; for (i=0; i < 3; i++) for (j=0; j < 3; j++) matrix[j][i] = a++; 1 ©Gustavo Alonso, ETH Zurich. 4 7 2 5 8 3 9 Programming in C 27 ©Gustavo Alonso, ETH Zurich. Programming in C 28 outer loop traversal i 0 1 2 3 4 More on arrays ! Pointers ! Arrays can be initialized when they are defined: /* a[0] = 3, a[1] = 7, a[2] = 9 */ int a[3] = {3, 7, 9}; /* liste[0]=0. 0, …, liste[99]=0. 0 */ float list[100] = {}; int a[3][3] = { { 1, 2, 3} { 4, 5, 6} { 7, 8, 9} }; Strings are arrays of characters terminated with the null character ! char str[6] = {‘h’,’a’,’l’,’l’,’o’,’’} char str[6] = “hello”; ! ! For string manipulation, however, use the string. h library In C, arrays are just a syntactic convenience to make programming easier.

Arrays are, for the compiler, the same as pointers (the array name is a pointer to the beginning of the array) ! 8 9 Programming in C 29 1 2 3 4 5 6 7 A variable has a name, an address, a type, and a value: “the name identifies the variable to the programmer “the address specifies where in main memory the variable is located (i. e. , the beginning of the memory region reserved for this variable ) “the type specifies how to interpret the data stored in main memory and how long the variable is “the value is the actual data stored in the variable after if has been interpreted according to a given type Pointers are language constructs that llow programmers to directly manipulate the address of variables Pointers are used with the * and & operators: int* px; /*px = pointer to an integer*/ ! int x; /*x is an integer */ px = &x; /* px gets the address of x */ /* or px points to x */ x = *px; /* x gets the contents of */ /* whatever x points to */ ©Gustavo Alonso, ETH Zurich. ©Gustavo Alonso, ETH Zurich. Programming in C 30 Pointers (I) int* int nummer = 3; int* nummer_ptr = NULL; int Pointers (II) int* *nummer_ptr = 7; int 0 nummer_ptr int* 3 nummer int nummer_ptr *nummer = 8; 7 nummer /* CAREFUL, 8 is not a pointer but an integer */ nummer_ptr = &nummer; 3 ummer_ptr nummer int int x = *nummer_ptr; x int* int nummer = 5; int* int 5 nummer_ptr nummer ©Gustavo Alonso, ETH Zurich. Programming in C 31 7 nummer_ptr 7 nummer ©Gustavo Alonso, ETH Zurich. Programming in C 32 Pointers (III) int int* y_ptr = nummer_ptr; int* int Pointers (IV) 7 x nummer_ptr int* 7 nummer y_ptr = &x; int int* int 7 x nummer_ptr int* 6 nummer y_ptr int *y_ptr = 6; int* int 7 x nummer_ptr int* 6 nummer y_ptr ©Gustavo Alonso, ETH Zurich. y_ptr Programming in C 33 ©Gustavo Alonso, ETH Zurich. Programming in C 34 Pointers (V) int** Pointers (VI) int** p_ptr_ptr int int* *p_ptr_ptr; p_ptr_ptr = &nummer_ptr; int* int _ptr_ptr int *(*p_ptr_ptr) = 5; int* int 7 x nummer_ptr int* 6 nummer 7 x nummer_ptr int* 5 nummer y_ptr y_ptr ©Gustavo Alonso, ETH Zurich. Programming in C 35 ©Gustavo Alonso, ETH Zurich. Programming in C 36 Pointers, arrays and strings ! Troubles with pointers ! ! An array is in reality a pointer: int a[10], y; int* px; px = a; /* px points to a[0] */ px++; /* px points to a[1] */ px=&a[4]; /*px points to a[4] */ y = *(px+3) /*y gets the value*/ /* in a[3] */ The pointer arithmetic in C guarantees that if a pointer is incremented or decremented, the pointer will vary according to its type.

For instance, if px points to an array, px++ will always yield the next element independently of what is the type stored in the array ! ! Strings can be manipulated through pointers: char* message; message = “This is a string”; message is a pointer that now points to the first character in the string “This is a string” Again, use the string. h for string manipulation rather than doing it directly (you will avoid many errors) What is printed by the following code? include void f(int *aa, int *bb) { *bb = 8; aa[1] = bb[2]; aa = bb; } main() { int a[5] = { 1, 2, 3, 4, 5 }, *b; b = a + 2; f(a,b); printf(“%d %d %d %d %d
“, a[0], a[1], a[2], a[3], a[4]); } What is printed by the following code? #include void g(int *aa, int *bb) { bb[2] = aa[-2]; *aa++ = 17; *++aa = 10; } main() { int blap[7] = { 1, 2, 3, 4, 5, 6, 7 }; int *c = blap + 3; g(c,blap); printf(“%d %d %d %d %d %d %d
“, blap[0], blap[1], blap[2], blap[3], blap[4], blap[5], blap[6]); } Programming in C 38 ©Gustavo Alonso, ETH Zurich. Programming in C 37 Gustavo Alonso, ETH Zurich. Structures ! Example structures ! Structures allow programmers to define complex data types. A structure is a new (user defined) data type: struct Id_card { char name[100]; /* Name */ char adresse[100]; /*Address */ short int geburtsjahr; /*Geburtsjahr*/ int telefon; /* Telefonnummer */ short int semester; /* Semester */ } ethz, uniz; struct Id_card erasmus; ! ! Structures of the same type can be copied with the operator = but they should not be compared with == ! Access to the elements of a structure is as follows: ethz. name = “Gustavo”; ethz. elefon = 1234567; Pointers can also refer to structures, in which case elements are accessed through the ->, or * operators: struct Id_card *pid; pid = ? z_student; pid->name = “Gustavo”; pid->telefon = 1234567; (*pid). name = “Gustavo”; (*pid). telefon = 1234567; In ANSI C, structures can be passed as arguments (by value or by reference) and can also be the return type of a function (this is not true in earlier versions of C) Programming in C 39 int main () { struct Typ_kiste { char inhalt[50]; int anzahl; float preis; }; /* was ist in der Kiste */ /* wieviel davon */ /* was kostet eine Einheit */ loat wert; const int MAX_KISTEN = 10; struct Typ_kiste liste_kisten[MAX_KISTEN]; /* Initialisierung … */ /* Gesammter Wert */ for (int i = 0; i < MAX_KISTEN; i++) wert += liste_kisten[i]. anzahl * liste_kisten[i]. preis; … } ©Gustavo Alonso, ETH Zurich. Programming in C 40 ©Gustavo Alonso, ETH Zurich. struct inhalt char[50] Functions ! inhalt char[50] inhalt char[50] ! anzahl int anzahl int anzahl int preis float preis float preis float … liste_kisten[0] liste_kisten[0]. inhalt liste_kisten[0]. anzahl liste_kisten[0]. preis liste_kisten[1] liste_kisten[1]. inhalt liste_kisten[1]. anzahl liste_kisten[1]. preis iste_kisten[2] liste_kisten[2]. inhalt liste_kisten[2]. anzahl liste_kisten[2]. preis C is a modular language where the main unit of composition is the function A function has the following elements: “a return type: specifies the type of the value returned by the function when it terminates “a function name: identifies the function for the programmer “arguments of defined types: parameters to pass to the function, which can be • by value: the function gets the a copy of the value of the parameters but cannot modify the actual parameters • by reference: the function gets the address (reference) of the parameters and can modify them General syntax: returntype function_name(def of parameters) { localvariables functioncode } ! An example: float findaverage(float a, float b) { float average; average=(a+b)/2; return(average); } ! In ANSI C functions must be declared as prototypes before they are defined: float findaverage(float a, float b) ©Gustavo Alonso, ETH Zurich. Programming in C 41 ©Gustavo Alonso, ETH Zurich. Programming in C 42 Examples /* SWAP.

C exchange values */ #include void swap(float *x, float *y); /* prototype */ main() { float x, y; printf(“Please input 1st value: “); scanf(“%f”, ); printf(“Please input 2nd value: “); scanf(“%f”, ); printf(“Values BEFORE ‘swap’ %f, %f
“, x, y); swap(, ); /* address of x, y */ printf(“Values AFTER ‘swap’ %f, %f
“, x, y); return 0; } /* exchange values within function */ void swap(float *x, float *y) { float t; t = *x; /* *x is value pointed to by x */ *x = *y; *y = t; printf(“Values WITHIN ‘swap’ %f, %f
“, *x, *y); } ©Gustavo Alonso, ETH Zurich. ain() is also a function * FACTORIAL * * fact(n) = n*(n-1)*…. 2*1 * #include fact(n) { int n; if (n == 0) return(1); return(n * fact(n-1)); } main() { int n, m; printf(“Enter a number: “); scanf(“%d”, ); m = fact(n); printf(”Factorial of %d is %d.
“, n, m); exit(0); /* program to print arguments from command line */ #include main(int argc, char **argv) { int i; printf(“argc = %d

“,argc); for (i=0;i= arrsize) { /* There’s not. Get more. */ arrsize *= 2; arr = (int*) realloc(arr, arrsize*sizeof(int)); if(arr == NULL){ fprintf(stderr, “Allocation failed %d. n”); exit(18); } } /* Store the number. */ arr[num++] = in; ! ! ! The definition of types and variables help the compiler to understand the program we have written The declaration of variables leads to the allocation of memory for those variables. In general, this happens automatically and without intervention of the programmer C allows the programmer to allocate and deallocate memory dynamically The functions used for memory allocation are in stdlib. h Typical function calls are “malloc “free ! malloc returns a pointer to the allocated memory.

The pointer is generic (void *) and it is a good practice to cast the pointer to the appropriate pointer type to avoid errors. Allocated memory must be returned to the system: free(nptr); } /* Print out the numbers. */ for(m = 0; m < num; ++m) printf(“%d
“, arr[m]); } ©Gustavo Alonso, ETH Zurich. Programming in C 45 ©Gustavo Alonso, ETH Zurich. Programming in C 46 Example string library #include #include void main() { char name1[12], name2[12], mixed[25]; char title[20]; strcpy(name1, “Rosalinda”); strcpy(name2, “Zeke”); strcpy(title, “This is the title. ); printf(” %s

“, title); printf(“Name 1 is %s
“, name1); printf(“Name 2 is %s
“, name2); if(strcmp(name1, name2) ; 0) /* returns 1 if name1 > name2 */ strcpy(mixed, name1); else strcpy(mixed, name2); } printf(“The biggest name alphabetically is %s
“, mixed); strcpy(mixed, name1); strcat(mixed, ” “); strcat(mixed, name2); printf(“Both names are %s
“, mixed); References Some material for these foils and some of the examples have been taken from the following online books on C (there are many more): ! ! ! C Programming, Steve Holmes: http://www. strath. ac. k/IT/Docs/Ccourse/ C language tutorial: http://www. graylab. ac. uk/doc/tutorials/C/index. htm Programming in C , A. D. Marshall: http://www. cs. cf. ac. uk/Dave/C/CE. html For how C was developed, read the tutorial written by Brian W. Kernighan in 1974: This is the title. Name1 is Rosalinda Name2 is Zeke The biggest name alphabetically is Zeke Both names are Rosalinda Zeke ! Programming in C: A Tutorial, B. W. Kernighan: http://www. lysator. liu. se/c/bwk-tutor. html ©Gustavo Alonso, ETH Zurich. Programming in C 47 ©Gustavo Alonso, ETH Zurich. Programming in C 48

Cite this Programming in C

Programming in C. (2018, Feb 03). Retrieved from https://graduateway.com/programming-in-c/

Show less
  • Use multiple resourses when assembling your essay
  • Get help form professional writers when not sure you can do it yourself
  • Use Plagiarism Checker to double check your essay
  • Do not copy and paste free to download essays
Get plagiarism free essay

Search for essay samples now

Haven't found the Essay You Want?

Get my paper now

For Only $13.90/page