Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
office hours Thu 2-4 Soroor Soltani (TA and grading) Classroom: 3353 Engineering Charles B. Owen BuildingCSE 251 Dr.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)
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.)
Course Structure
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
Grading
3 projects, each for 15% of the grade, total 45%
Attendance is important
We drop the lowest step assignment grade!
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
11
12
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
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
Bringing up
Bring up a terminal Window Applications/ Accessories/Terminal Type: cal 2011
15
Directories
16
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
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
a.out
Leaves
18
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
20
21
22
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
.. 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
24
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
cp ../file.c ~/programs
cp file.c in parent directory to the sub-directory programs under the home directory
26
rm ./file.c
remove file.c in the current directory
rm i ./file.c
interactive, are you sure?
27
man
man pages exist on Unix, providing documentation (a lot of documentation) on each command man ls
man page on the ls command
man -S 2 mount
man page for section 2 of mount
28
yelp runs using the lifesaver icon. Go to Advanced options, man pages
29
30
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
31
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
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
Command completion
Type a partial command, followed by tab. it will complete as much as it can
34
Compiling
35
36
37
38
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
Editors
40
Many Editors
Examples:
gedit vi emacs pico kate
41
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
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
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
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
18
CSE251Dr.CharlesB.Owen ProgramminginC
FullFormatstring g
Theformatstringcontainsasetofformatdescriptors thatdescribehowanobjectistobeprinted
% -#0 12 .4 h d
Conversion Type (dfordecimal) size modifier (hforshortint) Precision
dh Width
19
CSE251Dr.CharlesB.Owen ProgramminginC
Examples printf(%f\n,M_PI); f( f\ )
3.141593
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);
27
CSE251Dr.CharlesB.Owen ProgramminginC
Basicform
Tounderstandinput,itisprobablybettertostartwith anexample. scanf(%d, %f, &myInt, &myFloat);
int float
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
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
CSE251Dr.CharlesB.Owen ProgramminginC
Structureofan ifstatement
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
11
CSE251Dr.CharlesB.Owen ProgramminginC
Exampleifstatements
if(age<18) printf(Tooyoungtovote!\n);
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
13
CSE251Dr.CharlesB.Owen ProgramminginC
Whereisthisuseful?
14
CSE251Dr.CharlesB.Owen ProgramminginC
Whereisthisuseful?
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!
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.
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
p && q p || q
33
CSE251Dr.CharlesB.Owen ProgramminginC
Truth Tables
N Not A d And O Or
p && q p || q
34
CSE251Dr.CharlesB.Owen ProgramminginC
Truth Tables
N Not A d And O Or
!p
35
CSE251Dr.CharlesB.Owen ProgramminginC
Truth Tables
N Not A d And O Or
!p
36
CSE251Dr.CharlesB.Owen ProgramminginC
Truth Tables
N Not
37
CSE251Dr.CharlesB.Owen ProgramminginC
Precedence&Associativity
Canyouguesswhat whats stheanswer?
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
40
CSE251Dr.CharlesB.Owen ProgramminginC
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
statement count++
CSE251Dr.CharlesB.Owen ProgramminginC
doubleincome; int filingStatus; int numDependents; int children; doublestandardDeduction; doubledeductions; doubletaxableIncome; doubletax;
First,thetaxprogram
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
CSE251Dr.CharlesB.Owen ProgramminginC
while(condition)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
Examplewith whileloop
Whatdoesthisdodifferent?
11
CSE251Dr.CharlesB.Owen ProgramminginC
while
while(condition) statement; while(condition) { statement1; statement2; }
false
while(!valid) until hil (! lid)/*Loop L tilvalue l is i valid lid*/ { printf("Entertheinductanceinmillihenrys:"); scanf("%lf",&l); if(l>0) { valid=true; } }
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;
16
CSE251Dr.CharlesB.Owen ProgramminginC
count<=5
false
17
CSE251Dr.CharlesB.Owen ProgramminginC
Ascendingfor <=,++ ,
control_var =init_value
true
control_var <=limit_value
false
statement control_var++
18
CSE251Dr.CharlesB.Owen ProgramminginC
control_var =init_value
true
control_var >=limit_value
false
statement control_var
19
CSE251Dr.CharlesB.Owen ProgramminginC
20
CSE251Dr.CharlesB.Owen ProgramminginC
count=1
true printf
count<=5
false
count++
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 {
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
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); }
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
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
Variables
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
Area
p ( p a )( p b)( p c)
area =
a+b+c p= 2
CSE251Dr.CharlesB.Owen ProgramminginC
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
13
CSE251Dr.CharlesB.Owen ProgramminginC
double CtoF(double) ( )
Declarationsdescribethefunction:
thereturntypeandfunctionname thetypeandnumberofparameters
14
CSE251Dr.CharlesB.Owen ProgramminginC
Function Definition
15
CSE251Dr.CharlesB.Owen ProgramminginC
FunctionInvocation
int main() { f = CtoF(c); }
16
CSE251Dr.CharlesB.Owen ProgramminginC
Invocation(cont)
int main() { f = CtoF(c); }
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
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));
20
CSE251Dr.CharlesB.Owen ProgramminginC
Whatdoesourfunctionneedtoknow?
a=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2));
21
CSE251Dr.CharlesB.Owen ProgramminginC
Whatdoesourfunctionreturn?
a=sqrt((x1 x2)*(x1 x2)+(y1 y2)*(y1 y2));
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
25
CSE251Dr.CharlesB.Owen ProgramminginC
Another Example
Declarations
Invocations
26
CSE251Dr.CharlesB.Owen ProgramminginC
doubleGetTemperature() { doubleTemp; p;
Function: GetTemperature
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);
30
CSE251Dr.CharlesB.Owen ProgramminginC
Abstraction
intmain() { double TempC //TemperatureindegreesCelsius TempC, TempF;//TemperatureindegreesFahrenheit TempC=GetTemperature(); TempF=CelsiusToFahrenheit(TempC); ( ) DisplayResult(TempC,TempF); return0; }
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.
33
CSE251Dr.CharlesB.Owen ProgramminginC
InfiniteRecursion
intFactorial(intn) { returnn*Factorial(n1); }
WhatifIomitthebasecase? Thisleadstoinfiniterecursion!
34
CSE251Dr.CharlesB.Owen ProgramminginC
PsuedocodeandFunction
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
Variable B pB
Value
CSE251Dr.CharlesB.Owen ProgramminginC
ComputerMemory
Memoryisjustalonglistof numbersoneaftertheother Mylaptophasover4Billionof thesenumbers
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.
CSE251Dr.CharlesB.Owen ProgramminginC
CSE251Dr.CharlesB.Owen ProgramminginC
Arithmetic(inHex)
Sum: 0x 90 +0x 04 0x 94
CSE251Dr.CharlesB.Owen ProgramminginC
Arithmetic(inHex)
Sumwithcarry: 0x 8c +0x 04 0x??
CSE251Dr.CharlesB.Owen ProgramminginC
Arithmetic(inHex)
Sumwithcarry: 0x 8c +0x 04 0x??
10
CSE251Dr.CharlesB.Owen ProgramminginC
Arithmetic(inHex)
Sumwithcarry:
0x 8c +0x 04 0x??
11
CSE251Dr.CharlesB.Owen ProgramminginC
Arithmetic(inHex)
Sumwithcarry:
0x 8c +0x 04 0x90
12
CSE251Dr.CharlesB.Owen ProgramminginC
BytesandWords
byte word
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
15
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
17
CSE251Dr.CharlesB.Owen ProgramminginC
ExampleProgram
inta=21; int*pA=&a;
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 )
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
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
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
22
CSE251Dr.CharlesB.Owen ProgramminginC
FirstSection
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
25
CSE251Dr.CharlesB.Owen ProgramminginC
SecondExample
Address Memory y 15 49 38 0xeffffa94 Name A B C
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);
0xeffffa94
x y
0xeffffa98
0xeffffc8c
34
CSE251Dr.CharlesB.Owen ProgramminginC
Example
int x,y; x=5; y=Square(x);
0xeffffa94
x y
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
val
0xeffffa90
38
CSE251Dr.CharlesB.Owen ProgramminginC
FunctionReferenceParams
Name Address Value 10
val
0xeffffa90
39
CSE251Dr.CharlesB.Owen ProgramminginC
FunctionReferenceParams
Name Address Value 27
val
0xeffffa90
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
41
CSE251Dr.CharlesB.Owen ProgramminginC
Whatwillthisdodifferent?
Name Address Value 10
val
0xeffffa90
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);
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
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)!
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
VariableDeclaration forthearray
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
17
CSE251Dr.CharlesB.Owen ProgramminginC
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
SortArray(values,NumElements );
22
CSE251Dr.CharlesB.Owen ProgramminginC
ParameterPassing
voidPrintArray(doublearray[],int size) { } array isaCarrayofdoubles
23
CSE251Dr.CharlesB.Owen ProgramminginC
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
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
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
34
CSE251Dr.CharlesB.Owen ProgramminginC
SelectionSort
2 0 8 1 6 2 4 3
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
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
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
43
CSE251Dr.CharlesB.Owen ProgramminginC
Swap
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
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
CSE251Dr.CharlesB.Owen ProgramminginC
myStr
a b c d \0
CSE251Dr.CharlesB.Owen ProgramminginC
Anotherway
myStr
CSE251Dr.CharlesB.Owen ProgramminginC
Betterway
myStr
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); }
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);
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);
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[])
20
CSE251Dr.CharlesB.Owen ProgramminginC
comparison(strcmp)
int strcmp (const char s1[], const char s2[]);
Compares2strings
ifs1precedess2,returnvalueislessthan0 ifs2precedess1,returnvalueisgreaterthan0 ifs1equaltos2,returnvalueis0
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
CSE251Dr.CharlesB.Owen ProgramminginC
NamingConventions States
Wewillusuallynamestateswithcamelcaseandacapitalfirst letter.Welluse#definesinourprogramsforstatenames. WaitingForKeypress WaitingForElvis RaisingFirearm CellphoneDialing DoorOpening Verbswithing ing
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
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; } }
17
CSE251Dr.CharlesB.Owen ProgramminginC
Wenowhavethis
Thisisasimple2statestatement.
18
CSE251Dr.CharlesB.Owen ProgramminginC
Whathappens
while(IsGarageRunning()) { switch(state) { caseDoorClosed: StateDoorClosed(&state); break; } }
ControlLoop
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
CSE251Dr.CharlesB.Owen ProgramminginC
Read& asat at
CSE251Dr.CharlesB.Owen ProgramminginC
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; }
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 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]
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*/
CSE251Dr.CharlesB.Owen ProgramminginC
Pointerand[]
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+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
1.0
2.0
3.0
15
CSE251Dr.CharlesB.Owen ProgramminginC
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};
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
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
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));
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
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
26
CSE251Dr.CharlesB.Owen ProgramminginC
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
13 17 4
22 5 19
9 24 29
23 31 41
? 55 61
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)
Library Files
CSE251Dr.CharlesB.Owen ProgramminginC
CSE251Dr.CharlesB.Owen ProgramminginC
CPreprocessor,cpp
Expanded Ccode preprocessor (#commands)
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
functions.h
doubleSinc(doublex);
CSE251Dr.CharlesB.Owen ProgramminginC
main.c
Example
display h display.h voidDisplayMe(int n);
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
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
preproc.i
13
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; }
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]);
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
CSE251Dr.CharlesB.Owen ProgramminginC
Compiling
preprocessor (#commands)
Expanded Ccode
gcc c code.c
Csource file
Machinespecific
Eachlinerepresentseitherapieceofdataor amachinelevelinstruction
20
CSE251Dr.CharlesB.Owen ProgramminginC
Linking
Objectfilemay notbedirectlyexecutable
Missingsomeparts Stillhassomenamestoberesolved
21
CSE251Dr.CharlesB.Owen ProgramminginC
Linking
preprocessor gccE
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
24
CSE251Dr.CharlesB.Owen ProgramminginC
Anotherway(Compileallatonce)
mainprog.c shapes.h shapes.c
math.h
mainprog
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
35
CSE251Dr.CharlesB.Owen ProgramminginC
Whatitmeans
Thefirstlineindicateswhatafiledependson.That is,ifanyofthedependencieschange,thenthatfile mustbeupdated
Whatupdatingmeansisdefinedinthecommandlisted belowthedependency
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
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; }
Circle
radius
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; }
Box
width length g height
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; };
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;
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;
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;
struct Concepts
struct Box { doublewid,hit; } }; typedef struct { doubleradius; int x; int y; charname[10]; }Circle;
/*Notypedef */ /*typedef */
struct Box*pBox; /*PointertoBox*/ Circle*pCirc; /*PointertoCircle*/ pBox =&b; b.wid=3; pBox>wid =7; /*GetpointertoaBox*/
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);
malloc()
malloc()isusedtorequestadditionalmemoryfromthe operatingsystemduringprogramexecution Syntax:malloc(numBytes) Inputisthenumberofconsecutivebytestobeallocated Returnvalueisapointer tothebeginningoftheblockof memoryallocatedorNULLifmalloc fails Tousemalloc(),youmust#include<stdlib.h>
CSE251Dr.CharlesB.Owen ProgramminginC
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
CSE251Dr.CharlesB.Owen ProgramminginC
/*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';
CSE251Dr.CharlesB.Owen ProgramminginC
Memoryleak
Ifmalloced memoryisnotfreeed,thentheOSwill leakmemory
Thismeansthatmemoryisallocatedtotheprogrambut notreturnedtotheOSwhenitisfinishedusingit Theprogramthereforegrowslargerovertime. time
10
CSE251Dr.CharlesB.Owen ProgramminginC
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
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
charP
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);
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
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
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);
20
CSE251Dr.CharlesB.Owen ProgramminginC
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);
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); }
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