740 likes | 885 Views
IPC144 Session 10 The C Programming Language. 1. Objectives Construct the basic structure of a C program Use this structure in creating programs that can be compiled List the data types used in C Differentiate between integer and float data types
E N D
IPC144 Session 10 The C Programming Language 1
Objectives • Construct the basic structure of a C program • Use this structure in creating programs that can be compiled • List the data types used in C • Differentiate between integer and float data types • Select the most appropriate data type for the data • Explain the purpose of the #include statement • Use the #include to include system libraries and user libraries • Apply coding conventions to provide the approved layout of a program • Apply coding conventions in the creation of variable names • Apply coding conventions in the creation of C statements • Apply coding conventions in the creation of C comments 2
The C Language Introduction Developed in 1972 by Denis Ritchie and Ken Thompson as they worked designing on the UNIX operating system. It is a tool written by programmers for programmers. A program written in C can easily be ported from one environment to another. Unlike many languages that are used for teaching programming, C will allow you to shoot yourself in the foot. The best defense against becoming C-sick, is to adhere to the PDC discussed in class. Make extensive use of flowcharts and pseudocode as you develop your C-legs. As mentioned in the textbook- bad programming practices can be taken to the limit in C due to its flexibility. One of the goals of the annual International Obfuscated C Code Contest (www1.us.ioccc.org) is "To show the importance of programming style, in an ironic way." 3
The C Language Main This is the entry point for all C programs. It is a module that sits on top of the hierarchy of modules. The creation of the main module: int main(void) parameters passed to your program by the operating system "void" indicates that there are none - note the parentheses the name of the module a data type that allows your program to return a simple numeric message to the operating system, upon completion. 4
The C Language Main, continued The C language uses special characters to show the beginning and ending of a block of code (such as the code to be found in the main module). Start of code symbol: { End of code symbol: } Combining these with the main module: int main(void) { your C program } 5
The C Language Start Stop Main, continued The C language also uses a special character to show where a statement ends: ; (semi-colon) The semi-colon by itself, is considered a statement that performs no action. Putting it all together, remember the flow chart of the program that does nothing? The C code would look like: int main(void) { ; } 6
The C Language Main, continued int main(void) { ; } Note that the C statement (the ';') has been indented. The indentation you have practiced in pseudocode must be applied to C in order to have a program that is readable by others. The following programs have either no indentation, or bizarre indentation, these have been taken from the IOCCC (this NOT what I want your programs to look like) 7
The C Language Indentation Cheong.c (Calculates arbitrary-precision square root) #include <stdio.h> int l;int main(int o,char **O, int I){char c,*D=O[1];if(o>0){ for(l=0;D[l ];D[l ++]-=10){D [l++]-=120;D[l]-= 110;while (!main(0,O,l))D[l] += 20; putchar((D[l]+1032) /20 ) ;}putchar(10);}else{ c=o+ (D[I]+82)%10-(I>l/2)* (D[I-l+I]+72)/10-9;D[I]+=I<0?0 :!(o=main(c/10,O,I-1))*((c+999 )%10-(D[I]+92)%10);}return o;} 8
The C Language Indentation Ollinger.c (Prints primes with a sieve graph) #define n ((e[++a]-42)/9-f[d+1])? #define o printf("%c",c[" 01./:;|\\"]); char e[]="**3<HRZcir+3@OXakt;=GOXds*\?HRZcir*7HNZ`i19JS\\p*H[m1:CJSz*>H[`mr25\ \?Hx,P,B2Gs-KTfzRdv1SeyCR-ISeu.<Ev+9+P,z,4PfzIdvO2*HRZcir6GPis=MU*3HRZcir*HZi\ 1JS\\epy*>H[m1JSey*DH[m*3<HZiu-@P*3HZi<N]q1JS\\epy:[m1CJSeny06I[m*4\?HRZcir,\ \?*6HRZcir1J]q2K*H[m2K*H[m2@K]qtO@M2DK]q,]q1JS\\epy[m1:JSey+[m*3<HRZcir13Gt,\ =GVs*3<HRZcir1J]qz*HF*AH2;DK]qua0=G2:K]q]q1CJS\\pDVu1:JS*D!+3:BIOSY`egilqtxz\ \177.0249<==>EJMUY`ejov#$59@CJOXYZbfhlnrxy&+.57=@IMR[``bcfmnq!#),@",*f; int main(int j,char *k[]) { int a,b,c,d,g,h,i=19; printf(" "); for(g=0[f=(char *)calloc(80+(h=atoi(1[k])),1)]=1; g<=h; g++) { if ((g>30)&&(f[i-2]+f[i-1]!=0)) i++; for(d=c=0; d<i; d++) { o f[d]=(e[b=c*9,b+=(c=d[f]),(((a=e[345+b]+b/19*85-33-b/40*12-b/80*4)[e] -42)/9-f[d+1])?n n n n n n n n 0:a:a:a:a:a:a:a:a:a]-42)%9; } o if (0[f]-1) printf("\n%6i ",g); else printf("\n "); } } 9
The C Language Indentation Williams.c (Plays X-based missile command ) #include <X11/Xlib.h> #include <unistd.h> typedef long O; typedef struct { O b,f,u,s,c,a,t,e,d; } C; Display *d; Window w; GC g; XEvent e; char Q[] = "Level %d Score %d", m[222]; #define N(r) (random()%(r)) #define U I[n++]=L[n]=l; n%=222 #define K c=-l.u; l=I[i]; l.t=0; c+=l.u #define E l.e--&&!--L[l.e].d&&(L[l.e].t=3) #define M(a,e,i,o) a[0]=e,(a[1]=i)&&XFillPolygon(d,w,g,(void*)a,o,1,1) #define F return #define R while( #define Y if(l.t O p ,B, D,A=6,Z ,S=0,v= 0,n=0,W=400 ,H=300,a[7] ={ 33,99, 165, 231,297,363} ; XGCValues G={ 6,0 ,~0L,0,1} ; short T[]={ 0,300,-20,0,4 ,-20,4,10,4,-5,4,5, 4,-20,4,20,4,-5,4,5,4, -10,4,20},b[]={ 0,0,4, 0,-4,4,-4,-4,4,-4,4,4} ; C L[222],I[222];dC(O x){ M(T,a[x],H,12); } Ne(C l,O s) { l.f=l.a=1; l.b=l.u=s; l.t=16; l.e=0; U; } nL(O t,O a,O b,O x,O y,O s,O p){ C l; l.d=0; l.f=s; l.t=t; y-=l.c=b; l.e=t==2?x:p; x-=l.s=a;s=(x|1) %2*x; t=(y|1)%2*y; l.u=(a=s>t?s: t)>>9;l.a=(x<<9)/a;l.b=(y<<9)/a; U; } di(C I){ O p,q,r,s,i=222;C l; B=D=0; R i--){ l=L[i]; Y>7){ p=I.s -l.s>>9; q=I.c-l.c>>9; r=l.t==8?l.b: l.a; s=p*p+q*q; if(s<r*r||I.t==2&&s< 26) F S+=10; s=(20<<9)/(s|1); B+=p*s; D+=q*s; }} F 0; } hi(O x,O d){ O i=A; R i--&&(x<a[i]-d||x>a[i]+d)); F i; } dL(){ O c,r=0, i=222,h; C l; R i--){ l=L[i]; Y){ r++;c=l.f; Y==3){c=l.u; l.t=0; E; }R c--){-- l.u;h=l.c>>9; Y>7){XDrawArc(d,w,g, (l.s>>9)-++l.a,h-l.a,l.a*2,l.a*2,0 ,90<<8); if(!l.u){ I[i].t-=8; l=I[i]; } } else Y==2)M (b,l.s>>9,h,6); else XDrawPoint(d ,w,g,(l.s+=l.a)>>9, h=(l.c+=l.b)>>9); Y==4&&!l.u){ Ne (l,20); K; } Y&&l.t<3&&(di(l)||h> H)){ if(h>H&&(c=hi( l.s>>9,25))>=0){ dC(c); a[c]=a[-- A]; }Ne(l,30); Y==1){ E;K; } else c=l.t=0;} Y==1&&h<H -75&&!N(p*77)){ do{ nL(1,l.s,l.c, N(W<<9),H<<9,1,i+ 1); I[i].d++; }R N(3) ); K; l.u=c; c=0; } Y ==2){ l.s+=l.a+B; l.a= (l.e-l.s)/((H+ 20-h)|1); l.c+=l.b+D; M(b,l.s>>9,l.c>>9,6); } } L[i]=l; } } F r; } J(){ R A) { XFlush(d); v&&sleep( 3); Z=++v*10; p=50-v; v%2&&hi ((a[A]=N(W-50)+25),50)<0 &&A++; XClearWindow (d,w); for(B=0; B<A; dC(B++)); R Z|dL()){ Z&&!N(p)&&(Z-- ,nL(1+!N(p),N(W<<9), 0,N(W<<9),H<<9,1 ,0)); usleep(p*200); XCheckMaskEvent(d, 4,&e)&&A&&--S&&nL(4,a[N(A)]<<9,H-10<<9,e. xbutton.x<<9,e.xbutton.y<<9,5,0);}S+=A*100; B=sprintf(m,Q,v,S); XDrawString(d,w ,g,W/3,H/2,m,B); } } main () { O i=2; d=XOpenDisplay(0); w=RootWindow(d,0); R i--) XMapWindow(d,w=XCreateSimpleWindow(d,w,0,0,W,H,0,0,0)); XSelectInput(d,w,4|1<<15); XMaskEvent(d,1<<15,&e); g=XCreateGC(d,w,829,&G); srandom(time(0)); J(); puts(m); } 10
The C Language Preprocessor Directives Preprocessor directives are commands to the compiler program. They are always placed at the top of your source code file (before main). All preprocessor directives begin with the character: # The format of a preprocessor directive is: #directive [parameter ...] parameter(s)- depending on which preprocessor directive is invoked, parameters may or may not be required. one-word directive the '#' symbol that defines this line as a preprocessor directive 11
The C Language Preprocessor Directives, continued The most common preprocessor directive is the include preprocessor directive. It tells the compiler that another file of C code needs to be included in this process (this file may also contain preprocessor directives). The include preprocessor has one parameter: the name of the file to be included. #include <stdio.h> The name of the file to be included. The preprocessor directive The preprocessor symbol 12
The C Language Preprocessor Directives, continued The include preprocessor has the following syntax rules: If the filename is surrounded by '<' and '>', then the compiler will search for the source code in the system directory (/usr/include). For example: #include <stdio.h> If the filename is surrounded by double-quotes (" and "), then the compiler will search for the source code in your current working directory. For example: #include "prog1.h" 13
The C Language Header Files In the include preprocessor directive, the filenames above ended with an extension of ".h". The ".h" is the conventional extension used for "header files" Header files contain C language statements, however there are no executable blocks of code (by convention) The C statements in the include file may refer to modules in object files that have already been compiled. The C statements in the include file may refer to fixed values in the program that do not change often, or to fixed values scattered throughout the program that change frequently (and it is too difficult to keep finding them). 14
The C Language Header Files, continued The include preprocessor directive could also be used to include other C code source files. In this case the extension would be ".c", just like any other C code source file. This is handy when you have a large program, that consists of many modules. For example, one programmer tracking 12915 lines of code in 162 modules. By grouping the modules together that are related, the source code can be spread across many files- it is like modularizing your source code. It makes finding a particular module easier. For example: #include "fileops.c" #include "menus.c" 15
The C Language The Compile Process Revisited In the world of C we have added the preprocessor in front of the Translator. At this point additional source files can be pulled in for compiling. The header files are pulled in as well. Compiler Linker Preprocessor Translator Object File Source file (3GL Language Text File) Executable file References to other object files Other C source code files to be drawn into the process Library files (for O/S) 16
The C Language The C Source Code with the Preprocessor Directive As mention earlier, the preprocessor directives are placed before the main module. Our simple C program that does nothing now looks like: #include <stdio.h> int main(void) { ; } We will look at C code's version of the GET and DISPLAY in a couple of sessions. However, the stdio.h header file is the file that contains the Standard Input/Output library functions. It is how your program communicates with the operating system to get messages to the user, or to get data from the user. 17
The C Language Data Types The pseudocode we have been writing has used variables for various functions, whether it be numbers, letters or phrases. C code is much more specific regarding the use of variables. The following slides describe the various data types found in C. 18
The C Language char Data Type A char is one byte, and is used to represent characters. It can store integers between 0 and 255 (where each number represents a character on the keyboard, plus other special characters). For example, see inside cover of your text book for the ASCII character set). 19
The C Language char Data Types, continued ASCII Table: 20
The C Language short int Data Type The short int is an integer (2 bytes). It can store numbers between -32768 and 32767. 21
The C Language unsigned short int Data Type The unsigned short int is strictly a positive integer (2 bytes). It can store numbers between 0 and 65535. 22
The C Language int Data Types The int is slightly larger (4 bytes). It can store numbers between -2,147,483,648 to 2,147,483,647. 23
The C Language unsigned int Data Types The unsigned int is strictly positive (4 bytes). It can store numbers between 0 and 4, 294, 967,295. 24
The C Language long int Data Type The long int is larger again (8 bytes). It can store numbers between -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. 25
The C Language unsigned long int Data Type The unsigned long int is strictly positive. (8 bytes) It can store numbers between 0 and 18,446,744,073,709,551,615. 26
The C Language float Data Type The float is where the ability to store non-integers (real numbers) begins (single precision- 32 bits = 4 bytes). It can store very small numbers: ±0.11754943508222875x10-39 Or very large numbers: ± 0.34028234663852886x10+39 27
The C Language double Data Type The double is larger (double precision- 64 bits = 8 bytes). It can store even smaller numbers: ± 0.22250738585072014x10-309 Or even larger numbers: ± 0.17976931348623158x10+309. 28
The C Language int Data Types vs. float Data Types The type of calculations (and amount of precision required) will tell you whether you need to use an int data type or a float data type. The int data types cannot store fractional information- assigning 2.5 to a variable defined as being an int data type will result in 2 being stored. The float data type will store fractional information (including integers). 29
The C Language Choosing a data type Why not just use the float data type everywhere? float cannot be used as an index into an array (more of that later) float cannot be used as a char data type The system you are programming for may have space limitations You may be interested in only integers in your system (e.g. how many widgets were shipped) Generally, for counting use integers. For financial and scientific calculations use floats. Depending on the size of the data to be maintained by the variable, choose the appropriate variable. 30
The C Language Choosing a data type What would be appropriate data types for the following scenarios: Variables used for a company's financial transactions Variables used for personal financial transactions The variables used in calculating a averages for classes Variables used in the conversion of temperatures from Celsius to Fahrenheit 31
The C Language Choosing a data type What would be appropriate data types for the following scenarios: Variables used for a company's financial transactions float Variables used for personal financial transactions float The variables used in calculating a averages for classes float and unsigned short int Variables used in the conversion of temperatures from Celsius to Fahrenheit float 32
The C Language • Declaring Variables • When we declare variables in C, there are two parts to the C statement: • variable data type, followed by • variable name • For example: • int transCounter; • float balance; • Note that C statements all end with a ';' 33
The C Language 5.2653 86 125 168 64 105 (i) 72 (H) Declaring Variables, continued Remember the analogy for memory? The data type will determine the amount of memory to be used for your variable. int or unsigned int 12 short int or unsigned short int 11 10 float 9 8 7 6 char 5 4 3 2 1 0 10
The C Language • Declaring Variables, continued • Here are the rules for creating variable names in C: • first character must be an alphabetic character (a-z A-Z) or an underscore (_) • Must contain ONLY alphabetic characters, digits (0 - 9) and the underscore • Only the first 31 characters are significant (ANSI standard)- the compiler only looks at the first 31 characters and ignores the rest • abcdefghijklmnopqrstuvwxyz01234467890 • abcdefghijklmnopqrstuvwxyz01234567890 Are considered the same variable • Cannot be the same as a 'reserved' word - those words that are known to the compiler (like "if" or "while") 35
The C Language Standards and Guidelines This course will expect certain Standards and Guidelines to be followed. Based on the document: "C Style and Coding Standards for the SDM Project". Produced August 1996 by Los Alamos National Laboratory The conclusion from this document reads: "The standards and guidelines laid forth in this document should be followed zealously and in good faith (do not, for example ignore guidelines just because they do not say must). Remember above all that you are working on a team of programmers, and should therefore labour to make your code as easy to follow as possible in case another person has to modify your program. It is not unheard of for even the person who writes sloppy code to not be able to follow it after a significant amount of time has passed." 36
The C Language • Standards for Declaring Variables • The standard by which variable names are to be created in this course are: • Variable names are to be written in lower case characters • If a variable name is a compound name (two or more words make up the name), the first letter of each subsequent words is to be capitalized • The use of the underscore (_) is permitted, however it is not the primary convention. • Examples: • counter • average • avgOfClass • avgOfCourse 37
The C Language Standards for Declaring Variables, continued Use conventional abbreviations for common variables and for use in compound variables. Below is a partial list. Use abbreviations that you see and use in everyday life average avg database db length len message msg number num pointer ptr position pos string str Examples: custAvg msgLen avg 38
The C Language Standards for Writing Statements Line lengths must be less than 256 characters. Some editors are unable to properly handle long lines. Additionally, they are hard to read. Remember, someday somebody else will have to maintain your code- their favourite editor may only support 255 character line lengths. Do not use TABs when indenting text- editors handle TAB characters differently. Use 2 or 3 spaces for each level of indentation (be consistent). Guideline Keep module lengths less than 2 pages. If it becomes more than 2 pages, consider breaking it down into sub-modules. 39
The C Language • Comments • Comments refer to documentation embedded within your source code. They are not executed, and form no machine code at the end of the compile process. • Comments are there to help you remember how your program works- to act as brief notes to yourself and other programmers. • There are two extremes when writing comments: • There are no comments- as a result a very complex program may be too hard to read and maintain (maybe impossible). • There are too many comments- a trivial program may become too hard to follow, especially is viewed on a typical 25 line screen. 40
The C Language Comments, continued To create a comment within your C source code type the character sequence: /* This is the beginning of a comment. The comment will not end until it finds the character sequence: */ Comments may span many lines of source code Examples: /* this is a comment */ /* this comment spans two lines */ /********************\ * * * Is this a comment? * * * \********************/ To create a comment to the end of the line, use: // 41
The C Language • Comments, continued • There are three types of comments: • In-line comments • Block Comments • Module Header and File Header comments 42
The C Language In-Line Comments These are place in-line with the program code Written to the right of the source code statement Typically consist of a couple of words to help clarify the meaning of a statement IF provResidency ='ONT' THEN taxRate = 0.15 /* Charge PST & GST */ ELSE taxRate = 0.08 /* Charge GST only */ END IF Or IF provResidency ='ONT' THEN taxRate = 0.15 // Charge PST & GST ELSE taxRate = 0.08 // Charge GST only END IF 43
The C Language In-Line Comments, continued Can also be written above the line of code it refers to: IF provResidency ='ONT' THEN /* Charge PST & GST */ taxRate = 0.15 ELSE /* Charge GST only */ taxRate = 0.08 END IF Or IF provResidency ='ONT' THEN // Charge PST & GST taxRate = 0.15 ELSE // Charge GST only taxRate = 0.08 END IF Of the two examples, which was more readable? 44
The C Language Block Comments Consist of a block of text only (a paragraph or two is typical) Indented to the same level as the code it is between Structure: /*============================================================= | | Your comments go here. Note that the first line and the last | line are blank. Remember that the block comment is | aligned with the code you are writing | |============================================================*/ /**************************************************************\ * * * Your comments go here. Note that the first line and the last* * line are blank. Remember that the block comment is * * aligned with the code you are writing * * * \**************************************************************/ 45
The C Language Block Comments, continued Example: IF a = b THEN c= d /*================================================ | | This is an example of a block comment, indented | |===============================================*/ CALL someModule(c) ELSE c = q END IF 46
The C Language Module / File Header Comments These are special in that they are the introduction to a large block of code. They are like the preface to a book (File Header Comments) or and introduction to a chapter (Module Header Comments). They are always aligned with the left margin (no indentation). 47
The C Language • File Header Comments • File Header Comments consists of: • File Name • Purpose - a one line statement describing the file/program • Documentation - as much detail about the program as necessary to get the point across. Don't overdue it. • Revision history • A template to be used as a guideline has been provided by the 'C Style and Coding Standards' document. 48
The C Language File Header Comments, continued Template: /*=========================================================== | | File Name: | Purpose: | Documentation: | | | Revision History: | Date Name Revision | ---------- ------------- ------------------------------- | | |===========================================================*/ 49
The C Language File Header Comments, continued Example: /*=========================================================== | | File Name: hilo.c | Purpose : To guess a number chosen by the user | Documentation: | Narrow the range of numbers by taking an average of | the high number and the low number. Ask the user if | the value is higher, lower or equal to their number. | | Revision History: | Date Name Revision | ---------- ------------- ------------------------------- | 2003-10-08 Hi Lowe created | |===========================================================*/ 50