c programming 1 - university of the pacific · lab schedule activities ì this week ì intro to...

35
ì Computer Systems and Networks ECPE 170 – Jeff Shafer – University of the Pacific C Programming 1

Upload: others

Post on 08-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

ìComputerSystemsandNetworksECPE170–JeffShafer–UniversityofthePacific

CProgramming1

Page 2: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

LabSchedule

Activitiesì  ThisWeek

ì  IntrotoBuildToolsandMakefiles

ì  IntrotoC1ì  Lab3–BuildTools

ì  NextWeekì  IntrotoC2ì  Lab4–CProgramming

Project

Deadlinesì  Lab3–Feb4th2020

by5am

ì  Lab4–Feb18th2020by5am

Spring2020ComputerSystemsandNetworks

2

Page 3: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

PersonoftheDay:DennisRitchie

ì  CreatorofCprogramminglanguage

ì  Co-creatorofUnix(withKenThompson,BrianKernighan,andothersatBellLabs)

ì  WinnerofACMTuringAward

ì  9/9/1941—10/12/2011

ComputerSystemsandNetworks

3

Spring2020

Page 4: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 5: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

Spring2019ComputerSystemsandNetworks

5

DennisRitchieandKenThompsonuseateletypewritertorunaprogramonaUNIX-basedcomputersystemtheyco-foundedatBellLabsinNewJersey.Theirdevelopmentworkmorethan40yearsagofacilitatedtherealizationoftheInternet.

Page 6: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

ìCProgramming

ComputerSystemsandNetworks

6

Spring2020

Page 7: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

C++FeaturesNotinC

ì  Noclasses/object-orientedprogramming

ì  Nonew/delete

ì  Nostreamoperators(<<and>>),cin,cout,…

ì  NoC++StandardLibraries(e.g.iostream)

ì  boolkeywordì  AddedinC99standard

ì  Declarevariablesanywhereinsidefunctionì  AddedinC99standard

ComputerSystemsandNetworks

7

Spring2020

Page 8: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

ìConsoleI/O

ComputerSystemsandNetworks

8

Spring2020

Page 9: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 10: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 11: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

Inputwithscanf()

ì  Inputfromconsole

ì  scanf("%d %c", &myint, &mychar)

ì  Requirestheaddressofthedestinationvariableì  Usethe&operatortoobtainaddress

ì  Caveat:Arraynamesarealreadythe“addressof”!ì  char myarray[8];

scanf("%s", myarray)

ComputerSystemsandNetworks

11

No&neededhere!

Spring2020

Page 12: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

Documentation

ì  Man(ual)pagesexistforcommonprogrammingfunctionstoo

ComputerSystemsandNetworks

12

$ man printf

$ man scanf

Spring2020

Page 13: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

ìArrays

ComputerSystemsandNetworks

13

Spring2020

Page 14: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 15: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 16: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 17: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

ìPointers

ComputerSystemsandNetworks

17

Spring2020

Page 18: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 19: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

Pointers

ì  &is‘addressofvariable’operatorì  Example:&ivar translatesto

“addressofvariableivar”

ì  *is‘valueataddressstoredinpointer’operatorì  Example:*iptr translatesto

“valueataddressstoredinpointeriptr”

ComputerSystemsandNetworks

19

Spring2020

Page 20: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

Pointers

ì  Canhavemultiplelevelsof“indirection”

ì  int *myptr ì  Apointertoaninteger

ì  int **myptr ì  Apointertoapointertoaninteger

ì  int ***myptr ì  Apointertoapointertoapointertoaninteger

ComputerSystemsandNetworks

20

Spring2020

Page 21: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 22: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 23: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

Problem4–MorePointers

ComputerSystemsandNetworks

23

P4

CollaboratewithapartnerandanswerQuestion4-5

Spring2020

Page 24: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

ìC-Strings(ArraysofCharacters)

24

ComputerSystemsandNetworks Spring2020

Page 25: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

CStrings

ì  Thereisnosuchthingasa“string”inC!

ì  Whatdoyouget?Anarrayofcharactersì  Terminatedbythenullcharacter'\0'

ì  Mustmanipulateelementbyelement…ì  Notenoughroominthearray?Needabiggerarray

ComputerSystemsandNetworks

25

Spring2020

Page 26: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 27: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 28: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

HelpfulLibraryforCharacterArrays

ì  #include <string.h>

ì  Usefulfunctionsì  strcpy-Stringcopyì  strcmp-Stringcompareì  strlen-Stringlengthì  strcat-Stringconcatenate

28

ComputerSystemsandNetworks Spring2020

Page 29: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 30: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

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

Page 31: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

ctypeLibrary

ì  Usefulforcharactermanipulation

ì  #include <ctype.h>

ì  toupper(char)/tolower(char)–Convertscharactertouppercaseorlowercaseì  Example:

char c = toupper('a'); printf("%c", c); // A

31

ComputerSystemsandNetworks Spring2020

Page 32: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

ctypeLibrary

ì  isalpha(char)–Isthecharacteraletter?

ì  isdigit(char)–Isthecharacteranumber0-9?

ì  isspace(char)–Isthecharacterwhitespace?(spaceornewlinecharacter)

ì  ispunct(char)–Isthecharacterpunctuation?(technically,avisiblecharacterthatisnotwhitespace,aletter,oranumber)

ì  …andseveralothervariations

32

ComputerSystemsandNetworks Spring2020

Page 33: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

ìFileI/O

ComputerSystemsandNetworks

33

Spring2020

Page 34: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

FileI/OFunctions

ì  fopen–opensatextfile

ì  fclose–closesatextfile

ì  feof–testforend-of-file

ì  fgets–readsastringfromafile,stoppingatEOFornewline

ì  fwrite–writesarrayofcharacterstoafile

ì  fgetc–readsacharacterfromafile

ì  fputc–printsacharactertoafile

ComputerSystemsandNetworks

34

Spring2020

Page 35: C Programming 1 - University of the Pacific · Lab Schedule Activities ì This Week ì Intro to Build Tools and Makefiles ì Intro to C 1 ì Lab 3 – Build Tools ì Next Week ì

#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