1 / 81

The Introduction of C

The Introduction of C. By Hu,Huan . Contents. A taste of C Data types Input & output Control Statement Functions Arrays Pointers Structures and Unions Data File. A Taste of C. The following code shows that how to print the area of circle in C:

locke
Download Presentation

The Introduction of C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The Introduction of C By Hu,Huan

  2. Contents • A taste of C • Data types • Input & output • Control Statement • Functions • Arrays • Pointers • Structures and Unions • Data File

  3. A Taste of C The following code shows that how to print the area of circle in C: #include<stdio.h> /* stdio.h - standard buffered input/output*/ /* In a traditional C language, we use main(), but since we are in a C++ IDE int main() must be used*/ int main() /* main function*/ { float radius, area; printf("Radius = ? "); scanf("%f", &radius); area = 3.14159 * radius * radius; printf("Area = %f", area); system("pause"); }

  4. C data types Constant: C language define: #define PRICE 30 /*notice that no ‘=’, no ‘;’*/ Variable: C language define: [signed] int unsigned [int] [signed] short [int] unsigned short [int] [signed] long [int] unsigned long [int] float double long double char Java data types Constant: Java language define: final int PRICE = 100; Variable: Java language define: int short byte long float double char Boolean Data Types

  5. Input&Output In the previous example we showed in the a taste of c session, there is a row of code: # include <stdio.h> /* standard input & output library*/ /* Every I/O, except printf and scanf, must invoke this statement, otherwise it will occur a compile error */

  6. Input&Output • I/O with char data: putchar() function: e.g. #include <stdio.h> /* stdio.h - standard buffered input/output*/ main() { char a,b,c; a = ’B’; b=’O’; c=’Y’; putchar(a); putchar(b); putchar(c); }

  7. Input&Output get char() function //A function for input char data e.g. #include <stdio.h> main() { char C; c=getchar(); putchar(c); }

  8. Input&Output 2. I/O of general data printf() function // For writing output data In general terms, the printf function is written as printf(control string, arg1, arg2,……, argn) e.g. main() { unsigned int a = 65535; int b = -2; printf(“a = %d,%o,%x,%u\n”,a,a,a,a); /*The first a is output in int type, the second is output in octal int type, the third in hexadecimal int type, the last in unsigned type*/ /*a % followed by a conversion character which indicates the type of the corresponding data item is a standard structure for I/O*/ printf(“a = %d,%o,%x,%u\n”,b,b,b,b); }

  9. Input&Output

  10. Input&Output #include <stdio.h> main() { char line[80]; scanf(“ %[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line); } if the string: NEW YORK CITY is entered from the standard input device when the program is executed, the entire string will be assigned to the array line since the string is comprised entirely of uppercase letters and blank spaces. If the string were written as New York City However, then only the single letter N would be assigned to line, since the first lowercase letter (in this case, e) would be interrupted as the first character beyond the string. It would, of course, be possible to include both uppercase and lowercase characters within the brackets, but this becomes cumbersome!

  11. Input&Output main() { printf(“%3s, %7.2s, %.4s,%-5.3s\n”,”CHINA”,”CHINA” ,”CHINA”,”CHINA”); } output: CHINA,—————CH,CHIN,CHI—— /*’—‘ means a space*/ List of the meanings of the numbers put in front of s: //m,n mean numbers • %s, normal circumstance. • %ms, the output will occupy m spaces, but if the length of the string is longer than the length of the spaces, the whole string will be fully output. • %-ms, if the length of the string is shorted than m, then be fully output, and string will aligned left, the rest right position will be occupied by spaces • %m.ns, the output will occupy m spaces, but only the left n characters of the string will be output, these n characters will occupy the most right positions, and the rest of the positions will be filled by spaces. • %-m.ns, the output will occupy m spaces, but only the left n characters of the string will be output, these n characters will occupy the most left positions, and the rest of the positions will be filled by spaces. (The circumstances are same for input integer, floating number, etc)

  12. Input&Output scanf() function // For Entering input data In general terms, the scanf function is written as scanf(control string, arg1, arg2,……, argn) e.g. main() { int a,b,c; scanf(“%d%f%c”,&a,&b,&c); /*The symbol ‘&’ is an address operator, &a means the address of a in memory*/ printf(“%d,%f,%c\n”,a,b,c); } output: 3 4.0 c /*enter the values of a,b,c. “” mean enter*/ 3,4.0,c /*output values*/

  13. Input&Output *Cautions: • scanf(“%f%d”,a,b); /*This is wrong, for it forget to put the &s in front of a, b*/ • scanf(“%d,%d”, a,b); /*This is legal, but when you enter the number, you must take cautious*/ if input is in this way 3,4 /*legal, you must use commas to isolate the numbers*/ if input is in these following ways 3 4 /*illegal*/ 3:4 /*illegal*/

  14. Input&Output 3. The gets and puts Functions Reading and Writing a Line of Text #include <stdio.h> #include <iostream> Main() { char line[80]; gets(line); puts(line); /*This way is more convenient*/ system(“pause”); } If you enter a string of less than 80 characters in program, it will automatically output them.

  15. Control Statements 1. Branching if-else statement: The standard form of if-else statement is if(condition) {body} else if (condition){body} ….. else{body} /*How familiar it is, it is the mode that works in java!!!*/

  16. Control Statements switch statement: switch(grade) { case ‘A’: printf(“85~100\n”); break; case ‘B’: printf(“70~84\n”); break; case ‘C’: printf(“60~69\n”); break; case ‘D’: printf(“<60\n”); break; default: printf(“error\n”); }

  17. Control Statements 2. Looping goto statement: e.g. 1+2+3+…….+98+99+100 = 5050 main() { int i, sum = 0; i = 1; loop: if (i <= 100) { sum = sum +i; i++; goto loop; } printf(“%d”, sum); } output: 5050

  18. Control Statements *cautions: • Programmers are not encouraged to use goto in their programs, because it will make the reader fell unreadable for the program. • goto label_1; is legel, but goto 123; is not legal which means that goto cannot refer to a data

  19. Control Statements while statement: while(condition){body} e.g. main() { int count, sum = 0; count = 1; while(count<=100) { sum = sum+count; count++; } printf(“%d”,sum); }

  20. Control Statements do-while statement: e.g. main() { int count, sum = 0; count = 1; do { sum = sum+count; count++; } while(count<=100); printf(“%d”,sum); }

  21. Control Statements for statement: e.g. main() { int count, sum = 0; for(int count = 1; count<=100; count++) { sum = sum+count; } printf(“%d”,sum); } // it is similar to while and do-while, I don’t put any resource for for-statement

  22. Functions 1. A simple sample for demonstrating the application of functions #include <stdio.h> char lower_to_upper(char c1) /*function definition*/ { char c2; c2 = (c1>=’a’&& c1<=’z’)?(‘A’ + c1 –‘a’): c1; return(c2); } main() { char lower, upper; printf(“Please enter a lowercase character: ”); scanf(“%c”, &lower); upper = lower_to_upper(lower); /*function use*/ printf(“\nThe uppercase equivalent is %c\n\n”, upper); }

  23. Functions 2. Three way for the function declaration 1. If writing the function under the main function, then it must be declared in the main function before it is to be invoked. eg: main(){ float add(float x, float y); /*the function declaration*/ float a, b, c; scanf(“%f, %f”, &a, &b); c = add(a,b); /*the function application*/ printf(“sum is %f”, c); } float add(float x, float y) /*the function head*/ { /*the body */ float z; z = x+y; return(z); /*note that here the syntax is different from Java*/ /*Java syntax: return z;*/ }

  24. Functions 2. If the function is above the main function, then we don’t need to declare it again in the main function. e.g. float add(float x, float y) /*the function head*/ { /*the body */ float z; z = x+y; return(z); /*note that here the syntax is different from Java*/ } main() { float a, b, c; scanf(“%f, %f”, &a, &b); c = add(a,b); /*the function application*/ printf(“sum is %f”, c); } (Using this way, we can save a line of code for invoking a function, but the disadvantage is that main function will below the defined function that makes the code a little bit hard understanding)

  25. Functions 3. We put the function under the main function, but we can declare them prior to main function. e.g: char letter(char, char); /*function declaration with only the types of parameters*/ float f(float, float); int i(float, float); main() {…} char letter(char c1, char c2) {…} float f(float x, float y) {…} int i(float j, float k) {…} (I personally recommend this way to the programmers, because it is explicit, easy to read(and your count many user created functions in this program).)

  26. Arrays 1. One Dimensional Array The initializing of the one dimensional array: (1)int a[10] = {0,1,2,3,4,5,6,7,8,9}; /*this means a[0] = 0, a[1] =1, …….,a[9]=9*/ • (2)int a[10] = {0,1,2,3,4}; /* = {0,1,2,3,4,0,0,0,0,0}*/ • (3)int a[10] = {0}; /*Set all the elements of the array to be 0*/ • (4)int a[] = {1,2,3,4,5}; /*The system will automatically know that there are 5 elements in this array*/

  27. Arrays The difference of declaring and initializing of an array between Java and C: Java: int[] arr1 = new int[10]; //declaring an array in java int[] arr2 = {1,2,3,4,5}; //initializing an array in java C: int a[10]; /*declaring an array in C*/ int a[] = {1,2,3,4,5} /*initializing an array in C*/

  28. Arrays 2. Two Dimensional Array The initializing of the two dimensional array int a[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12}; int a[3][4] = {{1},{0,6},{0,0,11}}; /*partially initializing*/ int a[][4] = {1,2,3,4,5,6,7,8,9,10,11,12}; /*has the same function as (2)*/ int a[][4] = {{0,0,3},{},{0,10}}; /*partially initializing*/

  29. Arrays Application: main() { int a[2][3] = {{1,2,3},{4,5,6}}; int b[3][2], i, j; printf(“array a:\n”); for (i = 0;i<=1;i++) { for(j = 0; j<=2;j++) { printf(“%5d”, a[i][j]); b[j][i] = a[i][j]; } printf(“\n”); } printf(“array b: \n”); for (i = 0;i<=2;i++) { for(j = 0; j<=1;j++) { printf(“%5d”, b[i][j]); } printf(“\n”); } }

  30. Pointers Pointers might be a fairly new term to the learner who learned Java but not familiar with C and C++. Generally speaking, it is very similar to the reference in Java but more flexible, powerful, or even dangerous! But we will have a lot of fun with this term, let’s start! /*I will put a lot of time to discuss pointers*/

  31. Pointers 1. Fundamentals Pointers are the variables for representing the location (rather than the value) of a data item, such as a variable or an array element. They are very common used variables in C, as they have a number of useful applications. For example, pointers can be used to pass information back and forth between a function and its reference point. Pointers are also closely associated with arrays and therefore provide an alternate way to access individual array elements. Moreover, pointers provide a convenient way to represent multidimensional arrays, allowing a single multidimensional array to be replaced by a lower –dimensional array of pointers. This feature permits a group of strings to be represented within a single array, though the individual strings may differ in length.

  32. Pointers e.g. main() { int u = 3; int v; int *pu; /*defined a pointer*/ int *pv; /*defined a pointer*/ pu = &u; /*pointer pu points to the address of variable u*/ v = *pu; /*variable v gets the value which the pointer pu points to*/ pv = &v; /*pointer pv points to the address of variable u*/ printf(“\nu=%d &u=%X pu=%X pu=%d”,u, &u, pu, pu); printf(“\n\nv=%d &v=%X pv=%X pv=%d”,v, &v, pv, pv); }

  33. Pointers 2. Pointer declarations In general terms, a pointer declaration may be written in: data-type *ptvar; e.g. float *pointer_1; char *pointer_2; int *pointer_3; /*those are legal declarations*/ int pointer_4; double point_5; /*those are illegal declaration*/

  34. Pointers e.g. int i = 1, j = 2; int *pointer_1, *pointer_2; pointer_1 = &i; /*this means the pointer pointer_1 points to the address of i*/ pointer_2 = &j; /*this means the pointer pointer_2 points to the address of j*/ pointer_1 = i; /*this is illegal because the pointer should point to an address*/ pointer_2 = 100; /*this is illegal because the pointer should point to an address*/ pointer_2 = &*pointer_1; /*Because &,* have the same priority, it follows the rule of right to left which means pointer_2 = &(*pointer_1);. *pointer_1 is i, so pointer_2 = &(*pointer_1); can be written as pointer_2 = &i; */ (Specials: (*pointer_1)++ == i++, but if *pointer_1++, then it means pointer_1++ (address +1) and then get the value.)

  35. Pointers 3. Pointers as arguments of functions e.g. swap(int *p1, int *p2) { int temp; temp =*p1; *p1 = *p2; *p2 = temp; } main() { int a,b; int *pointer_1, *pointer_2; scanf(“%d,%d”,&a,&b); if (a<b) swap(pointer_1,pointer_2); printf(“\n%d,%d\n”,a,b); }

  36. Pointers 4. Pointers and One-Dimensional Arrays *Pointers can be used for an alternative way to represent array eg: main() { static int x[10] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; for (int j =0; j<10; j++) { /* display an array element*/ printf(“\nj=%d x[j]=%d *(x+j)=%d”, j, x[j], *(x+j)); /* display the corresponding array address*/ printf(“ &x[j]=%X x+j=%X”, &x[j], (x+j)); } }

  37. Pointers 5. Dynamic memory allocation: Since an array name is actually a pointer to the first element within the array, it should be possible to define the array as a pointer variable rather than as a conventional array. Syntactically, the two definitions are equivalent. However, a conventional array definition results in a fixed block of memory being reserved at the beginning of program execution, whereas this does not occur if the array is represented in terms of a pointer variable. Therefore, the use of a pointer variable to represent an array requires some type of initial memory assignment before the array elements are processed. This is known as dynamic memory allocation. Generally, the malloc library function is used for this purpose. To assign sufficient memory for x,y, we can make use of the library function malloc, as follows. x = (int *) malloc(10 * sizeof(int)); y = (double *)malloc(10 * sizeof(double));

  38. Pointers eg: #include <stdio.h> #include <stdlib.h> /*for invoke malloc function*/ void reorder(int n, int *x); main() { int j, n, *x; /*read in a value for n*/ printf(“\nHow many numbers will be entered? ”); scanf(“%d”, &n); printf(“\n”); /*allocate memory*/ x = (int *)malloc(n * sizeof(int)); …… } …… See the resource example pointer4 for the detail information

  39. Pointers 6. Pointers and multidimensional arrays Since a one-dimensional array can be represented in terms of a pointer (the array name) and an offset (the subscript), it is reasonable to expect that a multidimensional array can also be represented with an equivalent pointer notation. This is indeed the case. A two dimensional array, for example, is actually a collection of one-dimensional arrays. Therefore, we can define a two-dimensional array as a pointer to a group of contiguous one-dimensional arrays. This, a two-dimensional array declaration can be written as data-type (*ptvar) [expression 2]; rather than data-type array[expression 1][expression 2]; This concept can be generalized to higher-dimensional arrays; that is data-type (*ptvar) [expression 2] [expression 3]… [expression n]; replaces data-type array[expression 1][expression 2]… [expression n];

  40. Pointers eg: We can declare x as int (*x)[20]; // more flexible Rather than int x[10][20]; Or We can declare t as float (*t)[20][30]; Rather than float t[10][20][30]; eg: *(*(x+2) +5) == x[2][5]

  41. Pointers 7. Arrays of pointers: In general terms, a two dimensional array can be defined as a one-dimensional array of pointers by writing data-type *array[expression 1]; Rather than the conventional array definition data-type array[expression 1][expression 2]; Similarly, an n-dimensional array can be defined as an (n-1)-dimensional array of pointers by writing data-type *array[expression 1] [expression 2]… [expression n-1]; Rather than data-type array[expression 1] [expression 2]… [expression n1];

  42. Pointers eg: Int *x[10]; x[0] x[1] Address: (x[2]+3) Value: *(x[2]+3) x[2] …… x[9] x[10]

  43. Pointers 8. Passing functions to other functions: Host function, guest function relationship: A function which is passed as a parameter to a function is called guest function. A function which contains functions as parameters is called host function. The guest function is declared as a regular function. The function declaration for the host function is Funct-data-type funct-name(arg-data-type (*pt-var)(type 1 arg 1, type 2 arg 2, …), data types and names of other funct args);

  44. Structures and Unions 1. Structures: Fundamental: What is a Structure? The structure is a stuff in which the individual elements can differ in type, thus, a single structure might contain integer elements, floating-point elements and character elements. Pointers, arrays and other structures can also be included as elements within a structure. The individual structure elements are referred to as members. In general terms, the composition of a structure may be defined as struct tag{ member 1; member 2; member 3; …… member m; };

  45. Structures and Unions e.g. A typical structure declaration is shown below. struct account { int acct_no; char acct_type; char name[80]; float balance; }; /*Don’t forget the important ‘;’!!!*/ It is possible to combine the declaration of the structure composition with that of the structure variables, as shown below. struct tag { member 1; member 2; …… member m; } variable 1, variable 2, ……, variable n;

  46. Structures and Unions e.g. struct date { int month; int day; int year; }; struct student { int num; char name[20]; char sex; int age; struct data birthday; /*birthday is struct data type*/ char addr[30]; }student1, student;

  47. Structures and Unions Initializing of a Structure: eg: Struct date{ int month; int day; int year; } Struct account{ int acct_no; char acct_type; char name[80]; float balance; struct date lastpayment; }; Static struct account customer = {12345, ‘R’, “John W. Smith”, 586.30, 5, 24, 90};

  48. struct date{ char name[80]; int month; int day; int year; }; Static struct date birthday[] = {“Amy”, 12, 30, 73, “Gail”, 5, 13, 66, “Marc”, 7, 15, 72, “Susan”, 4, 12, 69}; struct date{ char name[80]; int month; int day; int year; }; Static struct date birthday[] = { {“Amy”, 12, 30, 73}, {“Gail”, 5, 13, 66}, {“Marc”, 7, 15, 72}, {“Susan”, 4, 12, 69} }; Structures and Unions

  49. Structures and Unions Processing a structure: In general terms, a structure member can be accessed by writing variable.member or variable.memeber.submember or variable.member[expression] eg: struct date{ int month; int day; int year;} struct account{ int acct_no; char acct_type; char name[80]; float balance; struct date lastpayment;} customer; We can access acct_no by customer.acct_no; Access name by cutomer.name; Access month by customer.lastpayment.month; Access the second character of name by customer.name[1]; Access the address of the acct_no by &customer.acct_no;

  50. Structures and Unions Application: The C code shows under resource/structure/struct1 directory a typical application of the structures. The program is about the payment of a group of persons.

More Related