c programming 1 - university of the pacific · lab schedule activities ì this week ì intro to...
TRANSCRIPT
ìComputerSystemsandNetworksECPE170–JeffShafer–UniversityofthePacific
CProgramming1
LabSchedule
Activitiesì ThisWeek
ì IntrotoBuildToolsandMakefiles
ì IntrotoC1ì Lab3–BuildTools
ì NextWeekì IntrotoC2ì Lab4–CProgramming
Project
Deadlinesì Lab3–Feb4th2020
by5am
ì Lab4–Feb18th2020by5am
Spring2020ComputerSystemsandNetworks
2
PersonoftheDay:DennisRitchie
ì CreatorofCprogramminglanguage
ì Co-creatorofUnix(withKenThompson,BrianKernighan,andothersatBellLabs)
ì WinnerofACMTuringAward
ì 9/9/1941—10/12/2011
ComputerSystemsandNetworks
3
Spring2020
PersonoftheDay:DennisRitchie
ì “Prettymucheverythingonthewebusesthosetwothings:CandUNIX.ThebrowsersarewritteninC.TheUNIXkernel—thatprettymuchtheentireInternetrunson—iswritteninC.WebserversarewritteninC,andifthey’renot,they’rewritteninJavaorC++,whichareCderivatives,orPythonorRuby,whichareimplementedinC.AndallofthenetworkhardwarerunningtheseprogramsIcanalmostguaranteewerewritteninC.It’sreallyhardtooverstatehowmuchofthemoderninformationeconomyisbuiltontheworkDennisdid.”ì RobPike,BellLabs/Google
ComputerSystemsandNetworks
4
Spring2020
Spring2019ComputerSystemsandNetworks
5
DennisRitchieandKenThompsonuseateletypewritertorunaprogramonaUNIX-basedcomputersystemtheyco-foundedatBellLabsinNewJersey.Theirdevelopmentworkmorethan40yearsagofacilitatedtherealizationoftheInternet.
ìCProgramming
ComputerSystemsandNetworks
6
Spring2020
C++FeaturesNotinC
ì Noclasses/object-orientedprogramming
ì Nonew/delete
ì Nostreamoperators(<<and>>),cin,cout,…
ì NoC++StandardLibraries(e.g.iostream)
ì boolkeywordì AddedinC99standard
ì Declarevariablesanywhereinsidefunctionì AddedinC99standard
ComputerSystemsandNetworks
7
Spring2020
ìConsoleI/O
ComputerSystemsandNetworks
8
Spring2020
Outputwithprintf()
ì printf("This is a string\n");
ì printf("The integer is %i\n", num);
ì printf("The floating-point values are %g and %g\n", num1, num2);
ComputerSystemsandNetworks
9
Spring2020
Outputwithprintf()
ComputerSystemsandNetworks
10
Format“Type”Code CorrespondingVariableType
dori int(interpretassigned2’scomp)
u int(interpretasunsigned)
x int(printashexadecimal)
forg float/double
c char
s string(null-terminatedarrayofchars)
Prefixwithlorll(i.e.“long”or“longlong”forlarger64-bitdatatypes)
ì Lotsofformattingoptionsnotlistedhere…ì #ofdigitsbefore/afterdecimalpoint?ì Padwithzeros?
Spring2020
Inputwithscanf()
ì Inputfromconsole
ì scanf("%d %c", &myint, &mychar)
ì Requirestheaddressofthedestinationvariableì Usethe&operatortoobtainaddress
ì Caveat:Arraynamesarealreadythe“addressof”!ì char myarray[8];
scanf("%s", myarray)
ComputerSystemsandNetworks
11
No&neededhere!
Spring2020
Documentation
ì Man(ual)pagesexistforcommonprogrammingfunctionstoo
ComputerSystemsandNetworks
12
$ man printf
$ man scanf
Spring2020
ìArrays
ComputerSystemsandNetworks
13
Spring2020
Arrays
ì Contiguousblockofmemory
ì Youcanhavearraysforint, char, float, double,structures…
ComputerSystemsandNetworks
14
int myarray[5]; //static declaration
4 8 12 16 20
myarray[0] myarray[1] myarray[2] myarray[3] myarray[4]
NOTE:Nameofthearrayistheaddressofthefirstelementprintf("%p",myarray); //prints what?
Spring2020
2DArrays
ComputerSystemsandNetworks
15
int myarray[5][5]; //static declaration
Address:4myarray[0][0]
Address:8
Address:12
Address:16 Address:20
Address:24 Address:28myarray[1][1]
Address:32
Address:36
Address:40
Address:44 Address:488 Address:52 Address:56
Address:60
Address:64
Address:68
Address:72myarray[3][2]
Address:76 Address:80
Address:84 Address:88 Address:92 Address:96 Address:100
Memorymap:
Spring2020
Problem1:Loopingthroughanarray
ì Considera3-Darray,int image[256][256][3]foranRGBcolorimage.Thefirstsubscriptdenotesthenumberofrows,thesecondsubscriptdenotesthenumberofcolumns,andthethirdsubscriptdenotesthenumberofcolorchannels.Forexample,apixelatrowi andcolumn j willhaveanRvaluegivenbyimage[i][j][0],Gvaluegivenbyimage[i][j][1],andBvaluegivenbyimage[i][j][2].AnypixelhasayellowcolorifitsRandGvaluesare255andBvalueis0.
ì Writeaforlooptosearchforthelocationoftheveryfirstyellowpixelinimage.Thesearchshouldterminateoncetheyellowpixelisfound.Searchinrow-wisemanner.
ComputerSystemsandNetworks
16
P1
Spring2020
ìPointers
ComputerSystemsandNetworks
17
Spring2020
Pointers
ì Pointersarespecialvariablesthathold/storememoryaddressesofothervariables
ì Whenapointer(e.g.iptr)holdstheaddressofanintegervariable(e.g.ivar),thenwesay:“iptrisanintegerpointerthatpointstoivar”
ComputerSystemsandNetworks
18
int ivar=45;int *iptr; iptr = &ivar; //iptr points to ivar
45
ivar:
address:65536
65536
iptr:
address:65520
Spring2020
Pointers
ì &is‘addressofvariable’operatorì Example:&ivar translatesto
“addressofvariableivar”
ì *is‘valueataddressstoredinpointer’operatorì Example:*iptr translatesto
“valueataddressstoredinpointeriptr”
ComputerSystemsandNetworks
19
Spring2020
Pointers
ì Canhavemultiplelevelsof“indirection”
ì int *myptr ì Apointertoaninteger
ì int **myptr ì Apointertoapointertoaninteger
ì int ***myptr ì Apointertoapointertoapointertoaninteger
ComputerSystemsandNetworks
20
Spring2020
Problem2-Pointers
Consider the variables below: Variable Name: ivar Pointer variable name: iptr value: 5 value: Address: 0xFFABCD Address: OxAFABAD int ivar=5; int *iptr; iptr = &ivar; printf(“\n %d”,ivar); prints________ printf(“\n %x”,&ivar); prints________ printf(“\n %x”,&iptr); prints________ printf(“\n %d”,*iptr); prints________ ComputerSystemsandNetworks
21
P2
Spring2020
Problem3–MorePointers Variable Name: ivar Pointer variable name: iptr Pointer variable name: dptr value: 5 value: value: Address: 0xFFABCD Address: OxAFABAD Address: OxFFACBD int ivar=5; int *iptr; int **dptr; iptr = &ivar; dptr=&iptr; printf(“\n %x”,dptr); prints________ printf(“\n %x”,iptr); prints________ printf(“\n %u”,**dptr); prints________ //printf(“\n %x”,*dptr); prints________ //printf(“\n %x”,&dptr); prints________ //printf(“\n %x”,*(&(iptr))); prints________
ComputerSystemsandNetworks
22
P3
Spring2020
Problem4–MorePointers
ComputerSystemsandNetworks
23
P4
CollaboratewithapartnerandanswerQuestion4-5
Spring2020
ìC-Strings(ArraysofCharacters)
24
ComputerSystemsandNetworks Spring2020
CStrings
ì Thereisnosuchthingasa“string”inC!
ì Whatdoyouget?Anarrayofcharactersì Terminatedbythenullcharacter'\0'
ì Mustmanipulateelementbyelement…ì Notenoughroominthearray?Needabiggerarray
ComputerSystemsandNetworks
25
Spring2020
ArraysofCharacters
ì char phrase[]="Math";
26
phrase
M A T H \0
phrase[0] phrase[1] phrase[2] phrase[3] phrase[4]
Nullterminatorcharacter(Endofstring)
ComputerSystemsandNetworks Spring2020
ArraysofCharacters
ì char phrase[8]="Math";
27
phrase
M A T H \0 ??? ??? ???
phrase[0] phrase[1] phrase[2] phrase[3] phrase[4] phrase[5] phrase[6] phrase[7]
printf("%s\n", phrase); Printsuntilitreaches the\0character!
ComputerSystemsandNetworks Spring2020
HelpfulLibraryforCharacterArrays
ì #include <string.h>
ì Usefulfunctionsì strcpy-Stringcopyì strcmp-Stringcompareì strlen-Stringlengthì strcat-Stringconcatenate
28
ComputerSystemsandNetworks Spring2020
StringCopy
ì char phrase1[] = "Math";
ì char phrase2[8];
ì strcpy(phrase2, phrase1);
29
phrase1
M A T H \0
phrase1[0] phrase1[1] phrase1[2] phrase1[3] phrase1[4]
phrase2
M A T H \0 ??? ??? ???
phrase2[0] phrase2[1] phrase2[2] phrase2[3] phrase2[4] phrase2[5] phrase2[6] phrase2[7]
ComputerSystemsandNetworks Spring2020
StringConcatenation
ì char phrase1[8] = “Comp”;
ì char phrase2[] = “Sci”;
ì strcat(phrase1, phrase2);
30
phrase1
C O M P S
phrase1[0] phrase1[1] phrase1[2] phrase1[3] phrase1[4]
phrase2
S C I \0
phrase2[0] phrase2[1] phrase2[2] phrase2[3]
C I \0
phrase1[5] phrase1[6] phrase1[7]
Youcannotdothis:phrase2= phrase1+phrase2;
ComputerSystemsandNetworks Spring2020
ctypeLibrary
ì Usefulforcharactermanipulation
ì #include <ctype.h>
ì toupper(char)/tolower(char)–Convertscharactertouppercaseorlowercaseì Example:
char c = toupper('a'); printf("%c", c); // A
31
ComputerSystemsandNetworks Spring2020
ctypeLibrary
ì isalpha(char)–Isthecharacteraletter?
ì isdigit(char)–Isthecharacteranumber0-9?
ì isspace(char)–Isthecharacterwhitespace?(spaceornewlinecharacter)
ì ispunct(char)–Isthecharacterpunctuation?(technically,avisiblecharacterthatisnotwhitespace,aletter,oranumber)
ì …andseveralothervariations
32
ComputerSystemsandNetworks Spring2020
ìFileI/O
ComputerSystemsandNetworks
33
Spring2020
FileI/OFunctions
ì fopen–opensatextfile
ì fclose–closesatextfile
ì feof–testforend-of-file
ì fgets–readsastringfromafile,stoppingatEOFornewline
ì fwrite–writesarrayofcharacterstoafile
ì fgetc–readsacharacterfromafile
ì fputc–printsacharactertoafile
ComputerSystemsandNetworks
34
Spring2020
#include <stdio.h> int main() { FILE *ptr_file; char buf[1000]; ptr_file = fopen("input.txt","r"); if (!ptr_file) return 1; while (fgets(buf,1000, ptr_file)!= NULL) printf("%s", buf); fclose(ptr_file);
return 0; }
Spring2019ComputerSystemsandNetworks
35