Upcoming SlideShare
×

# C Programming by Süleyman Kondakci

1,151 views

Published on

A general coverage of the C language is presented. These slides are useful for students attending C courses at universities and other institutions as well as others following C tutorials or learning the language by themselves. Comments are welcome for creating better future.
Faculty of Eng. & Computer Sciences of IEU, Izmir-Turkey,
Assoc. Prof. Dr. S. Kondakci

Published in: Education, Technology
3 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
Your message goes here
• Be the first to comment

Views
Total views
1,151
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
67
0
Likes
3
Embeds 0
No embeds

No notes for slide

### C Programming by Süleyman Kondakci

1. 1. Composed for SE 115 C programming Faculty of Engineering & Computer Sciences Izmir University of Economics Assoc. Prof. Dr. Süleyman Kondakci Suleyman.kondakci@ieu.edu.tr http://homes.ieu.edu.tr/skondakci
2. 2. Summary of C Operations • Arithmetic: • int i = i+1; i++; i--; i *= 2; • +, -, *, /, %, • Relational and Logical: • <, >, <=, >=, ==, != • &&, ||, &, |, ! • Flow Control: • • • • • • if ( ) { } else { } while ( ) { } do { } while ( ); for(i=1; i <= 100; i++) { } switch ( ) {case 1: … } continue; break;
3. 3. Relational,equality, and logical operators Relational Operator: Less than: < Greater than: > Less than or equal: <= Greater than or equal: >=
4. 4. Equality and Logical Operators Equality Operators: Equal: == Not equal: != Logical Operators: Negation: ! Logical and: && Logical or: ||
5. 5. Example: Conditional Operators int x=0, y=10, w=20, z, T=1, F=0; z = (x == 0); /*** logical operator; result --> 0 or 1 z = (x = 0); /*** assignment operator; result --> ***/ ***/ z = (x == 1); z = (x = 15); z = (x != 2); z = (x < 10); z = (x <= 50); z = ((x=y) < 10); /*** performs assignment, compares z = (x==5 && y<15); z = (x==5 && y>5 && w==10); z = (x==5 || y>5 && w==10); z = (T && T && F && x && x); /*** ==> F; ***/ z = (F || T || x || x); /*** ==> T; ***/ /*** value of x doesn't matter ***/ with 10 ***/
6. 6. Input to & Output From Program Input: scanf ("format specifier", variable) Output: printf ("format specifier", variable) Format specifiers %c = as a character %d = as a decimal integer %e = as a floating-point number in scientififc notation %f = as a floating-point number %g = in the e-format or f-format, whichever is shorter %s = as a string of characters
7. 7. Small Sample Programs /*hello.c - traditional zeroth program*/ #include <stdio.h> int main() { printf("Hello world!n"); return 0; } On the screen Hello world!
8. 8. Escape Sequences Escaped characters produce visual and audible effects a bell b backspace f formfeed t horizontal tab v vertical tab backslash ' single quote " double quote ooo octal number n newline ? question mark xhh r carriage return hexadecimal number
9. 9. The Output Function (printf) Char acter d, I o x, X Argument Type; Printed As int; decimal number int; unsigned octal number (without a leading zero) int; unsigned hexadecimal number (without a leading Ox or OX, using abcdef or ABCDEF for 10,...,15) u int; unsigned decimal number c int; single character s char; print characters from the string until a '0' or the number of charachters given by the precision f double; [-]m.dddddd, where the number of d's is given by the precision (default is 6) e, E double; [-]m.dddddde ± xx or [-]m.ddddddE ± xx where the number of d's is given by the precision (default is 6) g, G double; use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f; trailing zeros and a trailing decimal point are not printed p void *; pointer (implementation-dependent representation) % no argument is converted; print a %
10. 10. The Input Function (scanf) Char acter Input Data; Argument Type d decimal integer; int * I integer; int * ; the integer may be in octal (leading 0) or hexadecimal (leading 0x or 0X) o octal intger (with or without leading zero); int * u unsigned decimal integer; unsigned int * x hexadecimal number (with or without a leading 0x or 0X); int * characters; char *. The next input characters (default 1) are placed at the indicated c spot. The normal skip over white space is suppressed; to read the next non-white space character, use %1s character string (not quoted); char * ; pointing to an array of characters large s enough for the string and a terminating `0' that will be added floating-point number with optional sign, optional decimal point, and optional e, f, g exponent; float * % literal %; no assignment is made
11. 11. A Very Tiny Program /*fahr.c (several versions) - convert Fahrenheit to Celsius. Originally not mine, SK*/ int main() { int fahr = 42, cels; cels = 5*(fahr-32)/9; printf("%d degrees Fahrenheit is %d degrees Celsiusn", fahr, cels); return 0; }
12. 12. C Programming
13. 13. The if Statement The if statement has two forms: 1) Plain if: if(expression 1) statement 1; else if (expression 2) statement 2; else statement 3
14. 14. Nested if Statement 2) Nested if: if (expression) { if (expression) { statements if (expression) { statements } } } else { statements }
15. 15. The ? : decision operators expression1?expression2:expression3 Same as if(expression1) expression2 else expression3
16. 16. Example: The ? and : operators X = 12; y = (x < 5) ? 5 : 10; Gives the same result as this if (x < 5) y = 5; else y = 10;
17. 17. C Language Blocks and Styling single block { Statements outer block } { inner block { ... { } } } Multiple nested block structure
18. 18. Example: Single Block for (i=0; i<=10; i++) { printf("index is: %d", i); } if (a == b && a <= c || c >0) printf("Aha!! aa"); You can aslo write like this: if (a == b && a <= c || c >0) { printf("Aha!!aa"); } Or if (a == b && a <= c || c >0) printf("Aha!!aa");
19. 19. Example: Multiple (nested) Blocks int a=2; int b=30; int c=11; if(a==b){ if( b<=c && c >10){ c= a-b; while (a <=10) { printf("Value of a: %d", a); B = a*c; } a = a-1; } }else{ printf("That is all folks!"); }
20. 20. Small Sample Programs /* Uses scanf() to get input. Originally not mine, S.K */ /* Uses printf() to display the result. */ #include <stdio.h> int main() { int fahr, cels; printf("How many degrees? "); scanf("%d", &fahr); cels = 5*(fahr-32)/9; printf("%d degrees Fahrenheit is %d degrees Celsiusn", fahr, cels); return 0; }
21. 21. Small Sample Programs /*same, but with real numbers instead of silly integers*/ #include <tdio.h> int main() { double fahr, cels; printf("How many degrees? "); scanf("%lf", &fahr); cels = 5.0*(fahr-32.0)/9.0; printf("%.2f degrees Fahrenheit is %.2f degrees Celsiusn", fahr, cels); return 0; }
22. 22. Modified Farhrenheit to C-1 /*fahrcels.c (several versions) - use a conditional statement to select one of two calculations.*/ #include <stdio.h> int main() { double fahr, cels; int unit; /*'C' for Celsius input, 'F' for Fahrenheit*/ /*get input type*/ printf("Type C to convert Celsius (C) to Fahrenheit (F), or F to C: "); unit = getchar(); /*get input, and do the appropriate conversion*/ printf("degrees? "); if(unit == 'C') { scanf("%lf", &cels); fahr = 9.0*cels/5.0+32.0; } else { scanf("%lf", &fahr); cels = 5.0*(fahr-32.0)/9.0; } printf("%.3f degrees Fahrenheit is %.3f degrees Celsiusn", fahr, cels); return 0; }
23. 23. Modified Farhrenheit to C-2 /*uses logical OR to equlize lowercase to uppercase characters*/ #include <stdio.h> int main(){ double fahr, cels; int unit; /*'C' for Celsius input, 'F' for Fahrenheit*/ /*get input type*/ printf("Type C to convert Celsius to Fahrenheit, or F to C: "); unit = getchar(); /*get input, and do the appropriate conversion*/ printf("degrees? "); if((unit == 'C') || (unit == 'c')) { scanf("%lf", &cels); fahr = 9.0*cels/5.0+32.0; } else { scanf("%lf", &fahr); cels = 5.0*(fahr-32.0)/9.0; } printf("%.3f degrees Fahrenheit is %.3f degrees Celsiusn", fahr, cels); return 0; }
24. 24. Modified Farhrenheit to C-3 /*uses a conditional expression as well as a conditional statement*/ #include <stdio.h> #include <ctype.h> int main() { double fahr, cels; int unit; /*'C' for Celsius input, 'F' for Fahrenheit*/ /*get input type*/ printf("Type C to convert Celsius to Fahrenheit, or F to C: "); unit = toupper(getchar()); /*get input, and do the appropriate calculation*/ printf("degrees? "); scanf("%lf", (unit=='C')? &cels: &fahr); if(unit == 'C') fahr = 9.0*cels/5.0+32.0; else cels = 5.0*(fahr-32.0)/9.0; printf("%.3f degrees Fahrenheit is %.3f degrees Celsiusn", fahr, cels); return 0; }
25. 25. Modified Farhrenheit to C-4 #include <stdio.h> #include <ctype.h> int main() { double fahr, cels; int unit; /*'C' for Celsius input, 'F' for Fahrenheit*/ /*get input type*/ printf("Type C to convert Celsius to Fahrenheit, or F to C: "); unit = toupper(getchar()); /*get input, and do the appropriate calculation*/ printf("degrees? "); if(unit == 'C') { scanf("%lf", &cels); fahr = 9.0*cels/5.0+32.0; } else { scanf("%lf", &fahr); cels = 5.0*(fahr-32.0)/9.0; } printf("%.3f degrees Fahrenheit is %.3f degrees Celsiusn", fahr, cels); return 0; }
26. 26. Real C Programming
27. 27. The for Loop Syntax update_loop_counter) for (initialize_loop_counter; check_loop_range; update_loop_counter) { statements }
28. 28. Example: for Loop #include <stdio.h> #include <stdlib.h> int main(){ int i; for(i = 0; i <= 10; i++){ // Inside the loop printf("loop count = %dn", i); } // End of the loop return 0; }
29. 29. The while Loop Syntax while(expression) Statement; //Single statement Or like this if blocks of statements! while(expression) { Statements }
30. 30. Example: while Loop include <stdio.h> #include <stdlib.h> int main(){ int inchar; /* The Classic Bit */ while( (inchar = getchar()) != EOF){ printf("%c You typed:n", inchar); } return 0; }
31. 31. The do-while Loop Syntax First execute then check do { statements } First check then execute while (expression) { statements }
32. 32. Example: for and while Loops #include <stdio.h> #include <stdlib.h> int main(){ int i; i = 0; #include <stdio.h> #include <stdlib.h> int main(){ int i; for(i = 0; i <= 10; i++){ while(i <= 10){ printf("%dn", i); printf("%dn", i); i++; } return 0; } } return 0; }
33. 33. Example: do-while Loop #include <stdio.h> #include <stdlib.h> int main(){ int i; i = 0; /* check */ do { printf("%dn", i); /* increment i */ i++; } while(i <= 10); return 0; }
34. 34. The switch Statement some_value; expression = some_value; /* can be the result of another expression or a user defined value. */ some_value can be const1, const2,..., const100 or else expression) (expression switch (expression) { const1: case const1: statements ; break; const2: case const2: statements ; break; ... case const100: statements; break default: statements ; break; }
35. 35. Example: switch vs if Statement #include <stdio.h> #include <stdlib.h> #include <stdio.h> #include <stdlib.h> int main(){ int main(){ int i; int i; for(i = 0; i <= 3; i++){ for(i = 0; i <= 3; i++){ switch(i){ if (i == 1) printf("1 n"); case 1: printf("1 n"); else if (i == 2) printf("2 n"); break; else if (== 3) printf("3 n"); case 2: printf("2 n"); else printf("defaultn"); break; } case 3: printf("3 n"); return 0; break; } default: printf("defaultn"); break; } } return 0; }
36. 36. The break statemet: Get out of the loop! #include <stdio.h> #include <stdlib.h> int main(){ int i; for(i = 0; i < 100000000; i++){ printf("Press s to stop"); if(getchar() == 's') break; printf("%dn", i); } return 0; }
37. 37. The continue Statement: Skip some parts #include <stdio.h> int main(){ int i; for(i = -10; i < 10; i++){ if(i == 0 || i==6 || i == 9 ) // do not display 0, 6, and 9, continue with others continue; printf("%d n", i); // Other statements ..... } return 0; }
38. 38. C Programming
39. 39. Functions - why and how ? • If a program is too long • Modularization – easier to • code • debug • Code reuse • Passing arguments to functions – By value – By reference • Returning values from functions – By value – By reference
40. 40. Definition and Usage of Functions #include <stdio.h> #include <stdlib.h> /** function prototype declarations start here**/ int add(int a, int b); int GetPosinteger(void); // or just int GetPosinteger(); /** End of function prototype declarations **/ int main() { int x, y, z; x = GetPosinteger(); y = GetPosinteger(); printf("%d + %d = %dn", x, y, add(x,y)); return 0; } int add(int a, int b){ return a+b; } int GetPosinteger(void) { int a; do { printf("Enter a positive integer: "); scanf("%d", &a); } while (a <= 0); return a; }
41. 41. Functions are subprograms! The syntax for declaring a function: return-type function-name (argument declarations) { local variable declarations Statements } Signature (or prototype) of a function: return-type function-name (argument list)
42. 42. Void in void out or return value void print_message(void) // Inputs are void! { // Here void means no input parameter and no return value printf("hello"); // No return } int add(int a, int b) // We have two int inputs a & b { int sum; sum = a + b; return sum; // This is the output (return value) }
43. 43. Functions – Call by Value #include <stdio.h> int sum(int a, int b); /* function prototype at start of file */ void main(void){ int total = sum(4,5); /* call to the function */ printf("The sum of 4 and 5 is %d", total); } int sum(int a, int b){ return (a+b); } /* the function itself - arguments passed by value*/ /* return by value */
44. 44. Functions- Call by Reference (later!!) #include <stdio.h> /* function prototype at start of the code */ int sum(int *pa, int *pb); // Pointer references as input void main(void){ int a=4, b=5; int *ptr = &b; int total; total = sum(&a,ptr); /* call to the function */ printf("The sum of 4 and 5 is %d", total); } int sum(int *pa, int *pb){ /* the function definition here - arguments passed by reference */ return (*pa+*pb); /* return by ref */ }
45. 45. C Programming
46. 46. Making Menus for Users void menu () { printf("The following optionsn"); printf("R ==> Register a bookn "); printf("D ==> Display data about all booksn "); printf("F ==> Find and show a bookn "); printf("Enter [R,D,F] or [Q] to Quit: "); }
47. 47. Using functions with Menu void main(void) { char opt; menu(); opt=getchar(); do { switch (opt) { case 'r'| R': Register(); break; case 'f'|'F': Find(); break; case 'd'|'D': Show_data(); break; case 'd'|'D': break(); default: menu(); opt=getchar();break; } }while (opt != 'q' && opt != 'Q'); }
48. 48. Example Pseudo-code include<stdio.h> stdio.h # include<stdio.h> {worse=# typedef enum {worse=-1, bad=0, good=1, best=2} credit; /* Some global constant definitions, if required ... */ /* Start of function defs */ find_disp(); void register();void list();void find_disp(); void delete();void change();int get_option(); // End of function Defs /* End of function Defs */ /* Start of main(), Action definitions */ int main() { /* Some local variable and constant defs */ short int opt; do { opt=get_option(); switch(opt) { case 1: register(); break; case 2: list(); break; find_disp(); case 3: find_disp(); break; case 4: delete(); break; case 5: change(); break; case 6: exit(); /* exit the loop, hence the program */ } } while(1); /* End of while */ return 0; } /* End of main() */
49. 49. C Programming
50. 50. Recursion Recursion = a function calls itself as a function for unknown times. We call this recursive call n −1 su m =∑ i for (i = 1 ; i <= n-1; i++) sum++; i =1 int sum(int n) { if (n <= 1) Iterative version return 1 Recursive version else return (n + sum(n-1)); }
51. 51. Recursive function Compute this function f = 2 f ( x − 1) + x int f( int x ) { if( x == 0 ) return 0; else return 2 * f( x - 1 ) + x * x; } 2
52. 52. Kth Fibonacci Numbers F 0 = 0 , F 1 =1, a n d , F i = F i − 1 + F i − 2 For → i > 1 n 0 =1 n 1 =1 n 2 = n 1 + n 0 + 1 =1 + 1 + 1 = 3 n 3 = n 2 + n1 + 1 = 3 + 1 + 1 = 5 n 4 = n3 + n 2 + 1 =5 + 3 + 1 = 9 n5 =n4 + n3 + 1 = 9 + 5 + 1 = 1 5 n 6 = n 5 + n 4 + 1 =1 5 + 9 + 1 = 2 5 n7 =n6 + n5 + 1 =2 5 + 1 5 + 1 = 4 1 n8 =n7 + n6 + 1 =4 1 + 2 5 + 1 = 6 7
53. 53. kth Fibonacci Numbers Binary recursion int BinaryFib(k) { // Input: An integer k // Output: The kth Fibonacci number if (k <= 1) then return k ; else return BinaryFib(k-1)+BinaryFib(k-2); }
54. 54. Recursion Calculate factorial (n!) of a positive integer: n! = n(n-1)(n-2)...(n-n-1), 0! = 1! = 1 0! =1, n ! = n((n − 1)!)⋯ ∀(n > 0) int factorial(int n) { if (n <= 1) return 1; else return (n * factorial(n-1)); }
55. 55. Summary of Conditional Operators int x=0, y=10, w=20, z, T=1, F=0; z = (x == 0); /*** logical operator; result --> 0 or 1 z = (x = 0); /*** assignment operator; result --> ***/ ***/ z = (x == 1); z = (x = 15); z = (x != 2); z = (x < 10); z = (x <= 50); z = ((x=y) < 10); /*** performs assignment, compares with 10 ***/ z = (x==5 && y<15); z = (x==5 && y>5 && w==10); z = (x==5 || y>5 && w==10); z = (T && T && F && x && x); /*** ==> F; ***/ z = (F || T || x || x); /*** ==> T; ***/ /*** for && and !!, order is specified, stops when result is known, /*** value of x doesn't matter ***/ ***/
56. 56. Summary of the C Operations • Operators same as in C++ and Java: • Arithmetic • int i = i+1; i++; i--; i *= 2; • +, -, *, /, %, • Relational and Logical • <, >, <=, >=, ==, != • &&, ||, &, |, ! • Syntax same as in C++ and Java: • • • • • • if ( ) { } else { } while ( ) { } do { } while ( ); for(i=1; i <= 100; i++) { } switch ( ) {case 1: … } continue; break;
57. 57. Arrays & Pointers
58. 58. One-Dimensional Arrays #include <stdio.h> void main(void) { int number[12]; /* 12 cells, one cell per element */ int index, sum = 0; /* Always initialize arrays before use! */ for (index = 0; index < 12; index++) { // cells are numbered from 0 to 11 not from 1 to 12! number[index] = index; } for (index = 0; index < 12; index = index + 1) { sum += number[index]; /* sum array elements */ } return; }
59. 59. Array Initialization int a[10] = { 1,2,3,4,5,6,7,8,9,10 }; int b[10] = {0}; İnitialize all elements to zero Character arrays that hold strings allow shorthand initializations, like char str[9] = "I like C"; Or you can use this: char str[9] = { 'I',' ','l','i','k','e',' ','C','0' };
60. 60. Two-dimensional Arrays col1 col2 col3 col4 ... row1: matrix[0][0] matrix[0][1] matrix[0][2] matrix[0][3] ... row2: matrix[1][0] matrix[1][1] matrix[1][2] matrix[1][3] ... row3: matrix[2][0] matrix[2][1] matrix[2][2] matrix[2][3] ... ... ... ... ... ... rowM: matrix[M][0] matrix[M][1] matrix[M][2] matrix[M][3] void fillTable () { int row, col, maxRow, maxCol; int matrix [maxRow][maxCol]; for (int row = 0; row < maxRow; row++) for (int col = 0; col < maxCol; col++) matrix [row][col] = row + col; } ...
61. 61. Two-dimensional Arrays void fillTable () { int row, col, maxRow, maxCol; int matrix [maxRow][maxCol]; for (int row = 0; row < maxRow; row++) for (int col = 0; col < maxCol; col++) matrix [row][col] = row + col; } Outer loop executes (with row = 0) first, the inner loop fills in the values in the first row of matrix, namely: matrix[0][0] = row + col, matrix[0][1] = row + col, matrix[0][2] = row + col, and matrix[0][3] = row + col. The next round of the outer loop fills in the second row of matrix. The third and final round of the outer loop fills in the final row of matrix.
62. 62. Printing contents of 2-dimensional Arrays void displayTable () { int row, col; for ( row = 0; row < maxRow; row ++) { for (col = 0; col < maxCol; col ++) { printf("%dn",matrix [row][col]); } printf("n"); } }
63. 63. Initialization of Two-dimensional Arrays Two-dimensional arrays are initialized in the same way as the one-dimensional arrays, e.g., int myArray[6][2] = { 1,1, 2,4, 3,9, 4,16, 5,25, 6,36 };
64. 64. More Arrays • Array of Strings char name[6]; name = {‘C’,’S’,’4’,’1’,’4’,’0’}; /* ’0’= end of string */ printf("%s", name); /* print until ‘0’ */ – Functions to operate on strings • strcpy, strncpy, strcmp, strncmp, strcat, strncat, etc... • #include <strings.h> at program start • Multi-dimensional arrays int points[3][4]; points [1][3] = 12; /* NOT points[3,4] */ printf("%d", points[1][3]);
65. 65. More Array of Strings #include <stdio.h> int main() { char msg[10]; /* array of 10 chars */ char *p; /* pointer to a char */ char msg2[]="Hello"; /* msg2 = ‘H’,’e’,’l’,’l’,’o’,’0’ */ msg = "Hello"; /* ERROR. msg has a const address.*/ p = "Hello"; /* address of "Merhaba" goes into p */ msg = p; /* ERROR. Message has a constant address. */ /* cannot change it. */ p = msg; /* OK */ p[0] = ‘H’, p[1] = ‘i’,p[2]=‘0’; /* *p and msg are now "Hi" */ return 0; }
66. 66. Iterative sum of array contents int IterativeArraySum(int A[], int n) { // Input: An integer array A and an integer n (size) // Output: The sum of the first n integers if (n == 1) return A[0]; else while (n != 0) { sum = sum + A[n]; n = n – 1; } return sum; }
67. 67. Recursive sum of array contents int RecursiveArraySum(int A[], int n) { // Input: An integer array A and an integer n (size) // Output: The sum of the first n integers if (n == 1) return A[0]; else return RecursiveArraySum(A,n-1) + A[n-1]; }
68. 68. Iterative Reversing of Array void IterativeReverseArray(int A[], int i,int n) { // Input: An integer array A and an integers i and n // Output: The reversal of n integers in A starting at index i while (n > 1) { swap (A[i], A[i+n-1]); i =i +1; n = n-2; } return; }
69. 69. Recursive Reversing of Array void ReverseArray(int A[], int i, int n) { // Input: An integer array A and an integers i and n // Output: The reversal of n integers in A starting at index i if (n > 1) { swap (A[i], A[i+n-1]); ReverseArray(A, i+1, n-2); } return; }
70. 70. Higher-Order Recursion Making recursive calls more than a single call at a time. int BinarySum(int A[], int i,int n) { // Input: An integer array A and an integers i and n // Output: The sum of n integers in A starting at index i if (n == 1) { return A[i]; return BinarySum(A,i,[n/2])+BinarySum(A,i+[n/2],[n/2]); }
71. 71. Array Operations: Searching 2 10 25 11 34 22 1 i int score[5] tmp max=score[i]; for (i = 0; i < CLASS_SIZE; ++i) { if (max <= score[i] ) { max = score[i]; } }
72. 72. Array Operations: Searching #include <stdio.h> #define CLASS_SIZE 10 int main(void) { int i, score[CLASS_SIZE], max; printf("Input %d How many scores: ", CLASS_SIZE); for (i = 0; i < CLASS_SIZE; ++i) { scanf("%d", &score[i]); } max=score[i]; for (i = 0; i < CLASS_SIZE; ++i) { if (max <= score[i] ) { max = score[i]; } } printf("nMax is: %dnn", max); return 0; }
73. 73. Array Operations: Sorting 2 10 25 11 34 22 int score[5] 3 i j-1 j tmp 1 for (i = 0; i < CLASS_SIZE - 1; ++i) for (j = CLASS_SIZE - 1; j > i; --j) if (score[j-1] < score[j]) { tmp = score[j-1]; score[j-1] = score[j]; score[j] = tmp; }
74. 74. Array Operations: String Sorting void string_sort(char *s[]){ char tmp; int i, j, length; length=string_length(s); for(i=0; i<length-1; i++) { for (j=i+1; j<length; j++) { if (strcmp(*s[i], *s[j]) == 0) { tmp=s[i]; s[i]=s[j]; s[j]=tmp; } } } } int string_length(char str[]){ int i; for(i=0; i<80; i++) { if(str[i]=='0') return(i); } }
75. 75. Array Operations: Sorting #include <stdio.h> #define CLASS_SIZE 5 int main(void) { int i, j, score[CLASS_SIZE], sum = 0, tmp; printf("Input %d scores: ", CLASS_SIZE); for (i = 0; i < CLASS_SIZE; ++i) { scanf("%d", &score[i]); sum += score[i]; } for (i = 0; i < CLASS_SIZE - 1; ++i) /* bubble sort */ for (j = CLASS_SIZE - 1; j > i; --j) if (score[j-1] < score[j]) { /* check the order */ tmp = score[j-1]; score[j-1] = score[j]; score[j] = tmp; } printf("nOrdered scores:nn"); for (i = 0; i < CLASS_SIZE; ++i) printf(" score[%d] =%5dn", i, score[i]); printf("n%18d%sn%18.1f%snn", sum, " is the sum of all the scores", (double) sum / CLASS_SIZE, " is the class average"); return 0; }
76. 76. Read in Words void main(void) { char word[32]; /* work space keeps only one word*/ char *w[N]; int n; int i; /* an array of pointers to store words*/ /* number of words to be sorted */ printf("Enter wordsn"); for (i = 0; scanf("%s", word) == 1 ; ++i) { if (i >= N) break; if (strlen(word) >= 32) break; w[i] = (char *)calloc(strlen(word) + 1, sizeof(char)); /* w[i] = new char[strlen(word) + 1]; */ if (w[i] == NULL) printf ("Empty Word ...n"); strcpy(w[i], word); } n = i; for (i = 0; i < n; ++i) printf("%sn", w[i]); /* Display words */ }
77. 77. Sort Words void sort_words(char *w[], int n) /* sort n words */ { int i, j; for (i = 0; i < n; ++i) for (j = i + 1; j < n; ++j) if (strcmp(w[i], w[j]) > 0) swap(&w[i], &w[j]); } void swap(char **p, char **q) { char *tmp; tmp = *p; *p = *q; *q = tmp; }
78. 78. POINTERS
79. 79. Pointers!!!! • Pointer = variable containing address of another variable int x = 5; /* data variable */ int y = 7; /* data variable */ int *ptr = &x; /* & = address operator */ (&x) 1000 x=5 y=7 (&y) 1004 1200 5 7 ptr x y 1200 10 7 1000 (&ptr) 1200 *ptr = 10; (&x) 1000 (&y) 1004 (&ptr) 1200 x = 10 y=7 ptr ptr = &x = 1000 x y
80. 80. Pointers - 1 float f; float *f_addr; f /* data variable */ /* pointer variable */ f_addr any float ? ? ? 4300 4304 any address f_addr = &f; /* & = address operator */ f f_addr ? 4300 4300 4304
81. 81. Pointers - 2 *f_addr = 3.2; f /* indirection operator */ f_addr 3.2 4300 4300 4304 float g=*f_addr; /* indirection:g is now 3.2 */ f = 1.3; f f_addr 1.3 4300 4300 4304
82. 82. Arrays and Pointers An array name by itsels is an address or pointer value! #define N 100 int a[N], i, *p, *q, sum = 0; p = a; /* is equivalent to p = &a[0] */; p = a + 1; /* is equivalent to p = &a[1] */; int a[i] /* is equivalent to *(a + i) */; Here *(a + i) is the dereferencing of the expressin a + i that points i elements positions past in a p = a; /* points to the base of array a */ q = p + 1; /* equivalent to q =&a[1] */ printf("%dn", q – p); printf("%dn", (int) q - (int) p); for (p = a; p <&a[N]; ++p) sum += *p; for (i = 0; i < N; ++i) sum += *(a + i);
83. 83. Pointer Arithmetic int main(int argc, char* argv[]){ double a[2], *p, *q; p = a; /* points to the base of array a */ q = p + 1; /* equivalent to q =&a[1] */ printf("=============================n"); printf(" p = %d", p); printf("n q = %d", q ); printf("n q - p = %d", q - p); printf("n q - p = %dn", (int) q - (int) p); printf(" &a[0] = %d", &a[0] ); printf("n &a[1] = %d &a[1] ); }
84. 84. Pointer Example #include <stdio.h> void main(void) { int j; int *ptr; ptr=&j; /* initialize ptr before using it */ /* *ptr=4 does NOT initialize ptr */ *ptr=4; j=*ptr; } /* j <- 4 assign 4 to j*/ /* j <- ??? Ask students*/
85. 85. Pointers: Summary int a = 10, b = 2, *p; p = &a; // p is assigned address of a b = *p; // b is assigned the value pointed by p b = *p; is equivalent to b = a; •An array name is an address or a pointer value An •Arrays and pointers can be subscripted: Arrays int A[10], *p; int i = 0; A[0]=23; p=A; int b = A[i]; is equivalent to int b = *(A + 0); int c = p[i]; is equivalent to int c = *(p + i); p = A; is equivalent to p = &A[0]; p = A + 1; is equivalent to p = &A[1];
86. 86. Pointers: Summary All will equally sum the array ellements: 1) for (p = a; p <&a[N]; ++p) sum += *p; 2) for (i = 0; i < N; ++i) sum += *(a + i); 3) p = a; for (i = 0; i < N; ++i) sum += p[i];
87. 87. Call-by-value Whenever variables are passed as arguments to a function, their values are copied to the function parameters: int main(){ int a=20; int b=30; swap (a, b) printf("%d %d: ", a, b); return 0; } void swap(int x, y) { int tmp; tmp=x; x=y; y=tmp; }
88. 88. Pointers & Call-by-reference Pointers are passed as arguments to a function, their addresses are assigned to the function parameters defined as pointers: int main(){ int a=20; int b=30; swap (&a, &b) printf("%d %d: ", a, b); return 0; } void swap(int *x, int *y) { int tmp; tmp = *x; // get value pointed by x. *x = *y; // assign value pointed by y to x *y = tmp; }
89. 89. Why pointer arguments?! #include <stdio.h> void swap(int, int); int main() { int num1 = 5, num2 = 10; swap(num1, num2); printf("num1 = %d and num2 = %dn", num1, num2); return 0; } void swap(int n1, int n2) { /* passed by value */ int temp; temp = n1; n1 = n2; n2 = temp; }
90. 90. Why pointer arguments? This is why #include <stdio.h> void swap(int *, int *); int main() { int num1 = 5, num2 = 10; swap(&num1, &num2); printf("num1 = %d and num2 = %dn", num1, num2); return 0; } void swap(int *n1, int *n2) { /* passed and returned by reference */ int temp; temp = *n1; *n1 = *n2; *n2 = temp; }
91. 91. Arrays as Function Arguments #include <stdio.h> void init_array(int array[], int size) ; void main(void) { int list[5]; init_array(list, 5); for (i = 0; i < 5; i++) printf("next:%d", array[i]); } void init_array(int array[], int size) { /* why size ? */ /* arrays ALWAYS passed by reference */ int i; for (i = 0; i < size; i++) array[i] = 0; }
92. 92. More pointers int month[12]; /* month is a pointer to base address 430*/ month[3] = 7; /* month address + 3 * int elements => int at address (430+3*4) is now 7 */ ptr = month + 2; /* ptr points to month[2], => ptr is now (430+2 * int elements)= 438 */ ptr[5] = 12; /* ptr address + 5 int elements => int at address (434+5*4) is now 12. Thus, month[7] is now 12 */ ptr++; /* ptr <- 438 + 1 * size of int = 442 */ (ptr + 4)[2] = 12; /* accessing ptr[6] i.e., array[9] */ • Now month[6], *(month+6), (month+4)[2], ptr[3], *(ptr+3) are all the same integer variable.
93. 93. Pointer Example - argc and argv parameters #include <stdio.h> /* program called with cmd line parameters */ void main(int argc, char *argv[]) { int ctr; for (ctr = 0; ctr < argc; ctr = ctr + 1) { printf("Argument #%d is -> |%s|n", ctr, argv[ctr]); } /* ex., argv[0] == the name of the program */ }
94. 94. Pointers to function int int int int func(); /*function returning integer*/ *func(); /*function returning pointer to integer*/ (*func)(); /*pointer to function returning integer*/ *(*func)(); /*pointer to func returning ptr to int*/ • Advantage ? more flexibility
95. 95. Pointer to function - Example #include <stdio.h> void myproc (int d); void mycaller(void (* f)(int), int param); void main(void) { myproc(10); /* call myproc with parameter 10*/ mycaller(myproc, 10); /* and do the same again ! */ } void mycaller(void (* f)(int), int param){ (*f)(param); /* call function *f with param */ } void myproc (int d){ . . . } /* do something with d */
96. 96. C Programming
97. 97. Container Data types: Structures #include <stdio.h> struct birthday{ int month; int day; int year; }; int main() { struct birthday mybday; mybday.day=1; mybday.month=1; mybday.year=1977; printf("I was born on %d/%d/%d", birth.day, birth.month, birth.year); return 0; }
98. 98. Structures Cont’d struct { char name[41]; int age; float height; struct { int month; int day; int year; } birth; } person ; /* embedded or nested structure */ struct person me; me.birth.year=1977;……… struct person class[60]; /* array of info about everyone in class */ class[0].name="CS206"; class[0].birth.year=1971;……
99. 99. Accessing Members of Structures struct exp { char c; int i; float arr[10]; }; struct exp exp1; struct exp *expPtr; exp1.c = ‘A’; i = 20; prinf("%c%d ", exp1.c, exp1.i); expPtr->c=‘B’; expPtr->i=30; printf("%c%d ", expPtr->c, expPtr->i); expPtr = &exp1; printf("%c%d ", expPtr->c, expPtr->i); printf("%c%d ", (*expPtr).c, (*expPtr).i);
100. 100. enum - enumerated data types #include <stdio.h> enum month{ JANUARY, FEBRUARY, MARCH APRIL /* /* /* /* like like like like #define #define #define #define JANUARY 0 */ FEBRUARY 1 */ MARCH 2 */ APRIL 2 */ }; /* JANUARY is the same as month.JANUARY */ /* alternatively, …. */ enum month{ JANUARY = 1, FEBRUARY = 2, MARCH }; /* /* /* like like … */ #define #define JANUARY 1 */ FEBRUARY 2 */
101. 101. typdef : Synonym for a data type • • Easier to remember For creating clean and tidy codes typedef int numbers; typdef float kesirli; numbers a_number; /* same as int a_number; */ kesirli fi = 3.14 typedef struct person typedef struct person // struct person me; Person me; PrsPtr you; typedef struct person Personptr ptrtome; Person; *PrsPtr; /* same as struct person me; */ *Personptr; /* same as struct person *ptrtome;*/
102. 102. Memory layout of programs 0 Header info 100 Code 400 all malloc()s Data - Heap Dynamic memory Data - stack Local memory + function call stack 560 1010 all normal vars 1200
103. 103. Dynamic Memory allocation • Explicit allocation and de-allocation #include <stdio.h> void main(void) { int *ptr; /* allocate space to hold an int */ ptr = malloc(sizeof(int)); /* Put something into the space */ *ptr=4; free(ptr); /* free up the allocated space */ char *w[10]; /* Space for 10 words: pointer array */ char word[12] w[i] = calloc(strlen(word) + 1, sizeof(char)); /* allocate space to hold a word (string) */ }
104. 104. Advanced Structures
105. 105. Structures: Summary #include <stdio.h> struct birthday{ int month; int day; int year; }; int main() { struct birthday mybday; /* Create structure */ mybday.day=1; mybday.month=1; mybday.year=1977; printf("I was born on %d/%d/%d", birth.day, birth.month, birth.year); return 0; }
106. 106. Array of Structures struct person{ char name[41]; int age; float height; struct { int month; int day; int year; } birth; }; /* embedded structure (iç içe)*/ struct person me; me.birth.year=1977;……… struct person class[2]; /* array of info about everyone in class */ class[0].name="Gül Nihal"; class[0].birth.year=1971; Class[1].name="Mustafa Kemal"; class[0].birth.year=1883;……
107. 107. Passing/Returning a structure /* pass struct to functions by value */ void display_year_1(struct birthday mybday) { printf("I was born in %dn", mybday.year); } /* - inefficient: why ? */ . . . . /* pass struct to functions by reference */ void display_year_2(struct birthday *pmybday) { printf("I was born in %dn", pmybday->year); /* warning ! ‘->’, not ‘.’, after a struct pointer*/ } . . . . /* return struct by value */ struct birthday get_bday(void){ struct birthday newbday; newbday.day=02; newbday;newbday.month=08; newbday.year=1971; return newbday; }
108. 108. C Programming
109. 109. File Input Output Operations File I/O File I/O: Writing Data to Files Reading Data From Files
110. 110. File Operations 1) Open the file 2) Do operations on the File 3) Close the file
111. 111. Files in C • In C, each file is simply a sequential stream of bytes. C imposes no structure on a file. • A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a file handle is associated with the file. • Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block.
112. 112. Files in C • The statement: FILE *fptr1, *fptr2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. • Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable.
113. 113. Opening Files • The statement: fptr1 = fopen ( "mydata", "r" ) ; would open the file mydata for input (reading). • The statement: fptr2 = fopen ("results", "w" ) ; would open the file results for output (writing). • Once the files are open, they stay open until you close them or end the program (which will close all files.)
114. 114. Testing for Successful Open • If the file was not able to be opened, then the value returned by the fopen routine is NULL. • For example, let's assume that the file mydata does not exist. Then: FILE *fptr1 ; fptr1 = fopen ( "mydata", "r") ; if (fptr1 == NULL) { printf ("File 'mydata' could not open.n") ; }
115. 115. Parameters for FILE access mode Below are modes of opening a file: "w" open write to text file "r" read from text file "a" append to end of file "wb" write binary "rb" read binary "ab" binary appending "r+" Text file read and write "w+" Text file write and read
116. 116. Reading From Files • In the following segment of C language code: int a, b ; FILE *fptr1, *fptr2 ; fptr1 = fopen ( "mydata", "r" ) ; fscanf ( fptr1, "%d%d", &a, &b) ; the fscanf function would read values from the file "pointed" to by fptr1 and assign those values to a and b.
117. 117. End of File • The end-of-file indicator informs the program when there are no more data (no more bytes) to be processed. • There are a number of ways to test for the end-of-file condition. One is to use the feof function which returns a true or false condition: fscanf (fptr1, "%d", &var) ; if ( feof (fptr1) ) { printf ("End-of-file encountered.n) ; }
118. 118. End of File • There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf function: int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == EOF ) { printf ("End-of-file encountered.n) ; }
119. 119. Writing To Files • Likewise in a similar way, in the following segment of C language code: int a = 5, b = 20; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; fprintf ( fptr2, "%d %dn", a, b ) ; the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2.
120. 120. Closing Files • The statements: fclose ( fptr1 ) ; fclose ( fptr2 ) ; will close the files and release the file descriptor space and I/O buffer memory.
121. 121. Reading and Writing Files #include <stdio.h> void main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ; fclose (outfile) ; infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf ("%6.2f%2d%5.2fn", a, b, c) ; printf ("%6.2f,%2d,%5.2fn", e, f, g) ; } 12345678901234567890 **************************** 13.72 5 6.68 13.72, 5, 6.68
122. 122. More Lines in a File? • The last assignment requires us to read several lines of some information from a file and write it out to the screen and to a file. (Sounds repetitive, doesn't it?) • Simple repetitive tasks are easily performed with a "for" or "while" loop. For example: int i, ii = 0; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; for ( i = 1 ; i <= n ; i++ ) { fprintf ( fptr2, "%d %dn", a, b ) ; } fclose (fptr);
123. 123. Exp: Change the case of letters in a file #include <stdio.h> #include <stdlib.h> #define BUFSIZE 1024 int main(int argc, char *argv[]) { char mybuf[BUFSIZE], *p; int in_fd, out_fd, n; in_fd = open(argv[1], "r"); out_fd = open(argv[2], "w"); while ((n = read(in_fd, mybuf, BUFSIZE)) > 0) { for (p = mybuf; p - mybuf < n; ++p) if (islower(*p)) *p = toupper(*p); else if (isupper(*p)) *p = tolower(*p); write(out_fd, mybuf, n); } close(in_fd); close(out_fd); return 0; }
124. 124. Change the case of letter in a file The previous code (conv.c) will convert the content of a file having lowercase letters to corresponding capital (uppercase) letters Do the followings on UNIX/linux: gcc –o toupper conv.c ./toupper infile.txt outfile.txt
125. 125. Replicate a file with caps fp = fopen(argv[1], "r+"); #include <ctype.h> tmp_fp = tmpfile(); #include <stdio.h> while ((c = getc(fp)) != EOF) #include <stdlib.h> putc(toupper(c), tmp_fp); int main(int argc, char *argv[]) { rewind(tmp_fp); int c; FILE *fp, *tmp_fp; fprintf(fp, "---n"); if (argc != 2) { while ((c = getc(tmp_fp)) != EOF) printf("n%s%s%snn%snn", "Usage: " putc(c, fp); argv[0], " filename"); return 0; exit(1); } } if (fp=fopen(argv[1],"rw") == NULL) { printf("Cannot open %s - bye!n", argv[1]); exit(1); }
126. 126. Double Space a File #include <stdio.h> #include <stdlib.h> void double_space(FILE *, FILE *); void prn_info(char *); int main(int argc, char **argv) { FILE *ifp, *ofp; if (argc != 3) { prn_info(argv[0]); exit(1); } ifp = fopen(argv[1], "r"); /* open for reading */ ofp = fopen(argv[2], "w"); /* open for writing */ double_space(ifp, ofp); fclose(ifp); fclose(ofp); return 0; }
127. 127. Double Space a File (cont’ d) void double_space(FILE *ifp, FILE *ofp) { int c; while ((c = getc(ifp)) != EOF) { putc(c, ofp); if (c == 'n') putc('n', ofp); /* found a newline - duplicate it */ } } void prn_info(char *pgm_name){ printf("n%s%s%snn%s%snn", "Usage: ", pgm_name, " infile outfile", "The contents of infile will be double-spaced ", "and written to outfile."); }
128. 128. C Programming
129. 129. The C Preprocessor • Preprocessors extend power of C • Lines starting with # are preprocessing directives. • #define macro facility generates inline code in place of functions. They provide fatser execution. Examples: • #include <stdio.h> • #include "filename" • #define identifier token_string • #define (identifier,…, identifier) token_string
130. 130. The Use of #define • • • • • • • • #define PI 3.14159 #define size 1000 #define seconds_per_day (60*60*2) #define EQ == #define LT < #define LTE <= #define NOT != Example: int main(){ int i=0 while (i NOT 5){ printf ("hello!"); i++; } return 0; }
131. 131. Macros • Macros are small codes that can be used instead of functions. • They execute very fast! • Syntax: #define (identifier,…, identifier) token_string #define sq(x) ((x) * (x)) #define min(x,y) (((x) < (y)) ? (x) : (y)) How to call these macros ? int u,v,m,w = 6; sq(7 + w) expands to ((7 + 6) * (7 + 6)) sq(sq(5)) expands to what? scanf("%d%d", &u,&v); m = min(u,v);
132. 132. Macros With Arguments #include <stdio.h> #include <stdlib.h> #include <time.h> #define random_char() (rand() % 26 + 'a') #define random_int(x) (rand() % x) #define max(x,y) (((x) > (y)) ? (x) : (y)) #define min(x,y) (((x) < (y)) ? (x) : (y)) int main() { char a; int r; srand(time(NULL)); a = random_char(); r = random_int(100); printf("Random char = %ct Random int = %d n",a,r); printf("Min (%d and %d) = %d n",r, a, min(r,a)); printf("Max (%d and %d) = %d n", r, a, max(r,a)); return 0; }
133. 133. Some Macros in stdio.h and ctype.h • In the file ctype.h we have • #define getchar() getc(stdin) • #define putcahr() putc((c),stdout) Your code should contain this at the top #include <ctype.h>
134. 134. More Usefull Macros Macro Nonzero (true) returned if isalpha(c) isupper(c) islower(c) isdigit(c) isalnum(c) isxdigit(c) isspace(c) ispunct(c) isprint(c) isgraph(c) isascii(c) c is letter c is an uppercase letter c is lowercase letter c is a digit c is a letter or digit c is a hexadecimal digit c is a white space character c is a punctation character c is a printable character c is printable but not a space c is an code
135. 135. Conversion Call to function Value returned toupper(c) Uppercase value of c tolower(c) Lowercase value of c toascii(c) ASCII value
136. 136. Intro to Algorithms & Data Structures
137. 137. User Defined Data Types • All related data are collected in conglomerate structures • Many types of conglomerate structures: – – – – – Stacks Queues (FIFO = First in First Out) Trees Vectors Linked Lists • • • Single Double Circle
138. 138. C Programming
139. 139. What Are Stacks ? Overflow MAX PUSH POP 0 -1 Underflow
140. 140. Stacks const int MaxStack = 1024; const char EmptyFlag = '0'; char items [ MaxStack ]; int top; enum { FullStack = MaxStack, EmptyStack = -1 }; /* Required tack functions are: */ push(char); char pop(); bool empty(); bool full();
141. 141. Stack: Example const int MaxStack = 1024; const char EmptyFlag = '0'; char items [ MaxStack ]; int top; enum { FullStack = MaxStack, EmptyStack = -1 }; void push(char); char pop(); bool empty(); bool full(); void push(char c){ if (full()) return; items[++top] = c; } char pop(){ if (empty()) return EmptyFlag; return items[top--]; }
142. 142. Stacks: Example bool full() { if (top + 1 == FullStack) { cerr << "Stack Full at " << MaxStack << endl; return true; } return false; } bool empty(){ if (top == EmptyStack) { cerr <<"Stack empty" <<endl; return true; } return false; } void main(void){ push(‘A’); push(‘B’); pop();pop(); pop(); }
143. 143. C Programming
144. 144. Linked Lists • Nodes: Represent data storage points • Pointers: are used to handle nodes A node Head next int a char c char *name = "kerem" Tail next NULL
145. 145. Linked List Operations • • • • • • • • Creating a list element, Prepending elements on top of lists, Inserting elements into lists, Appending to end of lists, Finding/searching elements in the list Sorting elements, Deleting, Moving elements around in the list.
146. 146. Linked List Types Single linked lists Head next A node int a char c next char *name = "kerem" Tail next NULL Double linked lists A node previous previous Head Tail next next next NULL Circle linked lists A node Head next int a char c char *name = "kerem" Tail next
147. 147. Linked Lists struct list { int data; struct list data next *next; }a; struct list a, b,c a.data = 1; b.data=1;c.data=3; 1 next 2 next 3 next a.next=b.next=c.next = NULL; NULL a.next = &b; b.next =&c; 1 next 2 next 3 next NULL
148. 148. Linear Linked Lists #include <assert.h> #include <stdio.h> #include <stdlib.h> #define MAXLINE typedef char 100 DATA; /* will use char in examples */ struct linked_list { DATA d; struct linked_list *next; }; typedef struct linked_list typedef ELEMENT *LINK; ELEMENT;
150. 150. Creating a List: 1st Declare the List #include <assert.h> #include <stdio.h> #include <stdlib.h> #define MAXLINE typedef char 100 DATA; /* will use char in examples */ struct linked_list { DATA d; struct linked_list *next; }; typedef struct linked_list typedef ELEMENT *LINK; ELEMENT;
151. 151. Creating a List: Using Iteration #include "list.h" LINK s_to_l(char s[]) { LINK head = NULL, tail; int i; if (s[0] != '0') { /* first element */ head = malloc(sizeof(ELEMENT)); head -> d = s[0]; tail = head; for (i = 1; s[i] != '0'; ++i) { /* add to tail */ tail -> next = malloc(sizeof(ELEMENT)); tail = tail -> next; tail -> d = s[i]; } tail -> next = NULL; /* end of list */ } return head; }
152. 152. Creating a List: Using Recursion #include "list.h" LINK string_to_list(char s[]) { LINK head; if (s[0] == '0') /* base case */ return NULL; else { head = malloc(sizeof(ELEMENT)); head -> d = s[0]; head -> next = string_to_list(s + 1); return head; } }
153. 153. Count Elements of a List: Using Iteration #include "list.h" int count_list(LINK head) { int count; for (; head != NULL; head = head -> next) ++count; return count; }
154. 154. Count Elements of a List: Using Recursion #include "list.h" int count_list(LINK head) { if (head == NULL) return 0; else return(1 + count_list(head -> next)); }
155. 155. Print Elements in a List: Using Iteration #include "list.h" void wrt_list(LINK head) { LIST p; if (head == NULL) printf("NULL list"); else for (p = head; p != NULL; p = p -> next) putchar(p -> d); }
156. 156. Print Elements in a List: Using Recursion #include "list.h" void wrt_list(LINK head) { if (head == NULL) printf("NULL list"); Else { printf("%c ", head -> d); wrt_list(head ->next); } }
157. 157. Insertion of Elements in a List #include "list.h" Void insert(LINK p1, LINK p2, LINK q) { Assert (p1-> next == p2); initially p1->next = q; q->next = p2; } p1 p2 A C next next NULL q B next
158. 158. Delete Elements in a List: Using Iteration #include "list.h" void delete(LINK head) { LIST p; if (head == NULL) printf("NULL list"); else for (p = head; p != NULL; p = p -> next) free(p); }
159. 159. Delete Elements in a List: Recursively #include "list.h" void elete_list(LINK head) { if (head != NULL) { delete_list(head ->next); free(head); } }
160. 160. C Programming
161. 161. A linked list implementation of a queue queue Queue: First-In-First-Out (FIFO) data structure cnt front rear elem elem data next elem data next daat next NULL
162. 162. The header file: queue.h #define EMPTY 0 #define FULL 10000 typedef unsigned int data; typedef enum {false, true} boolean; struct elem { data /* an element in the queue */ d; struct elem *next; }; typedef struct elem elem; struct queue { int cnt; /* a count of the elements */ elem *front; /* ptr to the front element */ elem *rear; /* ptr to the rear element */ }; typedef struct queue queue;
163. 163. The header file: queue.h (cont’ d) void initialize(queue *q); void enqueue(data d, queue *q); data dequeue(queue *q); data front(const queue *q); boolean empty(const queue *q); boolean full(const queue *q);
164. 164. Basic queue routines (cont’ d) #include "queue.h" void initialize(queue *q){ q -> cnt = 0; q -> front = NULL; q -> rear = NULL; } data dequeue(queue *q){ data d; elem *p; d = q -> front -> d; p = q -> front; q -> front = q -> front -> next; q -> cnt--; free(p); return d; }
165. 165. Basic queue routines (cont’ d) void enqueue(data d, queue *q){ elem *p; p = malloc(sizeof(elem)); p -> d = d; p -> next = NULL; if (!empty(q)) { q -> rear -> next = p; q -> rear = p; } else q -> front = q -> rear = p; q -> cnt++; }
166. 166. Basic queue routines (cont’ d) data front(const queue *q){ return (q -> front -> d); } boolean empty(const queue *q){ return ((boolean) (q -> cnt == EMPTY)); } boolean full(const queue *q){ return ((boolean) (q -> cnt == FULL)); }
167. 167. C Programming