1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C...

74
1 IPC144 Session 10 The C Programming Language

Transcript of 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C...

Page 1: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

1

IPC144Session 10

The C Programming Language

Page 2: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

2

Objectives

Construct the basic structure of a C programUse this structure in creating programs that can be compiledList the data types used in CDifferentiate between integer and float data typesSelect the most appropriate data type for the dataExplain the purpose of the #include statementUse the #include to include system libraries and user librariesApply coding conventions to provide the approved layout of a programApply coding conventions in the creation of variable namesApply coding conventions in the creation of C statementsApply coding conventions in the creation of C comments

Page 3: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

3

The C Language

IntroductionDeveloped 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."

Page 4: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

4

The C Language

MainThis 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.

Page 5: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

5

The C Language

Main, continuedThe 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

}

Page 6: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

6

The C Language

Main, continuedThe 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){ ;}

Start

Stop

Page 7: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

7

The C Language

Main, continuedint 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)

Page 8: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

8

The C Language

IndentationCheong.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;}

Page 9: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

9

The C Language

IndentationOllinger.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 "); }}

Page 10: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

10

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);}

Page 11: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

11

The C Language

Preprocessor DirectivesPreprocessor 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

Page 12: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

12

The C Language

Preprocessor Directives, continuedThe 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

Page 13: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

13

The C Language

Preprocessor Directives, continuedThe 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"

Page 14: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

14

The C Language

Header FilesIn 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).

Page 15: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

15

The C Language

Header Files, continuedThe 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"

Page 16: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

16

The C Language

The Compile Process RevisitedIn 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.

Source file(3GL LanguageText File)

Library files (for O/S)

Executablefile

Translator LinkerObject File

Compiler

Preprocessor

References to other object filesOther C source

code files to be drawn into the process

Page 17: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

17

The C Language

The C Source Code with the Preprocessor DirectiveAs 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.

Page 18: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

18

The C Language

Data TypesThe 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.

Page 19: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

19

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).

Page 20: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

20

The C Language

char Data Types, continuedASCII Table:

Bit Positions 6543210 000 001 010 011 100 101 110 1110000 NULL DLE SPACE 0 @ P ` p0001 SOH DC1 ! 1 A Q a q0010 STX DC2 " 2 B R b r0011 ETX DC3 # 3 C S c s0100 EOT DC4 $ 4 D T d t0101 ENQ NAK % 5 E U e u0110 ACK SYN & 6 F V f v0111 BEL ETB ' 7 G W g w1000 BS CAN ( 8 H X h x1001 HT EM ) 9 I Y I y1010 LF SUB * : J Z j z1011 VT ESC + ; K [ k {1100 FF FS , < L \ l |1101 CR GS - = M ] m }1110 SOH RS . > N ^ n ~1111 SI US / ? O _ o DEL

Page 21: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

21

The C Language

short int Data Type

The short int is an integer (2 bytes).

It can store numbers between -32768 and 32767.

Page 22: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

22

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.

Page 23: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

23

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.

Page 24: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

24

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.

Page 25: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

25

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.

Page 26: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

26

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.

Page 27: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

27

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

Page 28: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

28

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.

Page 29: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

29

The C Language

int Data Types vs. float Data TypesThe 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).

Page 30: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

30

The C Language

Choosing a data typeWhy 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.

Page 31: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

31

The C Language

Choosing a data typeWhat 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

Page 32: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

32

The C Language

Choosing a data typeWhat 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

Page 33: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

33

The C Language

Declaring VariablesWhen we declare variables in C, there are two parts to the C statement:variable data type, followed byvariable name

For example:

int transCounter;float balance;

Note that C statements all end with a ';'

Page 34: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Declaring Variables, continuedRemember the analogy for memory?

The data type will determinethe amount of memory to beused for your variable.

10

1

2

3

4

5

6

7

8

9

10

11

12

0

72(H)

105(i)

64

168

12586

5.2653

The C Language

int or unsigned int

short int or unsigned short int

float

char

Page 35: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

35

The C Language

Declaring Variables, continuedHere 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 underscoreOnly the first 31 characters are significant (ANSI standard)- the compiler only looks at the first 31 characters and ignores the restabcdefghijklmnopqrstuvwxyz01234467890abcdefghijklmnopqrstuvwxyz01234567890 Are considered the same variableCannot be the same as a 'reserved' word - those words that are known to the compiler (like "if" or "while")

Page 36: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

36

The C Language

Standards and GuidelinesThis 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."

Page 37: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

37

The C Language

Standards for Declaring VariablesThe 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:

counteraverageavgOfClassavgOfCourse

Page 38: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

38

The C Language

Standards for Declaring Variables, continuedUse 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 avgdatabase dblength lenmessage msgnumber numpointer ptrposition posstring str

Examples:custAvgmsgLenavg

Page 39: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

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).

GuidelineKeep module lengths less than 2 pages. If it becomes more than 2 pages, consider breaking it down into sub-modules.

39

The C Language

Page 40: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

CommentsComments 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

Page 41: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Comments, continuedTo 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 codeExamples:

/* this is a comment */

/* this commentspans two lines */

/********************\* ** Is this a comment? ** *\********************/

To create a comment to the end of the line, use://

41

The C Language

Page 42: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Comments, continuedThere are three types of comments:

In-line commentsBlock CommentsModule Header and File Header comments

42

The C Language

Page 43: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

In-Line CommentsThese 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 & GSTELSE taxRate = 0.08 // Charge GST onlyEND IF

43

The C Language

Page 44: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

In-Line Comments, continuedCan also be written above the line of code it refers to:

IF provResidency ='ONT' THEN /* Charge PST & GST */ taxRate = 0.15ELSE /* Charge GST only */ taxRate = 0.08END IF

Or

IF provResidency ='ONT' THEN // Charge PST & GST taxRate = 0.15ELSE // Charge GST only taxRate = 0.08END IF

Of the two examples, which was more readable?44

The C Language

Page 45: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Block CommentsConsist 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

Page 46: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Block Comments, continuedExample:

IF a = b THEN c= d /*================================================ | | This is an example of a block comment, indented | |===============================================*/ CALL someModule(c)ELSE c = qEND IF

46

The C Language

Page 47: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Module / File Header CommentsThese 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

Page 48: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

File Header CommentsFile Header Comments consists of:

File NamePurpose - a one line statement describing the file/programDocumentation - 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

Page 49: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

File Header Comments, continuedTemplate:

/*===========================================================|| File Name:| Purpose:| Documentation:||| Revision History:| Date Name Revision| ---------- ------------- -------------------------------|||===========================================================*/

49

The C Language

Page 50: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

File Header Comments, continuedExample:

/*===========================================================|| 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

The C Language

Page 51: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Module Header CommentsModule Header Comments consist of:

Module NamePurpose - a one line statementMethod: as much detail as necessary about how the module performs its function.Revision history section

This template is virtually identical to the File Header template

51

The C Language

Page 52: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Module Header Comments, continuedModule Header Template:

/*===========================================================|| Module Name:| Purpose:| Method:||| Revision History:| Date Name Revision| ---------- ------------- -------------------------------|||===========================================================*/

52

The C Language

Page 53: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Module Header Comments, continuedExample:

/*===========================================================|| Module Name: determinePrime| Purpose : Determines if a given number is a prime number| Method:| Calculate the modulus of number (y) and all numbers (x)| from 2 to y - 1. If the modulus is 0 then x is a factor| of y, and therefore y is not a prime number.||| Revision History:| Date Name Revision| ---------- ------------- -------------------------------| 2003-10-08 Pete Prime created||===========================================================*/

53

The C Language

Page 54: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Module Header Comments, continuedExample of a variation that I use:

/***********************************************************\* ** Name : determinePrime ** Parameters: i - y: The number to be tested ** Returns : TRUE - if the number is a prime number ** : FALSE - if the number is not a prime number ** Description: ** Calculate the modulus of number (y) and all numbers (x) ** from 2 to y - 1. If the modulus is 0 then x is a factor ** of y, and therefore y is not a prime number. ** *************************************************************** MODIFICATION HISTORY ** ** Date Name Revision ** ---------- ------------- -------------------------------** 2003-10-08 Pete Prime created ** *\***********************************************************/

54

The C Language

Page 55: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

File OrganizationWhen writing your source code, it must contain the following sections, in the following order:

Prologue - the file header

Includes - the #include preprocessor directive for all included files

Defines - (static definitions used by your program- more on these later)

Global Definitions - variables that are global to the program-you better have a good reason to use these, they are generally

considered bad form and are forbidden on your assignments

Modules - your modules in some meaningful order

55

The C Language

Page 56: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

56

Data Manipulation

IntroductionWithin the C language there are various ways to manipulate data, or the contents of variables within memory. To begin with we will look at:

AssignmentsOperators

AssignmentsThere are two variations of assignment statements we will look at:

Variable declarationExpression

In both cases the assignment operator that is used is '='.

Page 57: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

57

Data Manipulation

Assignments - Variable DeclarationThis variation of an assignment takes place at the same time the variable is declared in the C program.

To declare a variable, the format is:

dataType variable1 [=value] [,variable2 [=value]]... ;

For example:

int counter; /* no assignments */

int counter, classCount, courseCount; /* no assignments */

int x = 0; /* 1 assignment */

int x = 1, y = 2, z = 3; /* 3 assignments */

Page 58: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

58

Data Manipulation

Assignments - Variable Declaration, continuedRemember that the computer stores only numbers. Characters are stored using the ASCII coding scheme (in our case).

When dealing with char datatypes, there are two ways to initialize the variable with a value from the ASCII code table:

The compiler does a lookup in the ASCII table, and places the appropriate numerical value into the variable:char myChar = 'A';

You, the programmer, perform a lookup in the ASCII table, and assign the appropriate numerical value to the variable.char myChar = 65;

Page 59: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

59

Data Manipulation

Assignments - ExpressionThis variation of an assignment takes place as a result of a calculation.

For example:

a = b + c;

avgNumber = ttlNumber / count;

i = i + 1;

*Note: the computer will evaluate the right side of the assignment operator and then the final result will be placed into the variable on the left side of the assignment operator

Page 60: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

60

Data Manipulation

OperatorsThere are three basic types of operators:ArithmeticRelationalLogical

Page 61: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

61

Data Manipulation

Arithmetic OperatorsThe following symbols are used for arithmetic operations in the C language:

+ Addition 8 + 2 = 10

- Subtraction 8 - 2 = 6

* Multiplication 8 * 2 = 16

/ Division 8 / 2 = 4

% Modulo 8 % 2 = 0

Page 62: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

62

Data Manipulation

Arithmetic Operators, continuedAn interesting technique to keep in mind, when dealing with char datatypes. Since the computer stores only numbers, and characters are stored using the ASCII coding scheme (in our case), what would be the result of:

char myChar = 'A';myChar = myChar + 32;

Page 63: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

63

Data Manipulation

Relational OperatorsA decision structure within a programming language is fairly useless without a means to compare two or more variables

There are only a few types of Relational Operators

When a relation is expressed in C, the result is either TRUE or FALSE

A relation is also referred to as an Expression

These Expressions can be used in the decision structure- specifically the IF-THEN-ELSE and DOWHILE that we have seen in pseudocode

In C any non-zero value is considered TRUE, zero is considered FALSE

Page 64: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

64

Data Manipulation

Relational Operators, continuedThe Relational Operators are:

Equal == (NOT "=" by itself)

Not Equal != (NOT "!==")

Less than <

Greater than >

Less than or equal <=

Greater than or equal >=

Page 65: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

65

Data Manipulation

Relational Operators, continuedExample Expressions based on a relation:

a < b5 > t7 < 0(a + b) > (g - f)

When evaluating expressions that contain relational operators, a TRUE condition is represented by the value 1, a FALSE condition is represented by the value 0

For example:

The expression (7 > 8) would be represented by 0

The expression (7 < 8) would be represented by 1

Page 66: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

66

Data Manipulation

Relational Operators, continuedWhat is the result of these expressions (the numerical value), and are they TRUE or FALSE?

7 - 2

5 < 3

i = 25

i = 0

((5 >= 3) + 2) < 3

For the next question, if a = 10, b = 15, c = 30

((((c % a) + (b % a)) > (a < b)) -1) + b

Page 67: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

67

Data Manipulation

Relational Operators, continuedWhat is the result of these expressions (the numerical value), and are they TRUE or FALSE?

7 - 2 5 TRUE

5 < 3 0 FALSE

i = 25 25 TRUE

i = 0 0 FALSE

((5 >= 3) + 2) < 3 0 FALSE

For the next question, if a = 10, b = 15, c = 30

((((c % a) + (b % a)) > (a < b)) -1) + b 15 TRUE

Page 68: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Logical OperatorsLogical operators are how we express the Boolean functions we explored in Session 2

In C the NOT logical operator is represented by !In C the OR logical operator is represented by || (two vertical bars)In C the AND logical operator is represented by &&

Example:

PseudocodeIF a > b AND c < d OR g = k THEN

C

if (a > b && c < d || g == k)...

68

Data Manipulation

Page 69: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Coding StandardUse a single space on either side of binary operators (binary operator in the context means an operator with two operands).

* a * b a*b/ x / y x/y% g % h g%h+ u + v u+v- q - w q-w&& y && u y&&u|| k || l k||l< s < d s<d> f > g f>g<= z <= x z<=x>= c >= v c>=v== n == m n==m!= i != o i!=o

69

Data Manipulation

Page 70: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Order of PrecedenceThe normal order of operations performed on the basic * / + - and % is:

1) Evaluate multiplication, division and modulo from left to right first2) Evaluate addition and subtraction from left to right

What would be the result of:

5 * 3 - 8 / 4 % 3

70

Data Manipulation

Page 71: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Order of Precedence, continuedThe preceding order of operations can be overridden by by use of parenthesis ().

What is the result of:

5 * (3 - 8 / 4) % 3

A simple mnemonic to help remember the order of operations is BEDMAS:

B - Brackets (i.e. parenthesis)E - Exponents (these do not exist in C)D - DivisionM - MultiplicationA - AdditionS - Subtraction

A more comprehensive list exists on the back cover of your textbook.

71

Data Manipulation

Page 72: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Order of Precedence, continuedInterpreting the Order of Precedence table can be difficult at first.

The first column of the table contains the operator. The closer to the top of the list an operator is, the sooner it must be calculated.

The second column indicates in which direction the operator is evaluated. A portion of the table is:

Operator Associativity* / % L-R recall from a previous slide that these are

evaluated left to right+ - L-R

= R-L recall from a previous slide that the right sidewill be evaluated first, then the result placedin a variable on the left side

72

Data Manipulation

Page 73: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Order of Precedence, continuedBased on the Order of Precedence table, the expression:

a > b && c < d || g == k

is the same as:

1) (a > b && c < d) || (g == k)

2) (a > b) && (c < d || g == k)

3) all of the above

4) none of the above

73

Data Manipulation

Page 74: 1 IPC144 Session 10 The C Programming Language. 2 Objectives Construct the basic structure of a C program Use this structure in creating programs that.

Order of Precedence, continuedBased on the Order of Precedence table, the expression:

a > b && c < d || g == k

is the same as:

1) (a > b && c < d) || (g == k)

2) (a > b) && (c < d || g == k)

3) all of the above

4) none of the above

74

Data Manipulation