Sei sulla pagina 1di 445

Getting Started

Sakti Pramanik(Instructor) 2148 E. B.

office hours Thu 2-4 Soroor Soltani (TA and grading) Classroom: 3353 Engineering Charles B. Owen BuildingCSE 251 Dr.Programming in C

Structure of the Course


Get a quick intro to C programming Learn enough Unix to use it Get some experience with C-oriented tools. Get some experience writing code

CSE 251 Dr. Charles B. Owen Programming in C

What is C?
C is a rather old programming language (1972, Richie, Bell Labs) Originally designed as a systems software platform (OS and the like) Procedural, block oriented language (no object-oriented programming)

Dennis Ritchie Inventor of the C Programming Language

CSE 251 Dr. Charles B. Owen Programming in C

Why learn C?
Small, extensible language. Progenitor of many languages. Many applications and much support due to its age and general use Many tools written to support C development. Close to the hardware, programmer manages memory Common embedded systems language Can be fast, efficient (most cited reason)
CSE 251 Dr. Charles B. Owen Programming in C

Disadvantages of C? Flexible language allows programmers to commit many sins without warning Hard to debug, fix code Speed depends on programmer as much as the language Managing memory can be dangerous, difficult, painful Lacks modern features (OOP, exceptions, etc.)

CSE 251 Dr. Charles B. Owen Programming in C

Course Structure

CSE 251 Dr. Charles B. Owen Programming in C

Course will be Lecture/Step


This is a 1 credit course, meets only 15 times

Lecture/Step approach pend some time on a lecture topic. pend some time doing hands-on work.

ach lecture/step will have some exercise you will have to turn in at the 7

CSE 251 Dr. Charles B. Owen Programming in C

Grading
3 projects, each for 15% of the grade, total 45%

13-15 Step assignments, exercises, total 55%

Thats it. No exams, no quizzes


8 CSE 251 Dr. Charles B. Owen Programming in C

Attendance is important
We drop the lowest step assignment grade!

Should go without saying that in a course like this attendance is important.

CSE 251 Dr. Charles B. Owen Programming in C

Step exercises
These can be collaborative, done with discussion and help from anyone during lab. Talk to people, ask questions. Lab time is a time to figure stuff out

10

CSE 251 Dr. Charles B. Owen Programming in C

Projects are individual


No collaboration on projects They will be checked by cheat check Just dont do it. Do your own work No makeups! There are only 3 and Ill give plenty of notice. Get it in on time.

11

CSE 251 Dr. Charles B. Owen Programming in C

Get Started, booting

12

CSE 251 Dr. Charles B. Owen Programming in C

Rebooting to linux
Machines are split to run either linux (a unix variant) or Windows You can reboot to run diskless and bring any machine up in linux. Lets do that now!

13

CSE 251 Dr. Charles B. Owen Programming in C

Booting
If your machine says press control-alt-delete to log in, do so, but use the red button in the lower right corner to shut the machine down. Then restart, selecting diskless when prompted. Before logging in, use the Session menu to select GNOME as your session. Once logged in, select Applications/Internet/Iceweasel Web Browser. Go to http://www.cse.msu.edu/~cse251
Initial password is your PID (starts with A)
14

CSE 251 Dr. Charles B. Owen Programming in C

Bringing up
Bring up a terminal Window Applications/ Accessories/Terminal Type: cal 2011

15

CSE 251 Dr. Charles B. Owen Programming in C

Directories

16

CSE 251 Dr. Charles B. Owen Programming in C

What is a directory/folder?
Be it Windows, Linux or OS X, all OSs maintain a directory structure. A directory is a container of files or other directories These directories are arranged in a hierarchy or tree

17

CSE 251 Dr. Charles B. Owen Programming in C

Directory Structure Has a root node, with branch nodes, ends in leaf nodes
The directory structure is a tree Each directory can hold files and point to parent and children directories hello.c

Root

/user

/bin

Branches

/cse251

/john

ls

myhello.c /exercises a.out

a.out

Leaves

18

CSE 251 Dr. Charles B. Owen Programming in C

File Path
A path to a file is a path through the hierarchy to the node that contains a file or directory /user/cse251/exercises/hello.c
/exercises a.out /user /bin

/cse251

/john

ls

myhello.c

Path is from root node /, to user directory, to cse251 directory, to exercises directory, where the file hello.c resides.
19

hello.c

a.out

CSE 251 Dr. Charles B. Owen Programming in C

The current directory


As you type in the command shell, you are presently in one current directory Many commands are available to navigate by changing your current directory

20

CSE 251 Dr. Charles B. Owen Programming in C

Unix command caution(s)


Names are short. This is to avoid typing. Get used to it Most commands take switches, parameters which modify the behavior of the command. Usually preceded by a - All commands, all switches, all paths, all filenames are case sensitive

21

CSE 251 Dr. Charles B. Owen Programming in C

Some Unix Commands


pwd Displays the current working directory ls Lists the contents of the current directory cd Changes the current directory mkdir Creates a new directory

22

CSE 251 Dr. Charles B. Owen Programming in C

Path String
a valid path string is a series of directories (separated by /) which indicates a valid path in the directory structure /user/cse251/exercises/hello.c is a valid path string but /cse251/hello.c is not

23

CSE 251 Dr. Charles B. Owen Programming in C

Three special directory names


. is shortcut for current directory you are in
./a.out is the same as /user/cse251/exercises/a.out if youre currently in /user/cse251/exercises directory

.. is shortcut for the name of the parent directory of the current directory you are in
../a.out is the same as /user/cse251/a.out if youre currently in /user/cse251/exercises directory

~ is a shortcut for your home directory


~/myhello.c is the same as /user/john/myhello.c if your login name is john

24

CSE 251 Dr. Charles B. Owen Programming in C

mv (changes a file)
mv is the move command. Rename a file in place or move to a new directory
mv file.c newFile.c
rename file.c to newFile.c in current directory

mv file.c /user/ptan/
move file.c in the current directory to /user/ptan. The target directory must already exist

mv ~/file.c ./newFile.c
move file.c in home directory to the current directory with the name newFile.c

25

CSE 251 Dr. Charles B. Owen Programming in C

cp, copy a file


cp file.c newFile.c
Create a new file called newFile.c in current directory from the file file.c, which is also in current directory

cp ../file.c ~/programs
cp file.c in parent directory to the sub-directory programs under the home directory

26

CSE 251 Dr. Charles B. Owen Programming in C

rm, remove a file


Cannot be undone, be careful rm /user/cse251/exercises/a.out
remove the file called a.out

rm ./file.c
remove file.c in the current directory

rm i ./file.c
interactive, are you sure?

27

CSE 251 Dr. Charles B. Owen Programming in C

man
man pages exist on Unix, providing documentation (a lot of documentation) on each command man ls
man page on the ls command

man -k graphics or apropos graphics


every man page that has graphics as a word

man -S 2 mount
man page for section 2 of mount

28

CSE 251 Dr. Charles B. Owen Programming in C

Better man pages


Almost every distribution of Linux provides a better way to view man pages On Debian/Ubuntu, the program yelp (the help program) will show man pages yelp, then man ls
show man page on ls in a nice way

yelp runs using the lifesaver icon. Go to Advanced options, man pages

29

CSE 251 Dr. Charles B. Owen Programming in C

Whats the shell


the shell is the program that interacts with you through the terminal window there are many, and you can change it easily
csh ksh tcsh bash

by default, you are using tcsh

30

CSE 251 Dr. Charles B. Owen Programming in C

Prompt
Default prompt looks like: <47 nelson:/usr/include >
47, which command in the history this is nelson, the name of the machine you are on /usr/include, current directory

can be configured differently [19:19][31][cse251@nelson]~ >


two lines: time, history, who@machine, path

31

CSE 251 Dr. Charles B. Owen Programming in C

Job control
Only one job runs in foreground (sending text to console), but many can run in background Foreground job controls the console
emacs myFile.c &
& mean run emacs in background. Console remains responsive to commands

jobs
lists all jobs running in background. Numbers can be used to control job

32

CSE 251 Dr. Charles B. Owen Programming in C

ps: List of processes


Typically, each job that is executing is called a process
Sometimes, a job can produce (fork) multiple processes

Use ps command to list all your current processes (including those that were suspended or running in background)
It also shows the background processes (including the shell program youre using)

33

CSE 251 Dr. Charles B. Owen Programming in C

Command completion
Type a partial command, followed by tab. it will complete as much as it can

34

CSE 251 Dr. Charles B. Owen Programming in C

Compiling

35

CSE 251 Dr. Charles B. Owen Programming in C

compile to make an executable


In C, you cannot directly execute the source code. You go through a process called compilation Compilation makes sure you followed the rules of C (even if you did something stupid), and makes an executable Compilation errors are rule mistakes. A compilation error means no executable The executable file is the thing you run

36

CSE 251 Dr. Charles B. Owen Programming in C

gcc: gnu compiler


There are others, but this is a good one and it is free (and on all Linux distributions, can be added to the MacOS and runs under Cygwin on windows) Has just around a zillion switches. Can be pretty impressive if you read the man page.

37

CSE 251 Dr. Charles B. Owen Programming in C

Example gcc usage


gcc file.c
if it compiles, makes an executable called a.out in the same directory as file.c can run a.out by typing ./a.out (meaning the a.out in the current directory)

gcc -o myExec file.c


make the executable called myExec

38

CSE 251 Dr. Charles B. Owen Programming in C

Compilation errors
You didnt follow the rules You have to fix the source code before the compiler can make an executable Errors can be cryptic, but at the very least they list the line number where it went wrong Doesnt prevent run-time errors

39

CSE 251 Dr. Charles B. Owen Programming in C

Editors

40

CSE 251 Dr. Charles B. Owen Programming in C

Many Editors
Examples:
gedit vi emacs pico kate

Im going to suggest using gedit in this course.

41

CSE 251 Dr. Charles B. Owen Programming in C

IntroducingC
1.Pleasegetloggedin. 2 OpenanewterminalwindowApplications/Accessories/Terminal 2. 3.OpenawebbrowserApplications/Internet/Iceweasel WebBrowser 4.Gotohttp://www.cse.msu.edu/~cse251 5.OpenStep2:IntroducingC

CSE251Dr.CharlesB.Owen ProgramminginC

HelloWorld
#include<stdio.h> /* / *ThisismyfirstprograminCSE251 */ int main() { printf("Hello,andwelcometoCSE251!!!\n"); }

CSE251Dr.CharlesB.Owen ProgramminginC

HelloWorld
#include<stdio.h> #includestatement

/ /* I l d other Includes th sourcecode d i into t *Thisismyfirstprogram inCSE 251 Oneuseistotell your program. */

yourprogramaboutlibrariesyou areusing.Weareusingthe int main() StandardInput/Output library { printf("Hello,andwelcome toCSE 251!!!\n"); rightnow: stdio. Thefilestdio.h is } theheaderthatdefinesthe S d dI/OLib Standard Library.

CSE251Dr.CharlesB.Owen ProgramminginC

HelloWorld
#include<stdio.h> / /* *ThisismyfirstprograminCSE251 */ Comment

ACommentisanotetoyourself. int main() InCwestartacommentwith/* { andenditwith*/. */ Everythingin printf("Hello,andwelcometoCSE251!!!\n"); betweenisignored. }


Programscanbecrypticandhardtoread.Youneedtoremind yourselfwhatyouwerethinkingwhenyouwrotesomething. Thatswhatcommentsarefor.
4 CSE251Dr.CharlesB.Owen ProgramminginC

HelloWorld
#include<stdio.h>

Themainfunction

main()isthestartingpointforaC /* / program.Its I where h the h computer *ThisismyfirstprograminCSE251 beginsexecution.Notethesyntax: */ thecodeiscontainedincurly braces. int main()
{ printf("Hello,andwelcometoCSE251!!!\n"); }

CSE251Dr.CharlesB.Owen ProgramminginC

HelloWorld
#include<stdio.h>

Aprintf functioncall

/* / printf()isalibraryfunctionthat *ThisismyfirstprograminCSE251 prints.Itsthemainwaywewill */ int main() { printf("Hello,andwelcometoCSE251!!!\n"); }

getoutputfromourCprograms programs.

CSE251Dr.CharlesB.Owen ProgramminginC

printf statementinmoredetail
Af i call ll( h weared i ) function (what doing) Alwaysanamefollowedby(,optional arguments,),and;. Astring Contentbetween"and"is ourwayoftellingthecomputerabout textwewanttoprint. printf("Hello printf( Hello,andwelcometoCSE251!!!\n 251!!!\n"); ); } \nmeansnewline. Cstatementsendwitha;
CSE251Dr.CharlesB.Owen ProgramminginC

Escapecharacters
Charactersthatarehardtoexpress: \n newline \t tab \ p printasingle g quote q \ \\ printabackslash manyothers

CSE251Dr.CharlesB.Owen ProgramminginC

VariableDeclarations
HereishowCdealswithmemory: Imaginethesystemmemoryasanice,flatstretchofbeach Youwantavariable,youneedtodigaholeinthesandand dumpthevaluein Howbigahole? TheholesinCareveryspecialized.Oncedug, theycanonlyholdonetypeofthing. thing Ourhole mightholdintegers,floatingpointvalues,or characters,forexample.

CSE251Dr.CharlesB.Owen ProgramminginC

Declarevariablebeforeuse
Wheny youdeclareavariable,y youaretelling gthe compilerthekindofvaluethevariablemayhold(its type) Youcannotchangethetypeofvalueavariablecan holdoncedeclared(well,prettymuchanyway) Infact,everythingneedsatypeinCanditmustbe declaredbeforeuse!

10

CSE251Dr.CharlesB.Owen ProgramminginC

Commontypes,regularC
int:aninteger,usually4bytes float:float,usually4bytes double:float,usually8bytes g char, ,valueinsingle g q quotes char:single

11

CSE251Dr.CharlesB.Owen ProgramminginC

Mustdeclarebeforeuse
Everyvariablemustbedeclaredbeforeitcanbeused (itstypemustbeindicated) Syntax: (optional)
<variable_type><variable_name>[=<initial_value>];

Example:int length;

12

CSE251Dr.CharlesB.Owen ProgramminginC

Mustdeclarebeforeuse
Everyvariablemustbedeclaredbeforeitcanbeused (itstypemustbeindicated) Syntax: (optional)
<variable_type><variable_name>[=<initial_value>];

Example:doublewidth=10;

13

CSE251Dr.CharlesB.Owen ProgramminginC

RulesforVariableNames

Mustbeginwithaletter Anycombinationofletters,digitsand underscore Upto31characterslong CannotmatchwithaCkeyword


E.g.,int int;int long;

14

CSE251Dr.CharlesB.Owen ProgramminginC

SomeCKeywords y
auto break case char h const continue default do double else enum extern t float f for goto if int long register return t short signed sizeof static struct switch typedef union i unsigned void volatile while

15

CSE251Dr.CharlesB.Owen ProgramminginC

SomeVariableDeclarations
int numLots =7; doublewidth1; doublewidth2; floatcarHP =420.7; i a,b, int b c;

16

CSE251Dr.CharlesB.Owen ProgramminginC

printf:anewfeature
Youcanuseprintf tooutputvariablesaswellasstrings.Puta descriptorinthestringyouprint: int numLots =10; doubletotalArea =100; 00; printf(Thereare%dlots\n,numLots); printf(The%dlotshaveatotalareaof%f\n,numLots,totalArea); Followthestringwithvariables. Eachdescriptor p isreplaced p withavariablesvalue.

17

CSE251Dr.CharlesB.Owen ProgramminginC

Manydescriptors

%s:string %d:decimal(integer) %e:floatingpointexponent %f:floatingpointdecimal %u:unsignedinteger andothers

18

CSE251Dr.CharlesB.Owen ProgramminginC

FullFormatstring g
Theformatstringcontainsasetofformatdescriptors thatdescribehowanobjectistobeprinted
% -#0 12 .4 h d
Conversion Type (dfordecimal) size modifier (hforshortint) Precision

start specification ifi ti Flags

dh Width

19

CSE251Dr.CharlesB.Owen ProgramminginC

Examples printf(%f\n,M_PI); f( f\ )
3.141593

printf(%.4f\n,M_PI); i f(% 4f\ M PI)


3.1416(4decimalpointsofprecision,withrounding)

printf(%10.2f\n,M_PI); i tf(%10 2f\ M PI)


3.14(10spacestotalincludingthenumberandthe decimalpoint)

printf(%10.2fisPI\n,M_PI);
3.14isPI( (10spaces, p ,butleftj justified) )

20

CSE251Dr.CharlesB.Owen ProgramminginC

Examples
int i t numLots L t =10; 10 doubletotalArea =100.7883; floatcurrent=22.7; printf("Thereare%dlotswithatotalareaof%f\n",numLots,totalArea); /*Output:Thereare10lotswithatotalareaof100.788300*/ printf("Theareais%6.2f\n",totalArea); /*Output:Theareais100.79*/ printf("Themeterreads%.1famps\n",current); /*Output:Themeterreads22.7amps*/

21

CSE251Dr.CharlesB.Owen ProgramminginC

Expression
Anexpressioniswritteninprettystandardmathematical notation: wins+losses width*height area/width x*y*z q M PI*2 M_PI printf(Weplayed%dgames\n,wins+losses); Wecanputexpressionswherewe havebeenputtingvariables.
CSE251Dr.CharlesB.Owen ProgramminginC

22

Typesdetermineresults
Forintegers:+,,*,/allyieldintegers.Thusdivision canleadtotruncation(2/3hasvalue0).%givesthe remainder Forfloats:+,,*,/allworkasadvertised.No remainder.

23

CSE251Dr.CharlesB.Owen ProgramminginC

Mixedcomputation
Aswithmostlanguages,Cexpectstoworkwithlike types.1+1,3.14+4.56 Whenmixing,errorsarecommonexceptwhereCcan help Itwillpromoteavaluetoamoredetailedtypewhen required 1+3.14yieldsafloat(1promotedto1.0)

24

CSE251Dr.CharlesB.Owen ProgramminginC

Assignment
Anassignmentputsavalueinavariable.Itisoftheform: variable=expression; Doeverythingontherighthandside,getavalue. Dumpthevalueintothevariable. doublearea, ,circumference; ; area=width*height; circumference=radius*2*M_PI; Declarefirst,assignlater! Dontforgetthesemicolon.
CSE251Dr.CharlesB.Owen ProgramminginC

25

ExpressionandAssignmentExamples
doublevolume,diameter,hypot; int games; volume=radius*radius*M_PI; diameter=radius*2; games=wins+losses; hypot yp =sqrt(near q *near+p pow(far,2));

TouseM_PIormathfunctions:#include<math.h> andcompilewithlmswitch.

26

CSE251Dr.CharlesB.Owen ProgramminginC

scanf
printf("Pleaseentertheyardsofpipeused:"); scanf(%f",&yardsOfPipe);

Scanf isaninputroutine Usefulforreadinginstringinputanddoing conversiontothecorrecttype,allatonce Syntaxiskind kindoflike like printf Notetheuseofthe&operator!!!

27

CSE251Dr.CharlesB.Owen ProgramminginC

Basicform
Tounderstandinput,itisprobablybettertostartwith anexample. scanf(%d, %f, &myInt, &myFloat);
int float

iswaitingforinputoftheexactform 25, 3.14159


Use%fforfloatand%lffordouble. double (Thatstheletterl, l notthenumber1)

28

CSE251Dr.CharlesB.Owen ProgramminginC

formatstringthesame
Whatistypedintheformatstringisthesameas whattheinputexpects,inthiscase:
adecimalnumber acomma afloating fl i point i number b

29

CSE251Dr.CharlesB.Owen ProgramminginC

The&
Hardtoexplainatthemoment,butanyvariablethat getsreadinneedsthatampersandcharacter Itistheaddressofthevariable moreonthatlater

30

CSE251Dr.CharlesB.Owen ProgramminginC

scanf examples
printf("Inputtheradius:"); scanf("%lf",&radius); printf("Inputtheheight:"); scanf("%lf", f("%lf" &height); &h i h ) printf( Inputthenumberofcylinders:"); printf("Input ); scanf("%d",&numCylinders);

31

CSE251Dr.CharlesB.Owen ProgramminginC

FlowControlandBooleans
1.Pleasegetloggedin. 2 OpenanewterminalwindowApplications/Accessories/Terminal 2. 3.OpenawebbrowserApplications/Internet/Iceweasel WebBrowser 4.Gotohttp://www.cse.msu.edu/~cse251 5.OpenStep3:FlowControlandBooleans

CSE251Dr.CharlesB.Owen ProgramminginC

Today:FlowControlandBooleans
FlowControl if,switch

BooleanLogic <,<=,==,>=,>,!=

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<math.h>

rlc.c

/ /* *Simpleprogramtocomputetheresonantfrequencyof *anRLCcircuit */ int main() { doublel;/*Inductanceinmillihenrys */ doublec; ;/* / Capacitance p inmicrofarads*/ / doubleomega;/*Resonancefrequencyinradianspersecond*/ doublef;/*ResonancefrequencyinHertz*/ p printf("Enter ( theinductanceinmillihenrys: y "); ); scanf("%lf",&l); printf("Enterthecapacitanceinmicrofarads:"); scanf("%lf", ( ,&c); ); omega=1.0/sqrt((l/1000)*(c/1000000)); f=omega/(2*M_PI); printf("Resonant p ( frequency: q y %.2f\n", ,f); ); }
3 CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<math.h>

rlc.c

/* / *Simpleprogramtocomputetheresonantfrequencyof *anRLCcircuit Notetheuseofcommentstotell:a)what */ int main() { doublel;/*Inductanceinmillihenrys */ ;/ p / doublec; /*Capacitance inmicrofarads*/ doubleomega;/*Resonancefrequencyinradianspersecond*/ doublef;/*ResonancefrequencyinHertz*/ p printf("Enter ( theinductanceinmillihenrys: y "); ); scanf("%lf",&l); printf("Enterthecapacitanceinmicrofarads:"); scanf("%lf", ( ,&c); ); omega=1.0/sqrt((l/1000)*(c/1000000)); f=omega/(2*M_PI);/*ConvertradianspersectoHertz*/ printf("Resonant p ( frequency: q y %.2f\n", ,f); ); }
4 CSE251Dr.CharlesB.Owen ProgramminginC

theprogramdoes,b)whatsomelinesof codedo,andc)whatthevariablesare.

#include<stdio.h> #include<math.h>

rlc.c

/* / *Simpleprogramtocomputetheresonantfrequencyof *anRLCcircuit Notetheuseofindentation */ int main() { doublel;/*Inductanceinmillihenrys */ doublec; inmicrofarads*/ ;/* / Capacitance p / doubleomega;/*Resonancefrequencyinradianspersecond*/ doublef;/*ResonancefrequencyinHertz*/ p printf("Enter ( theinductanceinmillihenrys: y "); ); scanf("%lf",&l); printf("Enterthecapacitanceinmicrofarads:"); ( ,&c); ); scanf("%lf", omega=1.0/sqrt((l/1000)*(c/1000000)); f=omega/(2*M_PI); printf("Resonant p ( frequency: q y %.2f\n", ,f); ); }
5 CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<math.h>

rlc.c

/* / *Simpleprogramtocomputetheresonantfrequencyof *anRLCcircuit Indentationisnecessaryto */

makeyourprogramreadable!
int main() { doublel;/*Inductanceinmillihenrys */ ;/ p / doublec; /*Capacitance inmicrofarads*/ doubleomega;/*Resonancefrequencyinradianspersecond*/ doublef;/*ResonancefrequencyinHertz*/ printf("Entertheinductanceinmillihenrys:"); scanf("%lf", ( ,&l); ); printf("Enterthecapacitanceinmicrofarads:"); scanf("%lf",&c); omega=1.0/sqrt((l/1000)*(c/1000000)); f=omega g /(2 ( *M_PI); ); printf("Resonantfrequency:%.2f\n",f); }

CSE251Dr.CharlesB.Owen ProgramminginC

SequentialExecution

Statement1

Statement2

...

Statementn

CSE251Dr.CharlesB.Owen ProgramminginC

SelectiveExecution

true

boolean expression

false

statement1

statement2

CSE251Dr.CharlesB.Owen ProgramminginC

ifstatements
Theifstatement Fundamentalmeansofflowcontrol Howwewillmakedecisions

if(age ( g >39) ) printf(Youaresoold!\n);

Booleanexpressions Theactualdeterminationof thedecision

age>39 c==0 l<=0 (age>= > 18) 8)&&(age<65)

CSE251Dr.CharlesB.Owen ProgramminginC

Structureofan ifstatement

Ifexpression1istrue,executestatement1. Otherwise testtoseeifexpression2istrue. true If Otherwise, so,executestatement2.

if(expression1) Otherwise,executestatement3. statement1; elseif(expression2) /*Optional*/ statement2; else /*Optional*/ statement3;


Theexpressionsareboolean expressionsthat resolvetoatrueorafalse.

10

CSE251Dr.CharlesB.Owen ProgramminginC

BasicBooleanExpressions Someoperators:
true false age<18 divisor==0 size>1000000 ch ==X < <= == != >= > Lessthan Lessthanorequalto Equal Notequal Greaterthanorequal q to Greaterthan

Important:Thetestforequalityis==, not =.Thisisthemostcommonerrorin aCprogram. program

11

CSE251Dr.CharlesB.Owen ProgramminginC

Exampleifstatements
if(age<18) printf(Tooyoungtovote!\n);

< <= == != >= >

Lessthan Lessthanorequalto E l Equal Notequal Greaterthanorequalto Greaterthan

if(area==0) printf(Theplotisempty\n); else printf(Theplothasanareaof%.1f\n,area); if(val ( <0) ) printf(Negativeinputisnotallowed\n); elseif(val ==0) printf(Avalueofzeroisnotallowed\n); else printf(Thereciprocalis%.2f\n,1.0/val);

Notetheindentation
12

CSE251Dr.CharlesB.Owen ProgramminginC

Blocks
printf(Thisisastatement\n); {

SingleStatement Block

printf(Allitemsinacurlybrace\n); printf(asifthereareonestatement); printf(Theyareexecutedsequentially); }

13

CSE251Dr.CharlesB.Owen ProgramminginC

Whereisthisuseful?

if(value>0) { result=1.0/value; printf("Result i tf("R lt=%f\n", %f\ " result); lt) }

Iftheexpressionistrue, allofthestatementsin theblockareexecuted

14

CSE251Dr.CharlesB.Owen ProgramminginC

Whereisthisuseful?

if(value>0) { result=1.0/value; printf("Result i tf("R lt=%f\n", %f\ " result); lt) }

Willthesetwosections ofcodework differently?

if(value>0) result=1.0/value; printf("Result printf( Result=%f\n %f\n", ,result);

15

CSE251Dr.CharlesB.Owen ProgramminginC

Whereisthisuseful?
if(value>0) { result=1.0/value; i tf("R lt=%f\ " result); lt) printf("Result %f\n", }

Yes!

if(value>0) result=1.0/value; printf( Result=%f\n ,result); printf("Result %f\n",

Willalwaysexecute!

16

CSE251Dr.CharlesB.Owen ProgramminginC

NestedBlocks

Whatdoesthisdo?

if(bobsAge !=suesAge)/*!=means"notequal"*/ { printf("BobandSuearedifferentages\n"); if(b b A if(bobsAge >suesAge) A ) { printf("Infact,BobisolderthanSue\n"); if((bobsAge (( g 20) )>suesAge) g ) { printf("Wow,Bobismorethan20yearsolder\n"); } } }

17

CSE251Dr.CharlesB.Owen ProgramminginC

Importanceofindentation

Seehowmuchharder thisistoread?

if(bobsAge !=suesAge)/*!=means"notequal"*/ { printf("BobandSuearedifferentages\n"); if(bobsAge >suesAge) if(b b A A ) { printf("Infact,BobisolderthanSue\n"); if((bobsAge (( g 20) )>suesAge) g ) { printf("Wow,Bobismorethan20yearsolder\n"); } } }

18

CSE251Dr.CharlesB.Owen ProgramminginC

BooleanExpressions
Anexpressionwhosevalueistrueorfalse InC:
integervalueof0isfalse nonzero integervalueistrue

ExampleofBooleanexpressions:
age<40 graduation_year ==2010
Relationaloperator

19

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<stdbool.h>

Librarythatdefines:bool,true,false

int main() { constbool trueVar =true,falseVar =false; constint int3=3, 3 int8=8; printf("No'boolean'outputtype\n"); printf("bool trueVar:%d\n",trueVar); printf("bool falseVar:%d\n\n",falseVar); printf("int int3:%d\n",int3); printf("int int8:%d\n",int8); }

Whatdoesthe outputlooklike?

20

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<stdbool.h>

Librarythatdefines:bool,true,false

int main() { constbool trueVar =true,falseVar =false; constint int3=3, 3 int8=8; printf("No'boolean'outputtype\n"); printf("bool trueVar:%d\n",trueVar); printf("bool falseVar:%d\n\n",falseVar); printf("int int3:%d\n",int3); printf("int int8:%d\n",int8); }

Whatdoesthe outputlooklike?

21

CSE251Dr.CharlesB.Owen ProgramminginC

//Example3 E l 3(continued) ( ti d )

printf("\nint3 printf( \nint3comparators\n comparators\n"); ); printf("int3==int8:%d\n",(int3==int8)); printf("int3 printf( int3!= ! int8:%d\n %d\n",(int3!=int8)); ,(int3! int8)); printf("int3<3:%d\n",(int3<3)); printf("int3<=3:%d\n",(int3<=3)); printf("int3>3:%d\n",(int3>3)); printf("int3>=3:%d\n",(int3>=3));
Comparingvaluesof twointeger constants Whatdoesthe outputlooklike?

22

CSE251Dr.CharlesB.Owen ProgramminginC

//Example3 E l 3(continued) ( ti d )

printf("\nint3 printf( \nint3comparators\n comparators\n"); ); printf("int3==int8:%d\n",(int3==int8)); printf("int3 printf( int3!= ! int8:%d\n %d\n",(int3!=int8)); ,(int3! int8)); printf("int3<3:%d\n",(int3<3)); printf("int3<=3:%d\n",(int3<=3)); printf("int3>3:%d\n",(int3>3)); printf("int3>=3:%d\n",(int3>=3));

23

CSE251Dr.CharlesB.Owen ProgramminginC

MoreExamples
charmyChar =A;
ThevalueofmyChar==Qisfalse(0)

Becarefulwhenusingfloatingpointequality comparisons,especiallywithzero,e.g.myFloat==0

24

CSE251Dr.CharlesB.Owen ProgramminginC

Suppose?
WhatifIwanttoknowifavalueisinarange? Testfor:100L1000?

25

CSE251Dr.CharlesB.Owen ProgramminginC

Youcantdo

ThiscodeisWRONG andwillfail.

if(100<=L<=1000) { printf( Valueisinrange\n ); printf(Value range \n); }

26

CSE251Dr.CharlesB.Owen ProgramminginC

Whythisfails

CTreatsthiscode thisway

if((100<=L)<=1000) { printf( Valueisinrange\n ); printf(Value range \n); } SupposeLis5000.Then100<=Listrue,so(100<=L) evaluatestotrue,which,inC,isa1.Thenittests1<=1000, whichalsoreturnstrue, ,eventhough g you y expected p afalse.

27

CSE251Dr.CharlesB.Owen ProgramminginC

CompoundExpressions
Wanttocheckwhether3<=B<=1
SinceB=2,answershouldbeTrue(1)

ButinC,theexpressionisevaluatedas
((3<=B)<=1)(<=isleftassociative) (3<=B)istrue(1) (1<=1)isfalse(0) Th f Therefore, answeris i 0!

28

CSE251Dr.CharlesB.Owen ProgramminginC

CompoundExpressions
Solution(notinC):(3<=B)and(B<=1) InC:(3<=B)&&(B<=1) g Operators p Logical
And:&& Or:|| Not:!

29

CSE251Dr.CharlesB.Owen ProgramminginC

CompoundExpressions
#i l d <stdio.h> #include tdi h int main() { constint A=2,B=2; printf("ValueofAis%d\n",A); printf("0<=A<=5?:Answer=%d\n",(0<=A)&&(A<=5)); printf("ValueofBis%d\n",B); printf("3<=B<=1?:Answer=%d\n",(3<=B)&&(B<=1)); }

30

CSE251Dr.CharlesB.Owen ProgramminginC

CompoundExpressions
#include<stdio.h> <stdio h> int main() { constint A=2,B=2; printf("ValueofAis%d\n",A); printf("0 printf( 0<=A<=5?:Answer=%d\n" Answer=%d\n ,(0<=A)&&(A<=5)); printf("ValueofBis%d\n",B); printf("3<=B<=1?:Answer=%d\n",(3<=B)&&(B<=1)); } True(1) True(1)
Correct Answer!!!

31

CSE251Dr.CharlesB.Owen ProgramminginC

CompoundExpressions
#include<stdio.h> <stdio h> int main() { constint A=2,B=2; printf("ValueofAis%d\n",A); printf("0 printf( 0<=A<=5?:Answer=%d\n" Answer=%d\n ,(0<=A)&&(A<=5)); printf("ValueofBis%d\n",B); printf("3<=B<=1?:Answer=%d\n",(3<=B)&&(B<=1)); } True(1)
&& Correct Answer!!!

True(1)

True(1)

32

CSE251Dr.CharlesB.Owen ProgramminginC

Truth Tables
N Not A d And O Or

p True True False False

q True False True False

!p

p && q p || q

33

CSE251Dr.CharlesB.Owen ProgramminginC

Truth Tables
N Not A d And O Or

p True True False False

q True False True False

!p False False True True

p && q p || q

34

CSE251Dr.CharlesB.Owen ProgramminginC

Truth Tables
N Not A d And O Or

p True True False False

q True False True False

!p

p && q p || q True False False False

35

CSE251Dr.CharlesB.Owen ProgramminginC

Truth Tables
N Not A d And O Or

p True True False False

q True False True False

!p

p && q p || q True True True False

36

CSE251Dr.CharlesB.Owen ProgramminginC

Truth Tables
N Not

Ourcomparisonoperators: <<===!=>=> A d And O Or

p True True False False

q True False True False

!p False False True True

p && q p || q True False False False True True True False

37

CSE251Dr.CharlesB.Owen ProgramminginC

Precedence&Associativity
Canyouguesswhat whats stheanswer?

Relationaloperatorshave precedenceandassociativity (justlikearithmeticoperators) Use()whenindoubt

38

CSE251Dr.CharlesB.Owen ProgramminginC

(((A+B)>5)&&(((A=0)<1)>((A+B) 2))) ((6>5)&&(((A=0)<1)>((A+B) 2))) (1&&((0<1)>((A+B) 2))) (1&&(1>(2 2))) (1&&(1>0)) (1&&1) Answer:1
Precedence: +/ >< &&
CSE251Dr.CharlesB.Owen ProgramminginC

39

Associativity
=isrightassociative Example:X=Y=5

rightassociative:X=(Y (Y=5) 5) expressionY=5returns value5:X=5

40

CSE251Dr.CharlesB.Owen ProgramminginC

Youshouldrefertothe Coperatorprecedence andassociativetable


Seeforexample, http://www.difranco.net/cop2220/op p prec.htm

Orjustuse parentheseswhenever youreunsureabout precedence d and d associativity

41

CSE251Dr.CharlesB.Owen ProgramminginC

SwitchStatement
Alessgeneralsubstituteforthemultibranch if.Itisused forselectingamongdiscretevalues(int),i.e.not continuousvalues values. switch(int_expression) { case_list: statement_list; ; case_list: statement_list; default: statement_list; }
Switch&Functions CSE251Dr.CharlesB.Owen
42 ProgramminginC

Behavior
Theint_expression isevaluated.Ifthevalueis inacase_list,executionbeginsatthat statement_list andcontinuesthrough subsequentstatement_lists until:break, return,orendofswitch. switch

Switch&Functions CSE251Dr.CharlesB.Owen
43 ProgramminginC

#include<stdio.h> voidmain() { int gender; printf("Enteryourgender(male=1,female=2):"); scanf("%d",&gender); f("%d" & d ) switch(gender) { case1: printf("Youareamale\n"); break; case2: printf("youareafemale\n"); break; default: printf("Notavalidinput\n"); break; } }
44

CSE251Dr.CharlesB.Owen ProgramminginC

switch(gender) { case1: printf("Youareamale\n"); break; case2: printf("you i f(" areafemale\n"); f l \ ") break; default: printf("Not printf( Notavalidinput\n"); input\n ); break; }

45

CSE251Dr.CharlesB.Owen ProgramminginC

LoopsandRepetition
condition true int count=1 statement false

true

false count t<=5

statement count++

CSE251Dr.CharlesB.Owen ProgramminginC

doubleincome; int filingStatus; int numDependents; int children; doublestandardDeduction; doubledeductions; doubletaxableIncome; doubletax;

First,thetaxprogram

printf("Enteryourannualincome:"); scanf("%lf" scanf( %lf ,&income); if(income<9350) { printf("Youmaybepoor,butyouowenotaxes\n"); exit(0); }

CSE251Dr.CharlesB.Owen ProgramminginC

printf("Whatisyourfilingstatus?\n1)single\n); printf(2)marriedfilingjointly\n3)marriedfilingseparately\n"); printf("Pleaseenteranumber:"); scanf("%d",&filingStatus); switch(filingStatus) { case1: numDependents =1; standardDeduction =5700; break; case2: printf("How printf( Howmanychildrendoyouhave?"); ); scanf("%d",&children); numDependents =children+2; standardDeduction =11400; break; case3: numDependents =1; standardDeduction =5700; break; default: printf("Invalidinput!\n"); exit(1); b break; k }
3 CSE251Dr.CharlesB.Owen ProgramminginC

deductions=standardDeduction +numDependents *3650; taxableIncome =income deductions; if(taxableIncome ( <0) ) { tax=0; } elseif(taxableIncome ( <=16750) ) { tax=taxableIncome *0.10; } elseif(taxableIncome ( <=68000) ) { tax=1675+0.15*(taxableIncome 16750); } elseif(taxableIncome ( <=137300) ) { tax=9362.50+0.25*(taxableIncome 68000); } else { tax=26687.50+0.28*(taxableIncome 137300); } printf("%.2f\n",tax);
4 CSE251Dr.CharlesB.Owen ProgramminginC

LoopsandRepetition
Loopsinprogramsallowusto repeat p blocksofcode. Usefulfor: Tryingagainforcorrectinput Counting Repetitiveactivities Programsthatneverend

CSE251Dr.CharlesB.Owen ProgramminginC

ThreeTypesofLoops/RepetitioninC
while
toptestedloop(pretest)

for
countingloop foreversentinel

do
bottomtestedloop(posttest)

CSE251Dr.CharlesB.Owen ProgramminginC

Thewhile loop Toptested dl loop(pretest) ( )


while(condition) statement; Notethat,asinIFselection,onlyonestatement isexecuted.Youneedablocktorepeatmore thanonestatement(using{})

CSE251Dr.CharlesB.Owen ProgramminginC

while(condition)statement;

condition true statement

false

CSE251Dr.CharlesB.Owen ProgramminginC

Similartotheifstatement
Checktheboolean condition Iftrue,executethestatement/block Repeat p theaboveuntiltheboolean isfalse

CSE251Dr.CharlesB.Owen ProgramminginC

Example
bool valid=true; //Untilweknowotherwise printf("Entertheinductanceinmillihenrys:"); scanf("%lf",&l); /*Testtoseeiftheuserenteredaninvalidvalue*/ if(l<=0) { printf("Youmoron,youenteredaninvalidinductance!\n"); valid=false; } else printf("Okay,Iguessthat'sreasonable\n");

Rememberthis?Whatifwe inputinvalidvalues?

10

CSE251Dr.CharlesB.Owen ProgramminginC

bool valid=false;/*Untilweknowotherwise*/ while(!valid)/*Loopuntilvalueisvalid*/ { printf("Entertheinductanceinmillihenrys:"); scanf("%lf",&l);

Examplewith whileloop

/ Testtoseeiftheuserenteredaninvalidvalue*/ /* / if(l<0) { printf("Youmoron,youenteredanegativeinductance!\n"); } elseif(l==0) { printf("Youarereallydumb,youenteredzero.\n"); } else { printf("Okay,Iguessthat'sreasonable\n"); valid=true; ; } }

Whatdoesthisdodifferent?

11

CSE251Dr.CharlesB.Owen ProgramminginC

while
while(condition) statement; while(condition) { statement1; statement2; }

condition true statement t t t

false

while(!valid) until hil (! lid)/*Loop L tilvalue l is i valid lid*/ { printf("Entertheinductanceinmillihenrys:"); scanf("%lf",&l); if(l>0) { valid=true; } }

inti=10; while(i>0) { printf("i=%d\n",i); i=i 1; }

12

CSE251Dr.CharlesB.Owen ProgramminginC

Foreverloopsandneverloops
Becausetheconditionalcanbealwaystrueor alwaysfalse,youcangetaloopthatrunsforever orneverrunsat tall. ll
int count=0; while(count!=0) printf(HiMom); while(count=1) (count 1) count=0;

Whatiswrongwith thesestatements?

//insidiouserror!!!

13

CSE251Dr.CharlesB.Owen ProgramminginC

Howtocountusingwhile
First,outsidetheloop,initializethecountervariable Testforthecountersvalueintheboolean Dothebodyoftheloop ginthebody yshouldchange g thevalueofthe Lastthing counter! i=1;
while(i<=10) { printf("i=%d\n",i); i=i+1; }

14

CSE251Dr.CharlesB.Owen ProgramminginC

Thefor loop
Thewhile loopisprettygeneral.Anythingthatcan bedoneusingrepetitioncanbedonewithawhile loop Becausecountingissocommon,thereisa specializedconstructcalledaforloop. Aforloopmakesiteasytosetupacountingloop

15

CSE251Dr.CharlesB.Owen ProgramminginC

Threeparts

for(count=1;count<=5;count++) statement;

Threepartstoaforloop(justlikethewhile): Settheinitialvalueforthecounter Settheconditionforthecounter Sethowthecounterchangeseachtimethroughthe loop

16

CSE251Dr.CharlesB.Owen ProgramminginC

for(count=1;count<=5;count++) printf(count=%d\n, printf( count %d\n ,count);


count=1

true printf count++

count<=5

false

17

CSE251Dr.CharlesB.Owen ProgramminginC

Ascendingfor <=,++ ,

for(control_var=init_value; control_var <=limit_value; control var++)statement; control_var++)

control_var =init_value

true

control_var <=limit_value

false

statement control_var++

18

CSE251Dr.CharlesB.Owen ProgramminginC

Descendingfor > >=,

for(control_var=init_value; control_var >=limit_value; control var)statement; control_var

control_var =init_value

true

control_var >=limit_value

false

statement control_var

19

CSE251Dr.CharlesB.Owen ProgramminginC

Comments Itisdangerous d toalter l control_var l orlimit_var l withinthebodyoftheloop.


Thecomponentsofthefor statementcanbea arbitrarystatements statements,e e.g. g theloopconditionmay beafunctioncall.

20

CSE251Dr.CharlesB.Owen ProgramminginC

for(count=1;count<=5;count++) printf(count=%d\n, printf( count %d\n ,count);


for(i=1;i<=10;i++) { printf("%d\n",i); } for(t ( =1.7; ;t<3.5; ;t=t+0.1) ) { printf("%f\n",t); }

count=1

true printf

count<=5

false

count++

for(i=1;i<5;i++) { for(j=1;j<4;j++) { printf("%d*%d=%d\n",i,j,i *j); } }


2
CSE251Dr.CharlesB.Owen ProgramminginC

21

Top ptestedEquivalence q
Thefollowingloop for(x=init;x<=limit;x++) statement_list isequivalentto x=init; while(x<=limit){ statement_list; x++; }

22

CSE251Dr.CharlesB.Owen ProgramminginC

SomeMagicStatements
s+=12; s=13; /*Equivalenttos=s+12;*/ /*Equivalenttos=s 13;*/ Theseworkfinefor integersorfloatingpoint

23

CSE251Dr.CharlesB.Owen ProgramminginC

break;
Thebreakstatementexitsthecontainingloopimmediately!
while(true)/*Loopuntilvalueisvalid*/ { printf("Entertheinductanceinmillihenrys:"); scanf("%lf",&l); / Testtoseeiftheuserenteredaninvalidvalue*/ /* / if(l<=0) { printf("Youmoron,youenteredaninvalidinductance!\n"); } else { printf("Okay,Iguessthat'sreasonable\n"); break; } }

24

CSE251Dr.CharlesB.Owen ProgramminginC

Thedo/whileloop
do/while

Oftenjustcalledadoloop.

bottomtestedloop(posttest)
do { angle+= + 2*M_PI M PI/20; sinVal =sin(angle); printf(sin(%f)=%f\n,angle,sinVal); }while( (sinVal <0.5); )

25

CSE251Dr.CharlesB.Owen ProgramminginC

BottomtestedLoop:do
Bottomtested(posttest) Onetripthroughloopisguaranteed,i.e. statement is i executed datleast l once
do statement while(loop_condition); do { statement1; statement2; } while(loop_condition);

Usually!

26

CSE251Dr.CharlesB.Owen ProgramminginC

do{statement;}while(condition)
statement;

true

condition

false

27

CSE251Dr.CharlesB.Owen ProgramminginC

do/whileExamples
angle=M_PI/2; do { angle=0.01; cosVal =cos(angle); printf("cos(%f)=%f\n", p ( ( ) \ ,angle, g ,cosVal); ); }while(cosVal <0.5); do {

i =0; do { i++; printf("%d\n",i); }while(i hil (i <10); 10)

printf( Enteravalue>0:"); printf("Enter ); scanf("%lf",&val); }while(val <=0);

28

CSE251Dr.CharlesB.Owen ProgramminginC

BottomtestedEquivalence
Bottomtesteddoloop(posttest) do { statement; } while(condition); ( ); Similartobottomtestedforeverloop for(;;) { statement_list; if(!condition)break; }

29

CSE251Dr.CharlesB.Owen ProgramminginC

Theoneofferror
Itiseasytogetaforloop tobeoneoffofthe numberyouwant.Be carefulofthe combinationofinit_value init value and<vs.<= Countingfrom0,with<, isagoodcombination andgoodforinvariantsas well.
30

for(i=1;i<10;i++) { } for(i=1; for(i 1;i<=10; i< 10;i++) { } for(i=0;i<10;i++) { }

CSE251Dr.CharlesB.Owen ProgramminginC

Theoneofferror
Itiseasytogetaforloop tobeoneoffofthe numberyouwant.Be carefulofthe combinationofinit_value init value and<vs.<= Countingfrom0,with<, isagoodcombination andgoodforinvariantsas well.
31

for(i=1;i<10;i++) { 9values: l 1to9 } for(i=1; for(i 1;i<=10; i< 10;i++) { 10values:1to10 } for(i=0;i<10;i++) { 10values:0to9 }

CSE251Dr.CharlesB.Owen ProgramminginC

while,for,do/while
for(t=1.7; 1 7;t<3 3.5; 5;t=t+0.1) 0 1) { printf("%f\n",t); } i =0; do { i++; printf("%d\n" printf( %d\n ,i); }while(i <10); do {

for(i=1;i<=10;i++) { printf("%d\n",i); }

printf("Enteravalue>0:"); scanf("%lf" scanf( %lf ,&val); }while(val <=0);

for(i=1;i<5;i++) { for(j=1;j<4;j++) { printf("%d*%d=%d\n",i,j,i *j); } }is while(!valid) hil (! lid)/*Loop L until tilvalue l i valid lid*/ i ti=10; int 10 { while(i>0) printf("Entertheinductanceinmillihenrys:"); { scanf("%lf",&l); printf("i=%d\n",i); angle=M_PI/2; i=i 1; ; if(l>0) do } { valid=true; { } angle=0.01; } cosVal =cos(angle); printf("cos(%f)=%f\n" printf( cos(%f)=%f\n ,angle, angle cosVal); }while(cosVal <0.5);
32

CSE251Dr.CharlesB.Owen ProgramminginC

Functions

CSE251Dr.CharlesB.Owen ProgramminginC

MoonLandings
Time WillCyr YongjiaoYu BinTian NanXia
ChenliYuan

Fuel 13 13 13 13 13 13 13 86.20 86.00 87 00 87.00 87.00 87.00 87.70 87.88

Velocity 0.49 1.82 1.69 1 69 1.69 1.69 2.74 3.00

ScottOliver MikeRobell

CSE251Dr.CharlesB.Owen ProgramminginC

TriangleAreaComputation
p3=(x3,y3) c p2=(x2 y2) p2=(x2,y2) b a p1=(x1,y1)

a = p 2 p1 b = p3 p1 c = p3 p 2
a = ( x 2 x1) 2 + ( y 2 y1) 2

area =

p ( p a )( p b)( p c)

a+b+c p= 2 Howwouldyouwritethisprogram?

CSE251Dr.CharlesB.Owen ProgramminginC

intmain() { doublex1=0 x1=0,y1=0; doublex2=17,y2=10.3; doublex3=5.2,y3=5.1;

Variables

doublea,b,c;/*Trianglesidelengths*/ doublep;/*ForHeron'sformula*/ doublearea;

a = p 2 p1

b = p3 p1 c = p3 p 2
a = ( x 2 x1) 2 + ( y 2 y1) 2

CSE251Dr.CharlesB.Owen ProgramminginC

LengthsofEdges
a=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2)); b=sqrt((x1 x3)*(x1 x3)+(y1 y3)*(y1 y3)); c=sqrt((x2 x3)*(x2 x3)+(y2 y3)*(y2 y3));

a = p 2 p1 b = p3 p1
p3=(x3,y3) c p2=(x2,y2) b a

c = p3 p 2
a = ( x 2 x1) 2 + ( y 2 y1) 2 p ( p a )( p b)( p c)

area =
p1=(x1,y1)

a+b+c p= 2
CSE251Dr.CharlesB.Owen ProgramminginC

p=(a+b+c)/2; area=sqrt(p q (p*(p a) )*(p b) )*(p c)); )); printf("%f\n",area);

Area
p ( p a )( p b)( p c)

area =

a+b+c p= 2

CSE251Dr.CharlesB.Owen ProgramminginC

intmain() { doublex1=0,y1=0; doublex2=17,y2=10.3; doublex3=5.2,y3=5.1;

WholeProgram
WhatifImade Wh d amistake i k on theedgelengthequation?

doublea,b,c;/ /*Trianglesidelengths*/ / doublep;/*ForHeron'sformula*/ doublearea; a=sqrt((x1 t(( 1 x2) 2)*(x1 ( 1 x2) 2)+( (y1 1 y2) 2)*(y1 ( 1 y2)); 2)) b=sqrt((x1 x3)*(x1 x3)+(y1 y3)*(y1 y3)); c=sqrt((x2 x3)*(x2 x3)+(y2 y3)*(y2 y3)); p=(a+b+c)/2; area=sqrt(p*(p a)*(p b)*(p c)); printf("%f\n" printf( %f\n ,area); }

CSE251Dr.CharlesB.Owen ProgramminginC

Functions
Functionsaresubprogramsthatperformsome operationandreturnone value Theyencapsulatesomeparticularoperation,soit canbereusedbyothers(forexample,theabs()or sqrt() ()f function) i )

CSE251Dr.CharlesB.Owen ProgramminginC

Characteristics
Reusablecode
codeinsqrt()isreusedoften

Encapsulatedcode
implementationofsqrt()ishidden

Canbestoredinlibraries
sqrt()isabuiltinfunctionfoundinthemathlibrary

CSE251Dr.CharlesB.Owen ProgramminginC

WritingYourOwnFunctions
Considerafunctionthatconvertstemperaturesin CelsiustotemperaturesinFahrenheit.
MathematicalFormula: F=C*1.8 1 8+32.0 32 0 WewanttowriteaCfunctioncalledCtoF

10

CSE251Dr.CharlesB.Owen ProgramminginC

ConvertFunctioninC
doubleCtoF(doubleparamCel) { returnparamCel*1.8+32.0; } Thisfunctiontakesaninputparametercalled paramCel(tempindegreeCelsius)andreturnsa valuethatcorrespondstothetempindegree Fahrenheit a e e

11

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> doubleCtoF(double);

Howtousea function?

/************************************************************************ *Purpose:toconverttemperaturefromCelsiustoFahrenheit ************************************************************************/ intmain() { doublec,f; printf(Enterthedegree(inCelsius):); scanf(%lf,&c); f=CtoF(c); printf(Temperature(inFahrenheit)is%lf\n,f); } doubleCtoF(doubleparamCel) { returnparamCel*1.8+32.0; }

12

CSE251Dr.CharlesB.Owen ProgramminginC

Terminology Declaration: D l ti

d bl Ct double CtoF( F(d double bl ); )

Invocation(Call):Fahr=CtoF(Cel); Definition: doubleCtoF(doubleparamCel) { returnparamCel*1.8+32.0; }

13

CSE251Dr.CharlesB.Owen ProgramminginC

FunctionDeclaration Also l called ll dfunction f prototype:


return_type function_name (parameter_list)

double CtoF(double) ( )

Declarationsdescribethefunction:
thereturntypeandfunctionname thetypeandnumberofparameters

14

CSE251Dr.CharlesB.Owen ProgramminginC

return_type function_name (parameter_list) { . functionbody . }

Function Definition

double CtoF(doubleparamCel) { returnparamCel*1.8+32.0; }

15

CSE251Dr.CharlesB.Owen ProgramminginC

FunctionInvocation
int main() { f = CtoF(c); }

1. Call 1 C ll copies i argument c to parameter t paramCel


double CtoF ( double paramCel ) { return paramCel*1.8 + 32.0; }

2. Control transfers f to function C F CtoF

16

CSE251Dr.CharlesB.Owen ProgramminginC

Invocation(cont)
int main() { f = CtoF(c); }

3. Expression in CtoF is evaluated


double CtoF ( double paramCel ) { return paramCel*1.8 paramCel*1 8 + 32 32.0; 0; }

4. Value of expression is returned to main main

17

CSE251Dr.CharlesB.Owen ProgramminginC

LocalObjects
TheparameterparamCelisalocalobjectwhichis definedonlywhilethefunctionisexecuting.Any attempttouseparamCeloutsidethefunctionisan error. Thenameoftheparameterneednotbethesameas th nameof the fth theargument. t T Typesmust tagree.

18

CSE251Dr.CharlesB.Owen ProgramminginC

intmain() { doublex1=0,y1=0; doublex2=17, x2 17 y2=10.3; y2 10 3 doublex3=5.2,y3=5.1; doublea,b,c;/*Trianglesidelengths*/ doublep;/*ForHeron'sformula*/ doublearea;

Canwedobetterthan this?

a=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2)); b=sqrt((x1 x3)*(x1 x3)+(y1 y3)*(y1 y3)); c=sqrt((x2 x3)*(x2 x3)+(y2 y3)*(y2 y3)); p=(a+b+c)/2; area=sqrt(p*(p a)*(p b)*(p c)); printf("%f\n" printf( %f\n ,area); }

19

CSE251Dr.CharlesB.Owen ProgramminginC

Whatshouldwenameourfunction?
a=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2));

Length Length soundslikeagoodidea. idea


???Length(???) { }

20

CSE251Dr.CharlesB.Owen ProgramminginC

Whatdoesourfunctionneedtoknow?
a=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2));

(x,y)fortwodifferentpoints: ???Length(doublex1,doubley1, doublex2,doubley2) { }

21

CSE251Dr.CharlesB.Owen ProgramminginC

Whatdoesourfunctionreturn?
a=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2));

Acomputedvaluewhichisoftypedouble double Length(doublex1,doubley1, doublex2,doubley2) { }

22

CSE251Dr.CharlesB.Owen ProgramminginC

Howdoesitcomputeit?
a=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2));

Acomputedvaluewhichisoftypedouble double Length(doublex1,doubley1, doublex2,doubley2) { doublelen; len=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2)); return(len); }

23

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<math.h> /*Declaration*/ doubleLength(doublex1,doubley1,doublex2,doubley2); /* *Programtodeterminetheareaofatriangle */ intmain() { doublex1=0,y1=0; doublex2=17,y2=10.3; doublex3=5.2,y3=5.1; doublea,b,c;/*Trianglesidelengths*/ d bl p;/*ForHeron's ' f l */ double formula doublearea; a=Length(x1,y1,x2,y2); b=Length(x1,y1,x3,y3); c=Length(x2,y2,x3,y3); p=(a+b+c)/2; area=sqrt(p*(p a)*(p b)*(p c)); printf("%f\n",area); } /*Definition*/ doubleLength(doublex1,doubley1,doublex2,doubley2) { doublelen; len=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2)); return(len); }

UsingThis
Declaration

Invocations

Definition

24

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> doubleconvert(double);

PotentialErrors

intmain() { doublec,f; printf(Enterthedegree(inCelsius):); scanf(%lf, scanf( %lf ,&c); f=convert(c); printf(Temp(inFahrenheit)for%lfCelsiusis%lf,paramCel,f); } doubleCtoF(doubleparamCel) { returnc *1.8+32.0; } Error!Cisnotdefined

Error!paramCelisnotdefined

Scope Whereavariableis knowntoexist. exist Novariableisknownoutsideof thecurlybracesthatcontainit, evenifthesamenameisused!

25

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> doubleGetTemperature(); p (); doubleCelsiusToFahrenheit(double); voidDisplayResult(double,double);

Another Example
Declarations

intmain() { double TempC,//TemperatureindegreesCelsius TempF;//TemperatureindegreesFahrenheit TempC=GetTemperature(); TempF=CelsiusToFahrenheit(TempC); DisplayResult(TempC,TempF); return0; }

Invocations

26

CSE251Dr.CharlesB.Owen ProgramminginC

doubleGetTemperature() { doubleTemp; p;

Function: GetTemperature

printf("\nPleaseenteratemperatureindegreesCelsius:"); scanf("%lf",&Temp); returnTemp; }

27

CSE251Dr.CharlesB.Owen ProgramminginC

Function:CelsiusToFahrenheit
doubleCelsiusToFahrenheit(doubleTemp) { return(Temp*1.8+32.0); }

28

CSE251Dr.CharlesB.Owen ProgramminginC

Function:DisplayResult
voidDisplayResult(doubleCTemp,doubleFTemp) { printf("Original:%5.2fC\n",CTemp); printf("Equivalent: printf( Equivalent:%5.2f %5 2fF\n F\n",FTemp); return; }

29

CSE251Dr.CharlesB.Owen ProgramminginC

Declarations(Prototypes)
doubleGetTemp(); doubleCelsiusToFahrenheit(double); voidDisplay(double,double);

void meansnothing. g Ifafunctiondoesntreturna value,itsreturntypeisvoid

30

CSE251Dr.CharlesB.Owen ProgramminginC

Abstraction

intmain() { double TempC //TemperatureindegreesCelsius TempC, TempF;//TemperatureindegreesFahrenheit TempC=GetTemperature(); TempF=CelsiusToFahrenheit(TempC); ( ) DisplayResult(TempC,TempF); return0; }

1. Get Temperature 2. Convert Temperature p 3. Display Temperature

Wearehidingdetailsonhow something isdoneinthefunctionimplementation.

31

CSE251Dr.CharlesB.Owen ProgramminginC

AnotherWaytoComputeFactorial
Pseudocode forfactorial(n)
ifn==0then result=1 else result=n*factorial(n 1) Afterall,5!=5*4*3*2*1=5*4!

32

CSE251Dr.CharlesB.Owen ProgramminginC

RecursiveFunctions

Factorialfunctioncontainsan invocationofitself.

intFactorial(intn) { Wecallthisa:recursivecall. if(n==0) return t 1 1; else returnn*Factorial(n1); }

Thisworksmuchlike proofbyinduction. induction

Recursivefunctionsmust haveabasecase (ifn==0):why? ifn==0then result=1 else result=n*factorial(n 1)

33

CSE251Dr.CharlesB.Owen ProgramminginC

InfiniteRecursion
intFactorial(intn) { returnn*Factorial(n1); }

WhatifIomitthebasecase? Thisleadstoinfiniterecursion!

Factorial(3)= 3*Factorial(2)= 3*2*Factorial(1)= 3*2*1*Factorial(0)= 3*2*1*0*Factorial(1)=

cbowen@ubuntu:~/cse251$./combi1 Inputn:5 Inputk:3 Segmentationfault

34

CSE251Dr.CharlesB.Owen ProgramminginC

PsuedocodeandFunction

intFactorial(intn) { if(n==0) return 1; t 1 else returnn*Factorial(n1); }

ifn==0then result=1 else result=n*factorial(n 1) BaseCase

Declaration:intFactorial(intn); Invocation:f=Factorial(7);
intFactorial(intn) { if(n==0) return1; else returnn*Factorial(n1); }

Definition f :

35

CSE251Dr.CharlesB.Owen ProgramminginC

PointersandReferenceparameters

CSE251Dr.CharlesB.Owen ProgramminginC

TodaysLecture
Address 0 4520 0x4520 0x4524 Variable B pB Value 181 0x4520

Pointersarevariablesthat storememoryaddresses
MemoryAddress

Beforewelearnabout Address pointers,wemustlearn 0x4520 moreaboutaddresses 0x4524


Pointer

Variable B pB

Value 181 0x4520

Value

CSE251Dr.CharlesB.Owen ProgramminginC

ComputerMemory
Memoryisjustalonglistof numbersoneaftertheother Mylaptophasover4Billionof thesenumbers

Eachnumberis8bits(BYTE) Wecombinethemtomake integersandfloatingpointvalues

CSE251Dr.CharlesB.Owen ProgramminginC

Computer Memory

int (21)

float(18.2)

CSE251Dr.CharlesB.Owen ProgramminginC

MemoryAddresses
Memoryaddressesincomputersareoften32bits(or nowadays,64bits)long,e.g. 01111111111111111111101010001100 Anotherwaytorepresentanaddressistouse hexadecimal: 0x7ffffa8c

CSE251Dr.CharlesB.Owen ProgramminginC

Hexadecimal(Base16)
Ihaveincludedthis chartony your worksheetsoyoucan refertoit.

0000=0 0001=1 0010=2 0011=3 0100=4 0101=5 0110=6 0111=7

1000=8 1001=9 1010=10=a 1011=11=b 1100=12=c 1101=13=d 1110=14=e 1111=15=f

CSE251Dr.CharlesB.Owen ProgramminginC

Addresses 32bit b address dd ( (Binary): ) 01111111111111111111101010001100 7ff f f a8c


32bitaddress(Hex):0x7ff f f a8c Notes:
InC0xindicatesaHexadecimalnumber Converteveryfourbitstoahexdigit

CSE251Dr.CharlesB.Owen ProgramminginC

Arithmetic(inHex)
Sum: 0x 90 +0x 04 0x 94

0000=0 0001=1 0010=2 0011=3 0100=4 0101=5 0110=6 0111=7

1000=8 1001=9 1010=10=a 1011=11=b 1100=12=c 1101=13=d 1110=14=e 1111=15=f

CSE251Dr.CharlesB.Owen ProgramminginC

Arithmetic(inHex)
Sumwithcarry: 0x 8c +0x 04 0x??

0000=0 0001=1 0010=2 0011=3 0100=4 0101=5 0110=6 0111=7

1000=8 1001=9 1010=10=a 1011=11=b 1100=12=c 1101=13=d 1110=14=e 1111=15=f

CSE251Dr.CharlesB.Owen ProgramminginC

Arithmetic(inHex)
Sumwithcarry: 0x 8c +0x 04 0x??

Whatisc+4? Indecimalitis12+4=16 which hi his i Hex H 10(0and dcarry1)

10

CSE251Dr.CharlesB.Owen ProgramminginC

Arithmetic(inHex)
Sumwithcarry:

0x 8c +0x 04 0x??

Whatisc+4? Indecimalitis12+4=16 which hi his i Hex H 10(0and dcarry1)

11

CSE251Dr.CharlesB.Owen ProgramminginC

Arithmetic(inHex)
Sumwithcarry:

0x 8c +0x 04 0x90

Whatisc+4? Indecimalitis12+4=16 which hi his i Hex H 10(0and dcarry1)

12

CSE251Dr.CharlesB.Owen ProgramminginC

BytesandWords
byte word

Remember 8bits=1byte 32bits=4bytes=1word.


32bitaddressmachinesare addressedbybytesso consecutivewordshave addressesthatdifferbyfour

13

CSE251Dr.CharlesB.Owen ProgramminginC

32bitAddresses
H arethree Here h consecutive i 32bit bi addresses dd (in (i Hex) H )of fwords: d 0x00712050 0x00712054 0x00712058 dcbb2100 01000000 00000000

14

CSE251Dr.CharlesB.Owen ProgramminginC

Pointers
Pointers arevariablesthatcontainaddresses
Justlikeothervariables,theymustbedeclaredbefore beingused

Declaration: int *p;/*insteadofint pforintegers*/


int *meanspisapointervariablethatstorestheaddress ofanintegervariable

15

CSE251Dr.CharlesB.Owen Programming inC parameters

PointersandRef

PointerInitialization
Declaration:
int a=2; /*aisaninteger*/ i t *pA int * A =&a; & /*pA A is i apointer i t containing t i i theaddressofa*/

&operatormeansaddressof Readitasat

16

CSE251Dr.CharlesB.Owen ProgramminginC

TheAddressGame

int a=2; int *pA =&a;


a p pA

AnIntelprocessoriscalledalittleendian processorbecauseitstoresvalueswiththeleast significantbytefirst.Youreaditinreverseorder. 0x00602104inmemorywillbe:04216000

17

CSE251Dr.CharlesB.Owen ProgramminginC

ExampleProgram
inta=21; int*pA=&a;

%xprintsthehexadecimalvalue Operators: p & addressof * dereference


Output

printf("%d\n",a); printf("%x\n",a); printf("% \n" &a); printf("%x\n", printf("%x\n",pA); printf("%d\n",*pA); printf("%x\n", p ( &pA); p )

21 15 bfee861c f bfee861c 21 bfee8618

18

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> int main() { int a=15,b=38; int *c=&a; printf("%x p ( :%d\n", \ ,&a, ,a); ); printf("%x:%d\n",&b,b); printf("%x:%x:%d\n",&c,c,*c); a=49; printf("%x:%d\n",&a,a); printf("%x:%d\n",&b,b); printf("%x p ( :%x:%d\n", \ ,&c, ,c, ,*c); ); c=&b; printf("%x:%d\n",&a,a); printf("%x printf( %x:%d\n %d\n",&b,b); b); printf("%x:%x:%d\n",&c,c,*c); }

19

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> int main() { int a=15,b=38; int *c=&a; printf("%x p ( :%d\n", \ ,&a, ,a); ); printf("%x:%d\n",&b,b); printf("%x:%x:%d\n",&c,c,*c); a=49; printf("%x:%d\n",&a,a); printf("%x:%d\n",&b,b); printf("%x p ( :%x:%d\n", \ ,&c, ,c, ,*c); ); c=&b; printf("%x:%d\n",&a,a); printf("%x printf( %x:%d\n %d\n",&b,b); b); printf("%x:%x:%d\n",&c,c,*c); }

20

CSE251Dr.CharlesB.Owen ProgramminginC

FirstSection

Declaresaandbasintegers Declarescasapointerthatcontainsthe address ofa( (points pointstoa a) )


Address Memory 15 38 0xeffffa94 Name a b c

int a=15 15,b=38; 0xeffffa94 int *c=&a; printf("%x:%d\n",&a,a); 0 ffff 90 0xeffffa90 printf("%x:%d\n",&b,b); printf("%x:%x:%d\n",&c,c,*c);
0xeffffa8c

21

CSE251Dr.CharlesB.Owen ProgramminginC

FirstSection

Declaresaandbasintegers Declarescasapointerthatcontainsthe address ofa( (points pointstoa a) )


Address Memory 15 38 0xeffffa94 Name a b c

int a=15 15,b=38; 0xeffffa94 int *c=&a; printf("%x:%d\n",&a,a); 0 ffff 90 0xeffffa90 printf("%x:%d\n",&b,b); printf("%x:%x:%d\n",&c,c,*c);
0xeffffa8c

Output: effffa9415 effffa9038 effffa8ceffffa9415

22

CSE251Dr.CharlesB.Owen ProgramminginC

FirstSection

Declaresaandbasintegers Declarescasapointerthatcontainsthe address ofa( (points pointstoa a) )

int a=15 15,b=38; int *c=&a; printf("%x:%d\n",&a,a); printf("%x:%d\n",&b,b); printf("%x:%x:%d\n",&c,c,*c);

Notethedifferencebetween *Cinvariabledeclaration and*Cinprintf

Output: effffa9415 effffa9038 effffa8ceffffa9415

23

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> int main() { int a=15,b=38; int *c=&a; printf("%x p ( :%d\n", \ ,&a, ,a); ); printf("%x:%d\n",&b,b); printf("%x:%x:%d\n",&c,c,*c); a=49; printf("%x:%d\n",&a,a); printf("%x:%d\n",&b,b); printf("%x p ( :%x:%d\n", \ ,&c, ,c, ,*c); ); c=&b; printf("%x:%d\n",&a,a); printf("%x printf( %x:%d\n %d\n",&b,b); b); printf("%x:%x:%d\n",&c,c,*c); }

24

CSE251Dr.CharlesB.Owen ProgramminginC

SecondSection
Address Memory y 15 49 38 0xeffffa94 Name A B C

a=49; printf("%x:%d\n",&a,a); printf("%x:%d\n",&b,b); printf("%x:%x:%d\n",&c,c,*c);

0xeffffa94 0xeffffa90 0xeffffa8c

25

CSE251Dr.CharlesB.Owen ProgramminginC

SecondExample
Address Memory y 15 49 38 0xeffffa94 Name A B C

a=49; printf("%x:%d\n",&a,a); printf("%x:%d\n",&b,b); printf("%x:%x:%d\n",&c,c,*c);

0xeffffa94 0xeffffa90 0xeffffa8c

Output: effffa94 49 effffa90 38 effffa8c effffa94 49

26

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> int main() { int a=15,b=38; int *c=&a; printf("%x p ( :%d\n", \ ,&a, ,a); ); printf("%x:%d\n",&b,b); printf("%x:%x:%d\n",&c,c,*c); a=49; printf("%x:%d\n",&a,a); printf("%x:%d\n",&b,b); printf("%x p ( :%x:%d\n", \ ,&c, ,c, ,*c); ); c=&b; printf("%x:%d\n",&a,a); printf("%x printf( %x:%d\n %d\n",&b,b); b); printf("%x:%x:%d\n",&c,c,*c); }

27

CSE251Dr.CharlesB.Owen ProgramminginC

ThirdSection

Address

Memory 49 38 0xeffffa90

Name A B C

0xeffffa94 c=&b;/*cnowpointstob*/ printf("%x:%d\n",&a,a); printf("%x:%d\n",&b,b); 0xeffffa90 printf("%x i f("% :%x % :%d\n", %d\ " &c, & c,*c); * ) 0xeffffa8c

28

CSE251Dr.CharlesB.Owen ProgramminginC

ThirdSection

Address

Memory 49 38 0xeffffa90

Name A B C

0xeffffa94 c=&b;/*cnowpointstob*/ printf("%x:%d\n",&a,a); printf("%x:%d\n",&b,b); 0xeffffa90 printf("%x i f("% :%x % :%d\n", %d\ " &c, & c,*c); * ) 0xeffffa8c Output: O t t effffa94 49 effffa90 38 effffa8c effffa90 38

29

CSE251Dr.CharlesB.Owen ProgramminginC

Referenceparameters
Avaluableuseforpointers: Passingaddressestoafunction

30

CSE251Dr.CharlesB.Owen ProgramminginC

Argument&ReturnedValue
Considerafunctioncally=f(x).
Thevaluexispassedtothefunctionf Avalueisreturnedandassignedtoy. Bypassed d wemeanthat h the h value l of fargumentxis copied totheparameterinthefunction.Some calculationisp performedandtheresultisreturnedand assignedtoy.

31

CSE251Dr.CharlesB.Owen ProgramminginC

Example
int x,y; x=5; y=Square(x); int Square(int t) { returnt*t }
Address Memory Name

0xeffffa94 0xeffffa98

x y

32

CSE251Dr.CharlesB.Owen ProgramminginC

Example
int x,y; x=5; y=Square(x); int Square(int t) { returnt*t }
Address Memory Name

0xeffffa94 0xeffffa98

x y

33

CSE251Dr.CharlesB.Owen ProgramminginC

Example
int x,y; x=5; y=Square(x);

ThecallSquare(x): creates avariablet copies thevalueofxtot


Address Memory Name

0xeffffa94

x y

int Square(int t) { returnt*t }

0xeffffa98

0xeffffc8c

34

CSE251Dr.CharlesB.Owen ProgramminginC

Example
int x,y; x=5; y=Square(x);

ThecallSquare(x): creates avariablet copies p thevalueofxtot calculates t*t returns t


Address Memory y Name

0xeffffa94

x y

int Square(int t) { returnt*t }

0xeffffa98

0xeffffc8c 0xeffffc90

5 25

t temp

35

CSE251Dr.CharlesB.Owen ProgramminginC

y=f(x)
Onlyone valuedreturned Whatifwewanttoreturnmorethanonevalue?
Solutionistousepointerstovariablesinthecalling function

36

CSE251Dr.CharlesB.Owen ProgramminginC

HowtodothisinC
Theapproachistopasstheaddress(usingthe& operator)ofthevaluetobemodified. Wecallsuchaparameterareference parameter. Usethe*operatortochangethereferenceparameter value

37

CSE251Dr.CharlesB.Owen ProgramminginC

FunctionReferenceParams
Name Address Value 10

int val =10; MyFun(&val); printf(%d,val);

val

0xeffffa90

voidMyFun(int *param) { *param =27; }

38

CSE251Dr.CharlesB.Owen ProgramminginC

FunctionReferenceParams
Name Address Value 10

int val =10; MyFun(&val); printf(%d,val);


Name param Address 0xefffea88 Value 0xefffa90

val

0xeffffa90

voidMyFun(int *param) { *param =27; }

39

CSE251Dr.CharlesB.Owen ProgramminginC

FunctionReferenceParams
Name Address Value 27

int val =10; MyFun(&val); printf(%d,val);


Name param Address 0xefffea88 Value 0xefffa90

val

0xeffffa90

voidMyFun(int *param) { *param =27; }

40

CSE251Dr.CharlesB.Owen ProgramminginC

FunctionReferenceParams
Name Address Value 27

int val =10; MyFun(&val); printf(%d,val); Prints:27 Thememoryusedby thefunctionis destroyedwhenit returns. returns

val

0xeffffa90

voidMyFun(int *param) { *param =27; }

41

CSE251Dr.CharlesB.Owen ProgramminginC

Whatwillthisdodifferent?
Name Address Value 10

int val =10; MyFun2(val); printf(%d,val);

val

0xeffffa90

voidMyFun2(int param) { param =27; }

42

CSE251Dr.CharlesB.Owen ProgramminginC

Cardsprogram
/*C t arandom d card dand dsuit it*/ Create /*Thiswillcomputearandomnumberfrom0to3*/ Thisprogramrepeatscode.Wedont suit1=rand()%4;

liketodothat.But,wecouldnotput the h card d draw d into i1to a function f i because b /*Thiswillcomputearandomnumber from 13*/ afunctioncanonlyreturnonevalue, card1=rand()%13+1; orsowethought!
/*Createarandomcardandsuit*/ /*Thiswillcomputearandomnumberfrom0to3*/ suit2=rand()%4; /*Thiswillcomputearandomnumberfrom1to13*/ card2=rand()%13+1;

do {

}while(card1==card2&&suit1==suit2);

43

CSE251Dr.CharlesB.Owen ProgramminginC

Solution,passbyreferenceusingpointers
/*Createarandomcardandsuit*/ DrawCard(&card1,&suit1); do { DrawCard(&card2,&suit2); }while(card1==card2&&suit1==suit2);

Dontforget: *suit suit tosetthevalue &card1 togettheaddress Passwith& Setwith*

voidDrawCard(int *card,int *suit) { /*Thiswillcomputea randomnumberfrom0to3*/ / *suit=rand()%4; /*Thiswillcomputearandom numberfrom1to13*/ / *card=rand()%13+1; }

44

CSE251Dr.CharlesB.Owen ProgramminginC

IntrotoArrays
StoringListof Data

CSE251Dr.CharlesB.Owen ProgramminginC

WhyArrays
Supposewewanttostorethe gradeforeachstudentinaclass
/ Needavariableforeach?*/ /* / int bob,mary,tom,;

W cumbersome Wow, b
Easiertohaveavariablethat storesthegradesforallstudents

CSE251Dr.CharlesB.Owen ProgramminginC

Anarray isaChunkofmemory Anarrayisacontiguouspieceof fmemorythat h can containmultiplevalues Th values The l within ithi th thecontiguous ti chunk h kcanb be addressedindividually
Addressin Add i 0xeffffa00 memory grades 74
0xeffffa04 0xeffffa08 0xeffffa0c 0xeffffa10 0xeffffa14 0xeffffa18 0xeffffa1c 0xeffffa20

59

95

85

71

45

99

82

76

CSE251Dr.CharlesB.Owen ProgramminginC

Array:Chunkofmemory
Physical address grades index
0xeffffa00 0xeffffa04 0xeffffa08 0xeffffa0c 0xeffffa10 0xeffffa14 0xeffffa18 0xeffffa1c 0xeffffa20

74
0

59
1

95
2

85
3

71
4

45
5

99
6

82
7

76
8

Useanindex toaccessindividualelementsofthearray: grades[0]is74,grades[1]is59,grades[2]is95,andsoon

CSE251Dr.CharlesB.Owen ProgramminginC

ArrayDeclaration
Syntaxfordeclaring arrayvariable: typearray_name[capacity];
typecanbeanytype(int,float,char,) array_name isanidentifier capacityisthenumberofvaluesitcanstore(indexing startsat0)

CSE251Dr.CharlesB.Owen ProgramminginC

Example

Notice:Thefirstlocationislocation0(zero)!

int x[3];//anarrayof3integers doubley[7];//anarrayof7doubles Storage,e.g.4bytesperint


X
0 1 FirstLocation 2

CSE251Dr.CharlesB.Owen ProgramminginC

OperationswithArrays
Assignment:
x[0]=6; y[2] [2]=3.1; 31 /*Assign6toelementx[0]*/ /*Assign A i 3 3.1 1toelement l y[2] [2]*/

Access
m=x[2]; p=y[0];

Input/Output:
theelementsarehandledastheirtypes types,e e.g. g scanf(%d%lf,&x[2],&y[3]); printf(%d%lf\n,x[0],y[2]); /*output6and3.1*/
7 CSE251Dr.CharlesB.Owen ProgramminginC

ArithmeticOperations () int main() { doublex[5];


[ ]=1; ; x[0] x[1]=2; x[2]=x[0]+x[1]; x[3]=x[2]/3; x[4]=x[3]*x[2]; }

VariableDeclaration forthearray

/*X[2]=3*/ /*X[3]=1*/ /*X[4]=3*/

CSE251Dr.CharlesB.Owen ProgramminginC

for loops
forloopsareidealforprocessingelementsinthe array.
int main() { int i; double values[4] = {3.14, {3 14 1.0, 1 0 2.61, 2 61 5 5.3}; 3}; double sumValues = 0.0; for (i=0; i<4; i++) { sumValues = sumValues + values[i]; } printf(Sum printf( Sum = %lf\n %lf\n, sumValues); }

CSE251Dr.CharlesB.Owen ProgramminginC

for loops
forloopsareidealforprocessingelementsinthe array.
int main() { int i; double values[4] = {3 14 1 0 2 61 5 3}; {3.14, 1.0, 2.61, 5.3}; double sumValues = 0.0; for (i=0; i<=4; i++) { sumValues = sumValues + values[i]; } printf( Sum = %lf\n printf(Sum %lf\n, sumValues); }

ERROR! Outofbound

10

CSE251Dr.CharlesB.Owen ProgramminginC

Initialization
Syntax:int X[4]={2,4,7,9}; ehavior:initiali initialize eelementsstartingwithleftmost, Behavior: i.e.element0.Remainingelementsareinitializedto zero. X
2 4 7 9 0 1 2 3

Initializeallto0:int X[4]={0};

11

CSE251Dr.CharlesB.Owen ProgramminginC

int main() { doubleg grades[5] [ ]={90, { ,87, ,65, ,92, ,100}; }; doublesum; int i; printf("Thefirstgradeis:%.1f\n", % 1f\n" grades[0]); sum=0; for(i=0;i<5;i++) { sum+=grades[i]; } printf("The printf( Theaveragegradeis:% %.1f\n 1f\n",sum/5);

Example

grades[2]=70;/*Replaces65*/ grades[3]=grades[4];/*Replaces92with100*/ }

12

CSE251Dr.CharlesB.Owen ProgramminginC

Constantsforcapacity
Goodprogrammingpractice: use#defineforconstantsinyourprogram Forexample: #defineMaxLimit 25 int grades[MaxLimit]; f (i t i; for(int i i<MaxLimit; i M Li it i++){ i ){}; } Ifsizeneedstobechanged, changed onlythecapacity MaxLimitneedstobechanged.
CSE251Dr.CharlesB.Owen ProgramminginC

13

Arraysasparametersoffunctions
int i t main() i () { double values[4] [ ] = {3.14, { , 1.0, , 2.61, , 5.3}; }; printf(Sum = %lf\n, SumValues( values, 4)); }

Supposewewantafunctionthat sumsupvaluesofthearray

14

CSE251Dr.CharlesB.Owen ProgramminginC

Arraysasparametersoffunctions
doubleSumValues(doublex[],int numElements) { int i; doubleresult=0; for(i=0;i <numElements;i++) result=result+x[i]; returnresult; } []flagstheparameterasanarray.
ALWAYSpassedbyreference

Arraysizeispassedseparately(asnumElements)

15

CSE251Dr.CharlesB.Owen ProgramminginC

Example
ProgramBehavior
1. 2. 3. 4. Createanarrayofrandomnumbers Printunsortedarray Sortthearray Printsorted darray

16

CSE251Dr.CharlesB.Owen ProgramminginC

Arraybeforesorting Element0:58.7000 Element1:8.0100 Element2:72.3700 Element3:4.6500 Element4:58.3000 Element5:92.1700 Element6:95.3100 Element7:4.3100 Element8:68.0200 Element9:72.5400 Arrayaftersorting Element0:4.3100 Element1:4.6500 Element2:8.0100 Element3:58.3000 Element4:58.7000 Element5:68.0200 Element6:72.3700 Element7:72.5400 Element8:92.1700 Element9:95.3100

Sample p output p Thearrayelements arerandomly generated

17

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<stdlib.h> voidPrintArray(double[],int ); voidSortArray(double[], [] int ); voidSwap(double*,double*);

Functionsareyourfriends! Makethemworkandthen usethemtodowork!

18

CSE251Dr.CharlesB.Owen ProgramminginC

#defineNumElements 10 int main() { int i; doublevalues[NumElements];/*Thearrayofrealnumbers*/ srand(time(NULL)); ( ( )); for(i=0;i <NumElements;i++) { values[i] [ ]=(double)(rand() ( )( ()%10000) )/100.0; ; } printf("\nArray beforesorting\n"); PrintArray( y(values, ,NumElements ); SortArray(values,NumElements ); p printf("\nArray ( y aftersorting\n"); g ); PrintArray(values,NumElements ); return0; }
CSE251Dr.CharlesB.Owen ProgramminginC

19

#defineNumElements 10

Array declaration int main() { Declare an array of 10 doubles int i; The indices range from 0 to 9, doublevalues[NumElements];/*The array ofreal numbers */ i.e. Value[0] to Value[9]
( ( )); srand(time(NULL)); for(i=0;i <NumElements;i++) { values[i] [ ]=(double)(rand() ( )( ()%10000) )/100.0; ; } printf("\nArray beforesorting\n"); PrintArray( y(values, ,NumElements ); SortArray(values,NumElements ); p printf("\nArray ( y aftersorting\n"); g ); PrintArray(values,NumElements ); return0; }
CSE251Dr.CharlesB.Owen ProgramminginC

20

#defineNumElements 10 int main() { int i; doublevalues[NumElements];/*Thearrayofrealnumbers*/ srand(time(NULL)); ( ( )); for(i=0;i <NumElements;i++) { values[i] [ ]=(double)(rand() ( )( ()%10000) )/100.0; ; }

Initialize the array with random values printf("\nArray before sorting\n"); PrintArray( y(values, ,NumElements ); rand() returns a pseudo random number between
SortArray(values,NumElements );

0 and

RAND_MAX rand()%10000 yields a four-digit integer remainder printf("\nArray p ( y after sorting\n"); g ); /100 0 moves /100.0 the decimal point left 2 places PrintArray(values,NumElements ); So, Values is an array of randomly generated 2-decimal digit return 0; numbers between 0.00 and 99.99

21

CSE251Dr.CharlesB.Owen ProgramminginC

printf("\nArray beforesorting\n"); PrintArray(values,NumElements );

PrintArray printsthe elementsofthearrayin theordertheyaregiven toit SortArray sortsthe elementsintoascending order

SortArray(values,NumElements );

printf("\nArray aftersorting\n"); PrintArray(values,NumElements );

22

CSE251Dr.CharlesB.Owen ProgramminginC

ParameterPassing
voidPrintArray(doublearray[],int size) { } array isaCarrayofdoubles

array ispassedbyreference, i.e.anychangestoparameter array inthefunctionwould changetheargumentvalues Thearraysizeispassedas size size

23

CSE251Dr.CharlesB.Owen ProgramminginC

voidPrintArray(doublearray[],int size) { i t i; int i for(i=0;i<size;i++) printf("Element%5d:%8 printf( %8.4lf\n 4lf\n",i, i array[i]); }

array[i]isadoublesotheoutputneedstobe%f %f Therangeofthefor for statementwalksthroughthe wholearrayfromelement0toelementN1.

24

CSE251Dr.CharlesB.Owen ProgramminginC

SortingArray
voidSortArray(doublearray[],int size) { } array isanarrayofdoubles. array is i passed dby b reference, f i.e. i changes h to parameterarraychangetheargumentvalues Thereisnosizerestrictiononarraysothesize ispassedassize.

25

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
array 8 0 2 1 6 2 4 3

26

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
array 8 0 2 1 6 2 4 3 Searchfromarray[0]toarray[3] tofindthesmallestnumber

27

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
array 8 0 2 1 6 2 4 3 Searchfromarray[0] y[ ]toarray[3] y[ ] tofindthesmallestnumberand swapitwitharray[0]

2 0

8 1

6 2

4 3

28

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
array 8 0 2 1 6 2 4 3 Searchfromarray[1]toarray[3] tofindthesmallestnumber

2 0

8 1

6 2

4 3

29

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
array 8 0 2 1 6 2 4 3 Searchfromarray[1]toarray[3] tofindthesmallestnumberand swapitwitharray[1]

2 0 2 0

8 1 4 1

6 2 6 2

4 3 8 3

30

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
array 8 0 2 1 6 2 4 3

2 0 2 0

8 1 4 1

6 2 6 2

4 3 8 3 Searchfromarray[2]toarray[3] tofindthesmallestnumberand swapitwitharray[2]

31

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
array 8 0 2 1 6 2 4 3

2 0 2 0 2 0

8 1 4 1 4 1

6 2 6 2 6 2

4 3 8 3 8 3 Searchfromarray[2]toarray[3] tofindthesmallestnumberand swapitwitharray[2]

A dwearedone! And d !

32

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
array 8 0 2 1 6 2 4 3

Howmanyiterationsarethere? Answer:3(fromi =0toi =2) Moregenerally,ifnumberof elementsinthearrayissize, size youneedtoiteratefrom i =0toi =size 2

2 0 2 0 2 0

8 1 4 1 4 1

6 2 6 2 6 2

4 3 8 3 8 3

33

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
2 0 8 1 6 2 4 3

Ateveryiterationi,youneedtosearch f from array[i] [i]to t array[size [ i 1]t to findthesmallestelement Howtodothis?

34

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
2 0 8 1 6 2 4 3

Ateveryiterationi,youneedtosearch fromarray[i]toarray[size 1]to findthesmallestelement Howtodothis? Useavariablecalledmintolocate theindex ofthesmallestelement

min

35

CSE251Dr.CharlesB.Owen ProgramminginC

SelectionSort
2 0 8 1 6 2 4 3 Assumecurrentiterationi =1 Initializemin=i

min

36

CSE251Dr.CharlesB.Owen ProgramminginC

Selection Sort
2 0

i
8 1

j
6 2 4 3 Assumecurrentiterationi =1 Initializemin=I Setj=i +1 Comparearray(min)toarray(j)

min

37

CSE251Dr.CharlesB.Owen ProgramminginC

Selection Sort
2 0

i
8 1

j
6 2 4 3

Assumecurrentiterationi =1 Initializemin=i Setj=i +1 Comparearray(min)toarray(j) Ifarray(j)<array(min) setmintoj

min

Because6<8, minisnowsetto2

38

CSE251Dr.CharlesB.Owen ProgramminginC

Selection Sort
2 0

i
8 1 6 2

j
4 3 Incrementj Comparearray(min)toarray(j)

min

39

CSE251Dr.CharlesB.Owen ProgramminginC

Selection Sort
2 0

i
8 1 6 2

j
4 3

Incrementj Comparearray(min)toarray(j) Ifarray(j)<array(min) setmintoj

Because4<6, minisnowsetto3 min 3

40

CSE251Dr.CharlesB.Owen ProgramminginC

Selection Sort
2 0

i
8 1 6 2

j
4 3 S Swap array(i) (i)with itharray(min) ( i )

min

41

CSE251Dr.CharlesB.Owen ProgramminginC

voidSortArray(doublearray[],int size) { i t i, int i j, j min; i for(i=0;i <size1;i++) { min=i; for(j=i+1;j<size;j++) { if(array[j]<array[min]) { min=j; j } } Swap(&array[i],&array[min]); } }

SortArray

42

CSE251Dr.CharlesB.Owen ProgramminginC

Swap

voidSwap(double*a,double*b) { doubletemp=*a; *a=*b; *b=temp; }

43

CSE251Dr.CharlesB.Owen ProgramminginC

Swap

voidSwap(double*a,double*b) { doubletemp=*a; *a=*b; Note:Werepassingtwoelementsofthe *b=temp; array;notpassingtheentirearray }


So,weCANNOT declareitas voidSwap(doublea,doubleb) voidSwap(doublea[],doubleb[])

44

CSE251Dr.CharlesB.Owen ProgramminginC

StringsandFileI/O

CSE251Dr.CharlesB.Owen ProgramminginC

CharacterType:char
InC,charactersareindicatedbysinglequotes:
char myChar; myChar ='a'; printf(myChar f( h is%c\n, \ myChar); h ) Thetype yp ischar for one(1)character

%cistheformal specifier forachar

CSE251Dr.CharlesB.Owen ProgramminginC

String
Astringisanarrayofcharacters,itisindicatedby doublequotes:
"thisisastring" Butyoucantuseanassignmentoperatortoassignastring toacharacterarray charmyChar[80]; /*arrayofchars*/ myChar[4]=a; /*OK*/ myChar Ch =this thi is i astring; t i /*NOTOK*/

CSE251Dr.CharlesB.Owen ProgramminginC

String
Anull(\0)characterisplacedtomarktheendofeach string t h i s i s a s t r i n g \0

Stringfunctionsuse\0tolocateendofstring(soyou donthavetopassstringlengthasargumenttothe functions)

CSE251Dr.CharlesB.Owen ProgramminginC

InitializingaString char h myStr[5] [ ]={a, { b, b c, d, d 0}; } printf(myStr is%s\n,myStr);


Arraysizehasexactly5elements Aterminating\0 \0 characterattheend (inASCII,char\0isequivalenttoint 0) Willprint:myStr isabcd

myStr

a b c d \0

CSE251Dr.CharlesB.Owen ProgramminginC

Anotherway

myStr

charmyStr[10]=birdbath; b i r d b a t h \0 printf(myStr is%s\n,myStr);


Oktouseassignmentonly toinitializestring myStr y isanarray yof10characters(but ( only ythefirst8 elementsusedtostoretheword) a\0isaddedtotheendautomatically(so9elementsin th arrayareoccupied) the i d)

CSE251Dr.CharlesB.Owen ProgramminginC

Betterway

myStr

charmyStr[]=birdbath; b i r d b a t h \0 printf(myStr is%s\n,myStr);


\0isaddedautomaticallytotheendofmyStr Space S is i allocated ll t dautomatically t ti ll to t hold h ldexactly tl what h twe need(9locations,including\0)

CSE251Dr.CharlesB.Owen ProgramminginC

printf forStrings
charmyStr[]=abc123; Output:
Use%s toprinttheentirestring: printf(%s\n,myStr); /*outputsabc123 */ /*\0isnotprinted*/ Use%c toprintacharacter: printf(%c\n printf( %c\n ,myStr[1]); myStr[1]);/*outputs: b*/

CSE251Dr.CharlesB.Owen ProgramminginC

Stringinput
Thereareseveralfunctionsavailable Partofthestdio.h library.

CSE251Dr.CharlesB.Owen ProgramminginC

scanf
scanf readsuptothefirstwhitespace,ignoresthestuff typedinafterthat.Becarefulwhenusingit.
charmyStr[10]; printf(Enter i f(E astring: i ); ) scanf(%s,myStr); printf(You printf( Youentered%s\n\n %s\n\n,myStr)

10

CSE251Dr.CharlesB.Owen ProgramminginC

scanf safer
Use%[width]stocopyonlyuptoamaximumnumber ofcharacter.But,doesnotappendthe\0
charmyStr[10]; printf(Enter i f(E astring: i ); ) scanf(%9s,myStr); myStr[9]=\0; \0 ; /*Dothisyourselfjustincase*/ / / printf(Youentered%s\n\n,myStr)

11

CSE251Dr.CharlesB.Owen ProgramminginC

getchar
getchar willfetchone(1)characterfromtheinput stream
charmyChar; printf(Enteracharacter:); myChar Ch =getchar(); h () printf(Youentered%c\n\n,myChar);

12

CSE251Dr.CharlesB.Owen ProgramminginC

fgets
char*fgets(charArray,lengthLimit,filePtr) fetchesawholeline,uptothesizelimitorwhenitseesa newline Itwill adda\0attheendofstring Example: Example
charmyStr[80]; fgets(myStr,80,stdin);//fetchfromconsole

ReturnsaNULLifsomethingwentwrong,otherwisea pointertothearray
Thefunctionsthatstartwithfworkwith anysourceofinput.stdin istheCStandard Input. p
13 CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<string.h> int main() { int inputLength=20 int cnt cnt=0; 0; charstr1[20],str2[20]; printf("\nEnter astring:"); fgets(str1, g ( ,inputLength, p g ,stdin); ); printf("Youentered%s\n",str1); printf(Enteranotherstring:"); scanf("%s",str2); printf("Youentered%s\n",str2); }

Makesureyoureclearthe differencebetweenfgets andscanf

14

CSE251Dr.CharlesB.Owen ProgramminginC

Notetheextranewline whenusingfgets
str1(readusingfgets)

t h i s
str2(readusingscanf)

i s

s t r i n g \n \0

t h i s \0

15

CSE251Dr.CharlesB.Owen ProgramminginC

#include<string.h> Stringmanipulationfunctions strcpy Copiesastring strcat Concatenatestwostrings strlen Returnsthelengthofastring strcmp Comparestwostrings

16

CSE251Dr.CharlesB.Owen ProgramminginC

stringcopy(strcpy)

strcpy(destString,srcString);

char [] strcpy (char dest[], const char src[]);

copystringcontentsfromsrc (2nd arg)todest (1st arg)including\0 \0 dest ischanged,src unmodified(butcandosome weirdthings) returnsapointertothemodifieddest array

17

CSE251Dr.CharlesB.Owen ProgramminginC

stringcopy(strcpy)
char [] strcpy (char dest[], const char src[]);

Thereisnoerrorchecking!
Ifdest arrayisshorterthansrc array,noerrors.Weirdthings couldhappen happen,butnocompileerrorsandoftennoruntime errors Tracking gthesebugs g downisvery yhard!

18

CSE251Dr.CharlesB.Owen ProgramminginC

Saferversionofstringcopy

strncpy(destString,srcString,80);

char [] strncpy (char dest[], const char src[], int N);

copiesatmostNcharactersfromsrc todest (orup to\0 Iflengthofsrc isgreaterthanN,copiesonlythefirst Ncharacters Iflengthofsrc islessthanN,padtheremaining elementsindest with\0
Doesnotcopythe\0ifthe stringlengthis>=N

19

CSE251Dr.CharlesB.Owen ProgramminginC

concatenation(strcat)
char [] strcat(char dest[], const char src[])

contentsofsrc areaddedtotheendofdest. dest ischanged,src isnot \0addedtotheendofdest returnapointertodest noboundscheck(again,thisisC)

20

CSE251Dr.CharlesB.Owen ProgramminginC

comparison(strcmp)
int strcmp (const char s1[], const char s2[]);

Compares2strings
ifs1precedess2,returnvalueislessthan0 ifs2precedess1,returnvalueisgreaterthan0 ifs1equaltos2,returnvalueis0

C Comparison i i isbased b donlexicographic l i hi order d (ASCII order) e.g.,a<b

21

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<string.h> int main() { printf("strcmp(\"a\",\"b\"):%d\n", strcmp("a","b")); printf("strcmp(\"b\" printf( strcmp(\ b\ ,\ \"a\"): a\ ):%d\n %d\n", strcmp( strcmp("b" b ,"a")); a )); printf(strcmp(\"a\",\"a\"):%d\n", strcmp("a","a")); printf("strcmp(\"2\",\"3\"):%d\n", strcmp("2","3")); printf("strcmp(\"2\",\"10\"):%d\n", strcmp("2","10")); }

Lexicographicorderingisnotthe sameasorderingnumbers

22

CSE251Dr.CharlesB.Owen ProgramminginC

Reversingastring
Input:Mathisfun Output:nuf si htaM

Howwouldyou dothis?

23

CSE251Dr.CharlesB.Owen ProgramminginC

front

voidReverse(charstr[]) { int front=0; int back=strlen(str) 1; chart;/*Atemporaryplacetoputacharacter*/ while(front<back) { t=str[front]; str[front]=str[back]; str[back]=t; front++; back; } }
24

back

CSE251Dr.CharlesB.Owen ProgramminginC

#include<ctype.h>

Builtinfunctionsforcharacters
Theseallreturnboolean (1/0).
isalnum(c):iscalphanumeric? isalpha(c):iscalphabetic? isdigit(c):iscadigit? iscntrl(c):iscacontrolcharacter? islower(c):isclowercase? isupper(c):iscuppercase? ispunct(c):iscapunctuationcharacter,thatisaprintable characterthatisneitheraspacenoranalphanumeric character
CSE251Dr.CharlesB.Owen ProgramminginC

25

converters
chartolower(c)
returnthecharacteraslowercase

chartoupper(c)
returnthecharacterasuppercase

26

CSE251Dr.CharlesB.Owen ProgramminginC

FileIO
Howtowriteprogramstoreadfrom orwritetofiles Sofar,weveonlylookedathowto read/writetotheconsole

27

CSE251Dr.CharlesB.Owen ProgramminginC

Openfiles
Filesareopenedwithfopen
thefopenfunctionispartofstdio.h Ittakestwoargs:astring(thenameofafile)andamode string(howthefileisopened). Itreturnsafilepointer
fptr = fopen(myfile.txt,r);

28

CSE251Dr.CharlesB.Owen ProgramminginC

Declareandassignfilepointer
fopenreturnsaNULLpointerifitcannotperformthe operation
FILE *infile; inFile = fopen(file fopen(file.txt,r); t t r) if (inFile == NULL) // bad file opening

29

CSE251Dr.CharlesB.Owen ProgramminginC

filemodes
r,readfromthebeginningofanexistingfile w,makeanemptyfile(wipeoutoldcontents), startwriting. a,findanexistingfile,startwritingattheendof thatfile

30

CSE251Dr.CharlesB.Owen ProgramminginC

Closefiles
Filesareclosedwithfclose
thefclosefunctionispartofstdio.h Ittakesoneargument: pointertothefiletobeclosed
fclose(fptr);

31

CSE251Dr.CharlesB.Owen ProgramminginC

Theffunctions
mostoftheI/Ofunctionsweknowhavean equivalentfversiontoworkwithafile. Thefirstargumentisthefilepointervalueofan openedfile
fprintf(filePtr,formatstring,values) fscanf(filePtr,formatstring,addresses) feof(filePtr) f f(fil Pt )end dof ffile fil test t t

32

CSE251Dr.CharlesB.Owen ProgramminginC

StatesandStateMachines

CSE251Dr.CharlesB.Owen ProgramminginC

Whatisthisfor?
Statemachinesarecommonlyusedin

EmbeddedSystems

Factory/ProcessControls

CSE251Dr.CharlesB.Owen ProgramminginC

State
State Anabstractionofthecurrentstatusofasystem. Statesareassignednames. WaitingforaKeypress WaitingforElvis RaisingFirearmtoFire Cellphone isDialing D Opening Door O i Verbswithing PaperJammed BatteryisBelowLimit PowerisOn DoorOpen Prius AcceleratorStuck Statementofcondition

CSE251Dr.CharlesB.Owen ProgramminginC

StatesinaGarageDoor

Arethereanymorestates?

DoorClosed

DoorOpen

CSE251Dr.CharlesB.Owen ProgramminginC

MoreStates
DoorOpening

DoorClosing

CSE251Dr.CharlesB.Owen ProgramminginC

Howwewillexpressthisinaprogram
/*Ourpossiblegaragedoorstates*/ #defineDoorClosed 1 #defineDoorOpening 2 #defineDoorOpen 3 #defineDoorClosing 4 int main() { i state=DoorClosed; int D Cl d

Abovemain inourprogram

Inthemain function

Why ydowecare?Wedodifferentthings g dependingonthecurrentstate.Whatdoes thebuttondoineachstate?

CSE251Dr.CharlesB.Owen ProgramminginC

NamingConventions States
Wewillusuallynamestateswithcamelcaseandacapitalfirst letter.Welluse#definesinourprogramsforstatenames. WaitingForKeypress WaitingForElvis RaisingFirearm CellphoneDialing DoorOpening Verbswithing ing

PaperJammed BatteryBelowLimit l i i PowerOn p DoorOpen PriusAccelStuck Statementofcondition

CSE251Dr.CharlesB.Owen ProgramminginC

Events
Aneventis A i anoccurrencein i time i .It I is i consideredatomicandinstantaneous. Leftmousebuttonpressed Key yp pressed Elvishasleftthebuilding Flight529haslanded Powerturnedon Pasttenseverbs

Paperisjammed Messagehastimedout 10secondshaselapsed Batteryisbelowlimit P j t2is Project i due d Onsetofcondition

CSE251Dr.CharlesB.Owen ProgramminginC

Eventsvs.State
clickedOnScreen screenSlideDone clickedOnScreen screenSlideDone

IdleClosed

SlidingOpen

IdleOpen

SlidingClosed

IdleClosed

Aneventiswhatcausesusto changefromstatetostate.

CSE251Dr.CharlesB.Owen ProgramminginC

StateDiagrams

Statediagramsdescribewhatwewill implementincodeasastatemachine.

10

CSE251Dr.CharlesB.Owen ProgramminginC

StateDiagrams
InitialState State Transition Event

11

CSE251Dr.CharlesB.Owen ProgramminginC

StartingoutStateMachine
int main() { i state=DoorClosed; int D Cl d

12

CSE251Dr.CharlesB.Owen ProgramminginC

int main() { int state=DoorClosed; printf("GarageStartup\n"); GarageStartup(); while(IsGarageRunning()) { } printf("GarageShutdown\n"); G GarageShutdown(); Sh d () return0; }

AControlLoop
Acontinuousloopinacontrols applicationthatcontrolsthe system. t Ri Right htnowourloop l is i doingnothing.Wellwanttoadd codetomakeourgaragedoor work.

13

CSE251Dr.CharlesB.Owen ProgramminginC

ImportantIdea
Wedosomethingdifferentdependingonthestateweare in.Itmakessensetocreateafunction foreachstate.
voidStateDoorClosed(int *state) { } Notethepointer.We passthe th state t t b by reference.Itisan in/outparameter

WhatshouldhappenwhenweareintheDoorClosed state?

14

CSE251Dr.CharlesB.Owen ProgramminginC

DoorClosed state
Ifthebuttonispressed: Startthemotor GototheDoorOpening p g state otherwise: Donothing

15

CSE251Dr.CharlesB.Owen ProgramminginC

DoorClosed state
Ifthebuttonispressed: Startthemotor GototheDoorOpening p g state otherwise: Donothing void idStateDoorClosed(int St t D Cl d(i t *state) *t t ) { if(WasButtonPressed()) { SetMotorPower(1); *state=DoorOpening; } }

16

CSE251Dr.CharlesB.Owen ProgramminginC

TheControlLoop HandlingStates
while(IsGarageRunning()) { switch(state) { caseDoorClosed: StateDoorClosed(&state); break; } }

Wewillputaswitch statementinourcontrol looptohandlethestates.

17

CSE251Dr.CharlesB.Owen ProgramminginC

Wenowhavethis

Trigger/Activity Triggeriswhatcauses thetransition. transition Activity issomethingthat happenswhenthe transitionoccurs.

Thisisasimple2statestatement.

18

CSE251Dr.CharlesB.Owen ProgramminginC

Whathappens
while(IsGarageRunning()) { switch(state) { caseDoorClosed: StateDoorClosed(&state); break; } }

ControlLoop

voidStateDoorClosed(int *state) state) { if(WasButtonPressed()) { SetMotorPower(1); *state=DoorOpening; } StateFunction }

Thecontrollooprunscontinuously(1000timespersecondin thisprogram).Eachtimeitcallsafunctionforthecurrent state.Thatstatefunctiondecidesifweneedtochangethe stateanddoesanythingelseweneedtodowhileinthatstate.

19

CSE251Dr.CharlesB.Owen ProgramminginC

AGarageDoorOpener

20

CSE251Dr.CharlesB.Owen ProgramminginC

Pointers,Arrays,MultidimensionalArrays
Pointersversusarrays
Lotsofsimilarities

Howtodealwith2D,3D,multidimensionalarrays (forstoringmatricesandother2Dor3Ddata!)

CSE251Dr.CharlesB.Owen ProgramminginC

Review:Pointers
Address Memory 15 0xeffffa94 Name

Pointersarevariablesthat storememoryaddresses

0xeffffa94 0xeffffa98

a b

int a=15; int *b=&a; printf(%x%x%d\n,b,&b,*b); //printseffffa94effffa9815

CSE251Dr.CharlesB.Owen ProgramminginC

int number; int *ptr =&number;

Read& asat at

Usingpointersin scanf function


Donthavetoput &beforeptr.Its alreadyanat at .

printf(Enteraninteger:); scanf(%d scanf( %d , &number); printf(Enteranotherinteger:); scanf(%d, ptr);

printf(Number=%d,*ptr =%d\n,number,*ptr); Exampleoutput:

CSE251Dr.CharlesB.Owen ProgramminginC

int multiply(int *,int);

int main() { int number=3; int *ptr =&number; &n mber; printf(1:%d\n,multiply(&number,2)); printf(2:%d\n,multiply(ptr,3)); } int multiply(int *a, int factor) { return(*a) *factor; }

Passingpointers (addresses)to functions

CSE251Dr.CharlesB.Owen ProgramminginC

Review:Arrays
Anarrayisacontiguouschunkofmemorytostore multiplevalues
int grades[]={74,59,95,85,71,45,99,82,76};
0xeffffa00 0xeffffa04 0xeffffa08 0xeffffa0c 0xeffffa10 0xeffffa14 0xeffffa18 0xeffffa1c 0xeffffa20

grades index

74
0

59
1

95
2

85
3

71
4

45
5

99
6

82
7

76
8

CSE251Dr.CharlesB.Owen ProgramminginC

int sumArray(int [],int);

int main() { int list[]={1,2,3,4}; printf(Sum=%d\n,sumArray(list ,4)); } int sumArray (int list[],int arraySize) { int sumvalue =0; for(int i=0;i<arraySize;i++) sumvalue +=list[i]; returnsumvalue; }

Passingarraysto functions

CSE251Dr.CharlesB.Owen ProgramminginC

ArrayName
Thearraynameisa list pointertothefirst element l tof fth thearray
ffe2de0c ffe2de10 ffe2de14 ffe2de18

1 [0]

2 [1]

3 [2]

4 [3]

int list[] list[]={1,2,3,4}; {1,2,3,4}; printf(%x,%x,%d,list,&list[0],*list);

Output:ffe2de0cffe2de0c 1

CSE251Dr.CharlesB.Owen ProgramminginC

PointersandArrays

p list
1 2 [1] [ ] 3 [2] [ ] 4 [3] [ ]

int *p, [0] [ ] int list[]={1,2,3,4}; list[] {1 2 3 4}; p=list; /*equivalenttop=&list[0]*/ printf(%d\n,*p);/*printsthevalue1*/

Youcanusea pointertoaccess thearray

CSE251Dr.CharlesB.Owen ProgramminginC

Pointerand[]

Anypointertoablockofmemory canusethe[]syntax,evenifitis notdeclaredasanarray! List

1 [0]

2 [1]

3 [2]

4 [3]

int *p, p int list[]={1,2,3,4}; int *v;andint v[];/*Meanthesamething*/ p=list; printf(%d\n, i tf(%d\ p[2]); [2]) //prints i t 3

CSE251Dr.CharlesB.Owen ProgramminginC

Arrayindexing[]
list
ff 2d 0 ffe2de0c

*list Contentspointedtobylist *(list+2) Contentsatlist[2] Indexinganarrayisjustaway offindingaparticularaddress inthatblock

list+2
ff 2d 10 ffe2de14 ffe2de10 ff 2d 14 ffe2de18 ff 2d 18

1 [0]

2 [1]

3 [2]

4 [3]

int list[]={1 {1,2,3,4} 2 3 4} //arrayof4ints printf(%d,list[2]); Thisisequivalentto printf(%d, printf( %d ,*(list+2) (list+2));

10

CSE251Dr.CharlesB.Owen ProgramminginC

PointerArithmetic
Whenweaddtoapointer,suchas(p+1),wedont literallyadd1tothepointeraddress Insteadweaddoneaddresstothepointer

11

CSE251Dr.CharlesB.Owen ProgramminginC

PointerArithmetic
int list[]={1,2,3,4}; int *p=list; /*sameasp=&list[0]*/ printf(%x,p); printf( %x ,p);/ /*printsffe2de0c*/ / p
ffe2de0c ffe2de10 ffe2de14 ffe2de18

12

CSE251Dr.CharlesB.Owen ProgramminginC

PointerArithmetic
int list[]={1,2,3,4}; int *p=list; /*sameasp=&list[0]*/ printf(%x,p); printf( %x ,p);/ /*printsffe2de0c*/ / p=p+1; /*pincreasesby4*/ printf(%x,p);/*printsffe2de10*/ Thinkofpointer arithmeticasadd 1location insteadofone byteoraddress. address p
ffe2de0c ffe2de10 ffe2de14 ffe2de18

13

CSE251Dr.CharlesB.Owen ProgramminginC

PointerArithmetic
double d bl list2[] li t2[]={1.0, {1 0 2.0, 2 0 3.0}; 3 0} double*p=list2;/*sameasp=&list2[0]*/ printf(%x, p ( p) p);/*prints p ffe2de0c*/ p
ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20

1.0

2.0

3.0

14

CSE251Dr.CharlesB.Owen ProgramminginC

PointerArithmetic
double d bl list2[] li t2[]={1.0, {1 0 2.0, 2 0 3.0}; 3 0} double*p=list2;/*sameasp=&list2[0]*/ printf(%x,p); p ( p) /*p printsffe2de0c*/ p=p+1;/*Pincreasesby8bytes*/ printf(%x,p);/*printsffe2de14*/
P

ffe2de0c

ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20

1.0

2.0

3.0

15

CSE251Dr.CharlesB.Owen ProgramminginC

PointerArithmeticonArrays *(list+1) *(l )references f the h nextelement l inthe h array (equivalenttolist[1])


Becareful:*(++list)workstoobutnowwehavelost ourpointertothebeginningofthearray!!!
Equivalentto: list=list+1;*list;

16

CSE251Dr.CharlesB.Owen ProgramminginC

sizeof()operator
int i t i; i int *ptr4i=&i; int IntArray[]={1,2,3,4,5}; doublej; double*ptr4j=&j; doubledoubleArray[]={1.0,2.0,3.0,4.0,5.0};

Returnsthenumber ofbytesneededto storeavariableora datatype

printf("Sizeof i tf("Si f integer i t i is%db bytes\n", t \ " sizeof(int)); i f(i t)) printf("Sizeof doubleis%dbytes\n",sizeof(double)); printf("Sizeof i is%dbytes\n",sizeof(i)); printf("Sizeof pointerfori is%dbytes\n",sizeof(ptr4i)); printf("Sizeof jis%dbytes\n",sizeof(j)); printf("Sizeof pointerforjis%dbytes\n",sizeof(ptr4j)); printf("Sizeof intArray is%dbytes\n",sizeof(intArray)); printf("Sizeof doubleArray is%dbytes\n",sizeof(doubleArray));

17

CSE251Dr.CharlesB.Owen ProgramminginC

sizeof()operator

18

CSE251Dr.CharlesB.Owen ProgramminginC

Whenwepassanarray Wh wepassanarray,wearepassing When i th thearray address


int sumArray(int [] ],int); int main() { int list[]={1,2,3,4); sumArray( A (list li ,4) );

19

CSE251Dr.CharlesB.Owen ProgramminginC

Whenwepassanarray
Thiswillworktoo(becausearraynameisapointerto thebeginningofthearray)
int sumArray(int *, int); int main() { int list[]={1,2,3,4); sumArray(list ,4);

20

CSE251Dr.CharlesB.Owen ProgramminginC

Whenwepassanarray
ButthisDOESNOT work!
int sumArray( y(int *, ,int); ); int main() { int *list={1 {1,2 2,3 3,4); sumArray(list,4);

21

CSE251Dr.CharlesB.Owen ProgramminginC

Pointers
list
ff 2d 0 ffe2de0c

*list Contentspointedtobylist *(list+2) Contentsatlist[2] list+2

ff 2d 10 ffe2de14 ffe2de10 ff 2d 14 ffe2de18 ff 2d 18

1 [0]

2 [1]

3 [2]

4 [3]

Indexinganarrayisjusta wayoffindingaparticular addressinthatblock

int list[]={1 {1,2,3,4} 2 3 4} //arrayof4ints printf(%d,list[2]); Thisisequivalentto printf(%d, printf( %d ,*(list+2) (list+2));

22

CSE251Dr.CharlesB.Owen ProgramminginC

2DArrays
int cave[ArraySize][ArraySize];
Column
0 0 1 1 2 3

Row

2 3

1 5 9 13

2 6 10 14

3 7 11 15

4 8 12 16

23

CSE251Dr.CharlesB.Owen ProgramminginC

2DArrays
int myMatrix[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12} {1 2 3 4} {5 6 7 8} {9 10 11 12}}; Column
0 0 1 2 3

Row

1 2

1 5 9

2 6 10

3 7 11

4 8 12

myMatrix[0][1] 2

myMatrix[2][3] M t i [2][3] 12 myMatrix[row][col]

24

CSE251Dr.CharlesB.Owen ProgramminginC

Physically,inoneblockofmemory
int myMatrix[2][4]={{1,2,3,4},{5,6,7,8}};
ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28

2
row1

6
row2

Arrayelementsarestoredinrowmajororder Row1first,followedbyrow2,row3,andsoon

25

CSE251Dr.CharlesB.Owen ProgramminginC

2DArrayNameandAddresses int myMatrix[2][4] [ ][ ]={{1,2,3,4},{5,6,7,8} { }{ }} };


ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28

myMatrix:pointertothefirstelementofthe2Darray myMatrix[0]:pointertothefirstrowofthe2Darray myMatrix[1]:pointertothesecondrowofthe2Darray *myMatrix[1]istheaddressofelementmyMatrix[1][0]

26

CSE251Dr.CharlesB.Owen ProgramminginC

Accessing2DArrayElements int myMatrix[2][4] [ ][ ]={{1,2,3,4} { },{5,6,7,8} { }} };


1 2 3 4 5 6 7 8

Indexing: g myMatrix[i][j] y [ ][j]issameas *(myMatrix[i]+j) (*(myMatrix +i))[j] *((*(myMatrix +i))+j) *(&myMatrix[0][0]+4*i +j)

27

CSE251Dr.CharlesB.Owen ProgramminginC

Declaration
#defineROWS3 #defineCOLS5 int table[ROWS][COLS]; voiddisplay(table);

28

CSE251Dr.CharlesB.Owen ProgramminginC

voiddisplay(int x[ROWS][COLS]) 2DArraysoftenrequire { nestedloops p two for(int i=0;i <ROWS;i++) variables { ;j<COLS; ;j for( (int j j=0; j++) { printf("x[%d][%d]:%d",i,j,x[i][j]); } printf("\n"); } printf("\n"); }

29

CSE251Dr.CharlesB.Owen ProgramminginC

TableA={{13,22,9,23}, {17,5,24,31,55}, {4 19, {4, 19 29, 29 41, 41 61}};

13 17 4

22 5 19

9 24 29

23 31 41

? 55 61

TableB={1,2,3,4, 5,6,7,8,9, 10 11, 10, 11 12, 12 13, 13 14};

1 6 11

2 7 12

3 8 13

4 9 14

5 10 ?

30

CSE251Dr.CharlesB.Owen ProgramminginC

passing2darrays
Inpassingamultidimensionalarray,thefirstarraysize doesnothavetobespecified.Thesecond(andany subsequent)dimensionsmustbegiven! int myFun(int list[][10]);

31

CSE251Dr.CharlesB.Owen ProgramminginC

#defineROWS3 #defineCOLS5 int addMatrix(int [][COLS]); int main() { int a[][COLS]={{13, {13 22, 22 9 9,23, 23 12}, 12} {17, {17 5 5,24, 24 31, 31 55}, 55} {4, {4 19, 19 29, 29 41, 41 61}}; printf(Sum=%d\n,addMatrix(a)); } int addMatrix( int t[][COLS]) { int i,j,sum=0; for(i=0;i<ROWS;i++) for(j=0;j<COLS;j++) sum+=t[i][j]; returnsum; ; }

32

CSE251Dr.CharlesB.Owen ProgramminginC

CompilationandMakefiles

CSE251Dr.CharlesB.Owen ProgramminginC

LectureOutline
Whatisgcc?
Whatarethedifferentswitches available?

WhatisaMakefile? Exercise:
Takeanexistingfile,splititintomultipleseparate programs,andwriteaMakefile tosimplifycompilationof thefiles

CSE251Dr.CharlesB.Owen ProgramminginC

gccisnotasingleprogram
gcc isaconglomerationof programsthatworktogetherto makeanexecutablefile Weneedtoknowwhatitdoes andhowwecanbettercontrolit. Inparticular,wewouldliketobe abletomakemultiple, p ,separate p programswhichcanbecombined intooneexecutable

CSE251Dr.CharlesB.Owen ProgramminginC

Whatdoesgccdo?
code.c d
#include #i l d <stdio.h> tdi h #include<math.h> #defineNumIter 5 int main() { int i; for(i=1;i<=NumIter;i++) printf(PI^%dis%f\n,i,pow(M_PI,i)); }

Csource file

CSE251Dr.CharlesB.Owen ProgramminginC

Whatdoesgccdo?
preprocessor (#commands)

Expanded Ccode C Compiler il

Csource file Linker Executable

MachineCode ( ofile) (.o

Library Files

CSE251Dr.CharlesB.Owen ProgramminginC

Somegcc options Preprocessing P i (gcc E code.c d > code.i d i)


Removespreprocessordirectives(commandsthatstartwith#) Producescode.i Don Dont tusedirectly

Compiling (gcc o code.o c code.i)


Convertssourcecodetomachinelanguagewithunresolveddirectives Producesthecode.o binary

Linking (gcc lm o code code.o)


Createsmachinelanguageexectutable Producesthecode binarybylinkingwiththemathlibrary(lm)

CSE251Dr.CharlesB.Owen ProgramminginC

CPreprocessor,cpp
Expanded Ccode preprocessor (#commands)

Processescommandsthatare precededwith#symbols p y and expandsthecode


#include #define #ifdef and#ifndef

Csource file

CSE251Dr.CharlesB.Owen ProgramminginC

#include
Include headerfilesthatcontaindeclarationsnecessary forcompilingcode
thedeclarationsprovidethepropertypes,butnotthe actualdefinitions(theactualcode)

CSE251Dr.CharlesB.Owen ProgramminginC

stdio.h
#ifndef_STDIO_H #if!defined__need_FILE&& !defined__need___FILE #define_STDIO_H1 #include<features.h> __BEGIN_DECLS

data c data.c #include<stdio.h> #includefunctions.h int main(){ doublex=1; printf(Sinc(x)=%f\n,Sinc(x)); }

functions.h
doubleSinc(doublex);

gcc Edata.c >data.i data i islikeanexpanded data.i expanded Ccodeinwhichthe#includecommand issubstitutedwithtextfromthefiles

CSE251Dr.CharlesB.Owen ProgramminginC

main.c

Example
display h display.h voidDisplayMe(int n);

#includedisplay.h int main() { DisplayMe(12); }

10

CSE251Dr.CharlesB.Owen ProgramminginC

HeaderFiles
Wevebeenusing.hfilestodefinethingsfromtheClibraries: stdio.h,stdlib.h,stdbool.h,etc. ThesearecalledHeaderFiles. Weregoingtocreateourown.hfilestoshareinformation between.cfiles.

11

CSE251Dr.CharlesB.Owen ProgramminginC

#define #defines d f apreprocessorvariable bl


everyplacethevariableoccurs,thedefinitionwillbe substitutedascode

Syntax: y #define var_name _ var_definition _


Examples:
#define DEBUG 1 #d fi PI 3 #define 3.1415926535 1415926535

12

CSE251Dr.CharlesB.Owen ProgramminginC

preproc.c #include<stdio.h> #definePI3.14157265 3 14157265 #definesquare(x)(x*x) int main(){ printf("ValueofPIis%f\n",PI); printf("Squareof3.5is%f\n",square(3.5)); } #1preproc.c" #1"<builtin>" #1"<command <commandline> line> typedefunsignedintsize_t; intmain(){ printf("ValueofPIis%f\n",3.14157265); printf("Squareof3.5is%f\n",(3.5*3.5)); }
CSE251Dr.CharlesB.Owen ProgramminginC

gccE Epreproc.c preproc c>preproc.i preproc i

preproc.i

13

#ifdef, #ifndef, #if


Surroundcodethatmightbeincluded.Includefor compilationwhendesired #ifdef DEBUG . #endif #ifndef DEBUG #endif

14

CSE251Dr.CharlesB.Owen ProgramminginC

Commonuse
if(num==1) { /*Thisistheonlytimeweactuallymoveadisk*/ DisplayTower(tower); #if0 printf("Pressreturn"); fgets(cmd, ( sizeof(cmd), ( ) stdin); ) #endif MoveDisk(tower,fm,to); return; }

Thisisahandywaytoturnoff ablockofcodewithout removingit. it Itoftenworks betterthantryingto commentouttheblock, whichmayhavecomments alreadyinit.

15

CSE251Dr.CharlesB.Owen ProgramminginC

hanoi.c:

HeaderFiles
hanoi h: hanoi.h: #defineNumDisks 6 #defineNumPins 3

#include<stdio.h> #include<stdlib.h> #include<stdbool.h> #includehanoi.h bool CheckDone(int tower[NumPins][NumDisks]); display.c: #include #i l d <stdio.h> di h #include<stdlib.h> #include<stdbool.h> #includehanoi.h voidDisplayTower(int tower[NumPins][NumDisks]) { }

Ihavetwo.cfilesin thesameprogram. B hneed Both dtoknow k NumDisks and NumPins.So,Iputthat informationina headerfile:hanoi.h

16

CSE251Dr.CharlesB.Owen ProgramminginC

hanoi.c:

Example
hanoi h: hanoi.h: #defineNumDisks 6 #defineNumPins 3

#includehanoi.h bool CheckDone(int tower[NumPins][NumDisks]); #if0 bool DebugStuff(int x,int b[NumPins]); #endif

17

CSE251Dr.CharlesB.Owen ProgramminginC

hanoi.c:

Whatwouldhappen?
hanoi h: hanoi.h: #defineNumDisks 6 #defineNumPins 3 solve.h: #includehanoi.h voidAutosolve(int tower[NumPins][NumDisks]);

#include<stdio.h> #include<stdlib.h> #include<stdbool.h> #includesolve.h #includehanoi hanoi.h h bool CheckDone(int tower[NumPins][NumDisks]);

18

CSE251Dr.CharlesB.Owen ProgramminginC

hanoi.c:

IncludeGuards
hanoi h: hanoi.h: #ifndef HANOI_H #defineHANOI_H #defineNumDisks 6 #defineNumPins 3 # dif #endif solve.h: #ifndef SOLVE_H SOLVE H #defineSOLVE_H #includehanoi.h voidAutosolve(int tower[NumPins][NumDisks]); #endif
19

#include<stdio.h> #include<stdlib.h> #include<stdbool.h> #includesolve.h #includehanoi hanoi.h h bool CheckDone(int tower[NumPins][NumDisks]);

IncludeGuards:Conditional compilationcodethatprotectsa sectionofcodeinaheaderfrom beingcompiledmorethanonce.

CSE251Dr.CharlesB.Owen ProgramminginC

Compiling
preprocessor (#commands)

Expanded Ccode

Object Code(.ofile) Compiler

gcc c code.c

Csource file

CompilertranslatestheCsourcecodeinto objectcode whatthemachineactually understands

Machinespecific

Eachlinerepresentseitherapieceofdataor amachinelevelinstruction

Tocreatetheassemblycode: gcc -c preproc.c

20

CSE251Dr.CharlesB.Owen ProgramminginC

Linking
Objectfilemay notbedirectlyexecutable
Missingsomeparts Stillhassomenamestoberesolved

Thelinker(ld)takesmultipleobjectfiles(.o) ( o)andputs themtogetherintooneexecutablefile


Resolvesreferencestocallsfromonefiletoanother

Linkingisimportantasitallowsmultiple,separate fil t files tob beb brought htt together th

21

CSE251Dr.CharlesB.Owen ProgramminginC

Linking

preprocessor gccE

Expanded Ccode Compiler p gcc c

MachineCode (.ofile) Csource file Linker Executable

gcc lm code.o o code

Library Files

22

CSE251Dr.CharlesB.Owen ProgramminginC

Separatecompilation
Forlarge,complexprograms,itisagoodideato breakyourfilesintoseparate.cand.hfiles Candebugeachseparately,thenreuse Candistributepiecestoothersotheycan incorporateintotheircodewithoutchangingtheir code(justlinkitin)

23

CSE251Dr.CharlesB.Owen ProgramminginC

Example(SeparateCompilation)
mainprog.c shapes.h shapes.c

math.h

mainprog

gcc -c shapes.c g p gcc c mainprog.c gcc lm mainprog.o shapes.o o mainprog

24

CSE251Dr.CharlesB.Owen ProgramminginC

Anotherway(Compileallatonce)
mainprog.c shapes.h shapes.c

math.h

mainprog

gcc lm l shapes.c h mainprog.c i o mainprog i

25

CSE251Dr.CharlesB.Owen ProgramminginC

Controllingcompilation/linkingbetter
Weneedabetterwaytocontrolcompilation
toomuchdetailtotypeeachtime

Wecansavetimebyonlyupdating(compiling)the partsthatneedupdating
ifa.ofileisOK(unchangedsource),leaveit.Ifa.cfileis changed,the.ofileneedstoberegeneratedthen everythingrelinked

26

CSE251Dr.CharlesB.Owen ProgramminginC

Makefiles
Supposeyouhaveaprogram,whichismadeupof these5sourcefiles:
main.c (includedata.h,io.h) data.c (includedata.h) d data.h h io.c (includeio.h) io h io.h

27

CSE251Dr.CharlesB.Owen ProgramminginC

Howtocreatetheexecutable?
data.c data.h main.c io.h io.c

gcc -c data.c data.o gcc -c c io.c io c io.o io o gcc -c main.c main.o gcc main.o i i io.o d data.o t o executable t bl

28

CSE251Dr.CharlesB.Owen ProgramminginC

Howtocreatetheexecutable?
data.c data.h main.c io.h io.c

Whatifyoumodifydata.h? gcc -c data.c D youneed Do dto t rerungcccon gcc -c c io.c io c io.candmain.c? gcc -c main.c gcc main.o i i io.o d data.o t o executable t bl

29

CSE251Dr.CharlesB.Owen ProgramminginC

Dependencies

executable

data.o

main.o

io.o

data.c

data.h

main.c

io.h

io.c

30

CSE251Dr.CharlesB.Owen ProgramminginC

WhatisaMakefile?
AMakefile isusedwiththemake utilitytodetermine whichportionsofaprogramtocompile. Itisbasicallyascriptthatguidesthemakeutilityto choosetheappropriateprogramfilesthataretobe compiledandlinkedtogether

31

CSE251Dr.CharlesB.Owen ProgramminginC

Ifdata.hismodified

executable

d t data.o

main.o i

i io.o

data.c

data.h

main.c

io.h

io.c

Noneedtorecreatedata.oandmain.o

32

CSE251Dr.CharlesB.Owen ProgramminginC

Ifio.cismodified

executable

d t data.o

main.o i

i io.o

data.c

data.h

main.c

io.h

io.c

Noneedtorecreatedata.oandmain.o

33

CSE251Dr.CharlesB.Owen ProgramminginC

hanoi.h: #ifndef HANOI_H #defineHANOI_H #defineNumDisks 6 #defineNumPins 3 #endif solve.h: #ifndef SOLVE_H #defineSOLVE_H #includehanoi hanoi.h h voidAutosolve(int tower[NumPins][NumDisks]); #endif

hanoi.c: #include<stdio.h> #include<stdlib.h> #include<stdbool.h> #includesolve.h #includehanoi hanoi.h h bool CheckDone(int tower[NumPins][NumDisks]); display.c: #include<stdio.h> #include<stdlib.h> #include<stdbool.h> #includehanoi.h bool DisplayTower(int tower[NumPins][NumDisks]);

34

CSE251Dr.CharlesB.Owen ProgramminginC

WhatisinaMakefile?
namein column1 spaces notcommas

fil d file: dependency1 d 1d dependency2 d 2 command


TABcharacter

35

CSE251Dr.CharlesB.Owen ProgramminginC

Whatitmeans
Thefirstlineindicateswhatafiledependson.That is,ifanyofthedependencieschange,thenthatfile mustbeupdated
Whatupdatingmeansisdefinedinthecommandlisted belowthedependency

Dont Don tforgettheTABcharactertobeginthesecond line

36

CSE251Dr.CharlesB.Owen ProgramminginC

Dependencygraph
data.o main.o

Executable(prog)

io.o

data.c

data.h main.c

io.h

io.c

37

CSE251Dr.CharlesB.Owen ProgramminginC

CreatingaMakefile
Executable(prog)

Makefile:
prog: data.o:

data.o

main.o

io.o

main.o: io.o:
data.c data.h main.c io.h io.c

Listtheobject(*.o)andexecutablefiles thatmakeuptheprogram

38

CSE251Dr.CharlesB.Owen ProgramminginC

CreatingaMakefile
Executable(prog)

Makefile:
prog:data.o d t main.o i i io.o gcc oprog data.o main.o io.o data.o:data.h data.c gcc cdata.c main.o:data.h io.h main.c gcc cmain.c i io.o:io.h io.c gcc cio.c g Firstlinespecifiesthedependenciesfor eachobjectandexecutablefiles

data.o

main.o

io.o

data.c

data.h main.c

io.h

io.c

39

CSE251Dr.CharlesB.Owen ProgramminginC

CreatingaMakefile
Executable(prog)

Makefile:
prog:data.o d t main.o i i io.o gcc oprog data.o main.o io.o data.o:data.h data.c gcc cdata.c main.o:data.h io.h main.c gcc cmain.c i io.o:io.h io.c gcc cio.c g

data.o

main.o

io.o

data.c

data.h main.c

io.h

io.c

Secondlinecontainsthecommandto executeifany yofthedependence p files aremodified

40

CSE251Dr.CharlesB.Owen ProgramminginC

Additionalmakefile targets
clean: rm -rf *.o example22 Commandmakecleancallsthecleancommand Inthiscase, case clearsthe.o ofilesandtheexecutable

41

CSE251Dr.CharlesB.Owen ProgramminginC

Usage
make
Tocreatetheexecutable

makelinkedList.o
dowhathastobedonetomakethat.ofile,thenstop

makeclean
runthecleancommand

42

CSE251Dr.CharlesB.Owen ProgramminginC

structs
Aggregatingassociateddata intoasinglevariable
int main() { Boxmybox; Circlec; mybox.width mybox width =10; mybox.length =30; mybox.height =10; c.radius =10; }

Box
width length height

Circle
radius

CSE251Dr.CharlesB.Owen ProgramminginC

Theidea
Iwanttodescribeabox.Ineedvariablesfor thewidth,length,andheight. Icanusethreevariables,butwouldntitbe betterifIhadasinglevariabletodescribea box? Thatvariablecanhavethreeparts parts,thewidth width, length,andheight.

Box
width length height

CSE251Dr.CharlesB.Owen ProgramminginC

Structs
Astruct (shortforstructure)inCisagroupingof variablestogetherintoasingletype
Similartostructs inMatlab struct nameOfStruct { type member; type member; }; N t the Note th semicolon i l at tth theend. d Todeclareavariable: struct nameOfStruct variable_name;
3 CSE251Dr.CharlesB.Owen ProgramminginC

Example
Box
width idth length height

#include<stdio.h> struct Box { int width; int length; int height; }; struct Circle l { doubleradius; }; int main() { struct Boxb; struct Circlec; }

Data structure definition

Circle
radius

Youcan declare variables i bl

CSE251Dr.CharlesB.Owen ProgramminginC

Example
#include<stdio.h> struct Box { int width; int length; int height; };

int main(){ struct Boxb; b.width =10; b.length =30; b.height =10; }

Youcan assign g values toeach member

Box
width length g height

Weuseaperiod.togettothe elementsofastruct. Ifxisastruct,x.width isanelement inastruct. struct

CSE251Dr.CharlesB.Owen ProgramminginC

AnotherExample
struct t t bankRecordStruct b kR dSt t { Youcanusemixeddatatypes charname[50]; withinthestruct (int,float, floatbalance; char[]) }; struct bankRecordStruct billsAcc;

CSE251Dr.CharlesB.Owen ProgramminginC

Accessingvalues
struct t t bankRecordStruct b kR dSt t { charname[50]; floatbalance; };

Accessvaluesina struct usingaperiod: .

struct bankRecordStruct billsAcc; printf(My i tf(M balance b l is: i %f\n, %f\ billsAcc.balance); bill A b l ) floatbal=billsAcc.balance;

CSE251Dr.CharlesB.Owen ProgramminginC

AssignValuesusingScanf()
struct t t BankRecord k d {
charname[50]; floatbalance; ;

}; int main() () { struct BankRecord newAcc;/*createnewbankrecord*/ printf(Enter i tf(E t account tname:) ); scanf(%50s,newAcc.name); printf(Enteraccountbalance:); scanf(%d, scanf( %d ,&newAcc.balance); }

CSE251Dr.CharlesB.Owen ProgramminginC

Copyvia=
Youcansettwostruct typevariablesequaltoeach otherandeachelementwillbecopied
struct Box{int width,length,height;}; int main() { struct Boxb,c; b.width =5;b.length=1;b.height =2; c=b; //copiesallelementsofbtoc printf(%d%d%d\n,c.width,c.length,c.height); }
9 CSE251Dr.CharlesB.Owen ProgramminginC

PassingStructtoafunction
Youcanpassastruct toafunction.Alltheelements arecopied Ifanelementisapointer,thepointeriscopiedbut notwhatitpointsto! int myFunction(struct Personp) { }

10

CSE251Dr.CharlesB.Owen ProgramminginC

UsingStructsinFunctions
Writeaprogramthat
Promptstheusertoenterthedimensionsofa3Dboxand acircle Printsthevolumeoftheboxandareaofthecircle

Samplerun:

11

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h> #include<math.h> struct Box{int width, width height,length;}; int GetVolume(struct Boxb) { returnb.width *b.height *b.length; } int main() { struct Boxb; printf("Entertheboxdimensions(widthlengthheight):"); scanf("%d%d%d",&b.width,&b.length,&b.height); printf("Box printf( Boxvolume=%d\n %d\n", ,GetVolume(b)); }

12

CSE251Dr.CharlesB.Owen ProgramminginC

Note:==Comparisondoesntwork
struct Box{int width,length,height;}; int main() { struct Boxb,c; b width =5;b.length=1; b.width b length 1;b.height b height =2; c=b; if(c==b) /*Errorwhenyoucompile!*/ printf(candbareidentical\n); else printf(c printf( candbaredifferent\n); different\n ); }t
Errormessage:invalidoperandstobinary==(have'Box' Box and'Box') Box )
13 CSE251Dr.CharlesB.Owen ProgramminginC

Createyourownequalitytest
#include #i l d <stdio.h> < tdi h> #include<math.h> struct Box{int width, ,height g ,length; g ;}; int IsEqual(struct Boxb,struct Boxc) { if(b.width==c.width (b width==c width && b.length==c.length && b.height==c.height) return1; struct Boxb, b c; else b.width =5;b.length=1;b.height =2; return0; c=b; } if(IsEqual(b,c)) printf("candbareidentical\n"); else i tf(" and dbarediff t\ ") printf("c different\n");
14 CSE251Dr.CharlesB.Owen ProgramminginC

typedef
typedef isawayinCtogiveanametoacustomtype.
typedef typenewname; typedef int dollars; typedef unsignedcharByte;

Icandeclarevariableslike: dollarsd; Byteb b,c; Itsasifthetypealreadyexisted.


CSE251Dr.CharlesB.Owen ProgramminginC

15

typedef forArrays
Thereisaspecialsyntaxforarrays: typedef charNames[40]; typedef doubleVector[4]; typedef doubleMat4x4[4][4]; Now,insteadof: doublemat[4][4]; Icando: Mat4x4mat;

16

CSE251Dr.CharlesB.Owen ProgramminginC

UsingStructswithTypedef
typedef struct [nameOfStruct] { type member; yp member; type optional } TypeName yp ;
Todeclareavariable:TypeName variable_name;

17

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdio.h>

Example
Box
width l length th height

typedef struct { int width; int length; i t height; int h i ht }Box; yp struct { doubleradius;}Circle; typedef int main() { Box b; /*insteadofstruct Box*/ Circle c; /*insteadofstruct Circle*/ b.width =10; b l th =30; b.length 30 b.height =10; c.radius =10; }
CSE251Dr.CharlesB.Owen ProgramminginC

Ci l Circle
radius

18

Arraysofstructs
Youcandeclareanarrayofastructureandmanipulateeach one
typedef struct { d bl radius; double di int x; int y; char h name[10]; [10] }Circle; Circlecircles[5];

19

CSE251Dr.CharlesB.Owen ProgramminginC

SizeofaStruct:sizeof
typedef struct { doubleradius; int x; int y; charname[10]; }Circle;

/*8bytes*/ /*4bytes*/ /*4bytes*/ /*10bytes*/

printf(SizeofCirclestruct is%d\n, sizeof(Circle));

20

CSE251Dr.CharlesB.Owen ProgramminginC

SizeofaStruct 8+4+4+10=26
Butsizeof()reports28bytes!!!

Mostmachinesrequirealignmenton4byteboundary ( word) (a d)
lastwordisnotfilledbythechar(2bytesused,2leftover)
DDDD DDDD IIII
4byte, 1word integer

IIII
4byte, 1word integer

CCCC

CCCC

CCXX

8byte,2worddouble

10bytechararray,2bytes ofthelastwordunused

21

CSE251Dr.CharlesB.Owen ProgramminginC

Pointerstostructs
typedef struct { int width; int length; int height; }Box;

Boxb; /*AvariableoftypeBox*/ Box*c; /*ApointertoaBox*/ doublew; b.width =5;b.height =7;b.length =3; c=&b; /*Sameasbefore*/ w=c>width;

Toaccessthemembersofastruct,weuse: .foravariableofthestructs type >forapointertoastruct


22 CSE251Dr.CharlesB.Owen ProgramminginC

struct Concepts
struct Box { doublewid,hit; } }; typedef struct { doubleradius; int x; int y; charname[10]; }Circle;

struct Boxb; Circlec;

/*Notypedef */ /*typedef */

struct Box*pBox; /*PointertoBox*/ Circle*pCirc; /*PointertoCircle*/ pBox =&b; b.wid=3; pBox>wid =7; /*GetpointertoaBox*/

pCirc =&c; (*pCirc).radius=9;

23

CSE251Dr.CharlesB.Owen ProgramminginC

DynamicMemoryAllocation
Dynamicmemoryallocation
Howtoallocatememoryforvariables(esp.arrays/strings) duringruntime malloc(),calloc(),realloc(),andfree()

CSE251Dr.CharlesB.Owen ProgramminginC

Whydynamicmemoryallocation?
Usually,sofar,thearraysandstringswereusinghave fixedlength(i.e.,lengthisknownatcompiletime) Example:
char h myStr[11]; [ ] //allocates ll memoryfor f 10chars h printf(Enterastring:); fgets(myStr,11,stdin);

Whatiftheuserwantsto enterastringmorethan10 charslongorifthelengthis knownonly yatruntime?


2 CSE251Dr.CharlesB.Owen ProgramminginC

malloc()
malloc()isusedtorequestadditionalmemoryfromthe operatingsystemduringprogramexecution Syntax:malloc(numBytes) Inputisthenumberofconsecutivebytestobeallocated Returnvalueisapointer tothebeginningoftheblockof memoryallocatedorNULLifmalloc fails Tousemalloc(),youmust#include<stdlib.h>

CSE251Dr.CharlesB.Owen ProgramminginC

malloc() char h * *charP; h P /*d declare l apointer i tochar h */


charP

charP=malloc(10);
charP

10bytesorchars

charPcontainstheaddressofthebeginningofthatblock.

CSE251Dr.CharlesB.Owen ProgramminginC

free()
Thefunctionfree()returnsmemorytothememory pool.Itfreesupmemory
Syntax:free(ptr) whereptr points pointsto tomemorypreviouslyallocatedby malloc()function

Tousefree(),youmust#include<stdlib.h>

CSE251Dr.CharlesB.Owen ProgramminginC

Example

Thisprogramallowstheuserto specifythelengthofastring, string allocatesmemoryforthestring,and pp string goperations p thenapplies

CSE251Dr.CharlesB.Owen ProgramminginC

#include<stdlib.h> #include<stdio.h> #include<string.h> int main() { char*charP, ,*q; q; int maxlen;

/*youneedthislibraryformalloc(),free(),exit()*/ /*youneedthislibraryforstrchr(),strlen()*/

printf("Entermaximumstringlength:"); scanf("%d" scanf( %d ,&maxlen); getchar(); /*readsthenewlinecharacter*/ p printf("Enter ( thestring: g "); ) fgets(charP,maxlen,stdin); if((q=strchr(charP,'\n'))!=NULL) *q='\0'; printf("You'veenteredastring%soflength%d\n",charP,strlen(charP)); free(charP); }
7 CSE251Dr.CharlesB.Owen ProgramminginC

Whatitdoes:
if((q=strchr(charP,'\n'))!=NULL) *q='\0'; Thefunctionfgets returnstheentirelineinputbytheuserincludingthe newlineattheend(whentheuserhitreturn).Thefunctionstrchr(charP,\n) willreturnapointertothatcharacter(newline)ifitexistsorNULLotherwise otherwise.If theresultinthevariableqisnotNULL,theifstatementexecutesthelineof codetoreplacethenewlinewithanullterminationforthestring.

CSE251Dr.CharlesB.Owen ProgramminginC

strchr
if((q=strchr(charP,'\n'))!=NULL) *q='\0';

Thiscodefindsthefirstoccurance ofthe character\nwhichisthenewlinecharacter thatfgets willobtain. obtain Iffound(valueinqis notNULL),itsetsthatcharactertothestring nulltermination.

CSE251Dr.CharlesB.Owen ProgramminginC

Memoryleak
Ifmalloced memoryisnotfreeed,thentheOSwill leakmemory
Thismeansthatmemoryisallocatedtotheprogrambut notreturnedtotheOSwhenitisfinishedusingit Theprogramthereforegrowslargerovertime. time

10

CSE251Dr.CharlesB.Owen ProgramminginC

int main() { Example char*charP,r[80]; int length;

Memoryleakexample

while(1) { printf("Enterthemaximumstringlength:"); fgets(r,80,stdin); sscanf(r,"%d",&length); if((charP =malloc(length))==NULL){ printf("Outofmemory.Quitting\n"); exit(1); ( ); } printf("Enterthestring:"); fgets(charP,length,stdin); /*free(charP);*/ } }
CSE251Dr.CharlesB.Owen ProgramminginC

11

int main() { Example char*charP,r[80]; int length;

Memoryleakexample
Eachiterationoftheloopallocatesmemory forastring.But,thatmemoryisneverfreed. Hence,wehaveamemoryleak.

while(1) { printf("Enterthemaximumstringlength:"); fgets(r,80,stdin); sscanf(r,"%d",&length); if((charP =malloc(length))==NULL){ printf("Outofmemory.Quitting\n"); exit(1); ( ); } printf("Enterthestring:"); fgets(charP,length,stdin); /*free(charP);*/ } }

12

CSE251Dr.CharlesB.Owen ProgramminginC

mallocwithoutfreeing

while(1) { charP =malloc(length+1); }

charP

Ifyoudontfreetheallocatedmemory,previousblockisstillours accordingtotheOS,butwecannolongerfindit(nopointertoit).That blockisanorphan! Itslikeyouboughtahouse,butthenlostthe address Youstillownitandpaytaxesonit, address. it but youcantuseitbecauseyoucantfindit.

13

CSE251Dr.CharlesB.Owen ProgramminginC

Alwaysfreewhatyoumalloc
Youareresponsibleforyourmemory,youmust allocateitandfreeit. Unlikeotherlanguages,itisalluptoyou! Ifyoudontfreeit,yourprogramgrowslargerand eventuallyrunsoutofmemory!

14

CSE251Dr.CharlesB.Owen ProgramminginC

mallocallocatesbytes
Ifyouwantacharacterarraythatstores10 characters(including\0):
char*p=malloc(10);

Ifyouwant tto t allocate ll t storage t for f 10ints i t (or ( d doubles bl orfloats),youcantdothis:


int *p p=malloc(10); /*WRONG!Why?*/ / /

15

CSE251Dr.CharlesB.Owen ProgramminginC

allocateintanddoublearray
int *intP; double*doubleP; //Allocatespacefor10integers intP =malloc(10*sizeof(int)); //Allocatespacefor10doubles doubleP =malloc(10*sizeof(double));

16

CSE251Dr.CharlesB.Owen ProgramminginC

allocateintanddoublearray
int *intP; double*doubleP; //Allocatespacefor10integers intP =malloc(10*sizeof(int)); Allocates40bytes sizeof(int)=4

//Allocatespacefor10doubles doubleP =malloc(10*sizeof(double)); Allocates80bytes sizeof(double)=8

17

CSE251Dr.CharlesB.Owen ProgramminginC

realloc
realloc takesapointertoallocatedmemoryand reallocatesthememorytoalargersize
ifitcanmaketheoldblockbigger,great ifnot,itwillgetanother,largerblock,copytheold contentstothenewcontents, contents freetheoldcontentsand returnapointertothenew intP =malloc(sizeof(int)); intP =realloc(intP,2*sizeof(intP)); intP maybedifferentafterarealloc!

18

CSE251Dr.CharlesB.Owen ProgramminginC

int main() { double*dblPtr; int howMany, howMany randNum; randNum

Step1: Prompttheusertoenter thenumberofrandomnumbersto generate

printf("Howmanyrandomnumberstogenerate:"); howMany=ProcessInput(stdin); dblPtr =malloc(howMany *sizeof(double)); if(dblPtr ==NULL) { printf("memory printf( memoryallocationerror, error exiting\n exiting\n"); ); exit(1); } for(int i=0;i<howMany;i++) { randNum =random(); dblPtr[i]=(randNum%10000)/1000 0; dblPtr[i]=(randNum%10000)/1000.0; } PrintArray(dblPtr,howMany);
CSE251Dr.CharlesB.Owen ProgramminginC

Anexample p program p g

19

int main() { double*dblPtr; int howMany, howMany randNum; randNum printf("Howmanyrandomnumberstogenerate:"); howMany=ProcessInput(stdin); dblPtr =malloc(howMany *sizeof(double)); if(dblPtr ==NULL) { printf("memory printf( memoryallocationerror, error exiting\n exiting\n"); ); exit(1); } for(int i=0;i<howMany;i++) { randNum =random(); dblPtr[i]=(randNum%10000)/1000 0; dblPtr[i]=(randNum%10000)/1000.0; } PrintArray(dblPtr,howMany);

Step2: createadynamicarrayto storetherandomnumbers

Inthisexamplewehave testedtobesuremalloc succeeded.Ifnot,weare outofmemory.

20

CSE251Dr.CharlesB.Owen ProgramminginC

int main() { double*dblPtr; int howMany, howMany randNum; randNum

Step3: generatetherandom numbersandprintthem

printf("Howmanyrandomnumberstogenerate:"); howMany=ProcessInput(stdin); dblPtr =malloc(howMany *sizeof(double)); if(dblPtr ==NULL) { printf("memory printf( memoryallocationerror, error exiting\n exiting\n"); ); exit(1); } for(int i=0;i<howMany;i++) { randNum =random(); dblPtr[i]=(randNum%10000)/1000 0; dblPtr[i]=(randNum%10000)/1000.0; } PrintArray(dblPtr,howMany);
CSE251Dr.CharlesB.Owen ProgramminginC

21

dblPtr =realloc(dblPtr,2*howMany);

Step4: doublethesizeofthearrayusing realloc

for(int i=howMany;i<howMany*2;i++) { randNum =random(); dblPtr[i]=(randNum%10000)/1000.0; } howMany *=2; PrintArray(dblPtr,howMany); PrintArray(dblPtr free(dblPtr); }

Step5: generatemorerandom numbersandprintthem

22

CSE251Dr.CharlesB.Owen ProgramminginC

int ProcessInput(FILE p ( *f) ) { int val; Safedataentry, y,j justlikelast week charin[100]; fgets(in,100,f); sscan(in,%d,&val); returnval; }

23

CSE251Dr.CharlesB.Owen ProgramminginC

PrintArray
voidPrintArray(double*ptr,int cnt) { printf("PrintingArrayValues\n"); ( *p=ptr; p p ;p p<ptr+cnt; p ;p++) p ) for(double printf("Valis:%lf\n",*p); }

24

CSE251Dr.CharlesB.Owen ProgramminginC

Potrebbero piacerti anche