w02b c programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates:...

38
C Programming 9/8/2016

Upload: others

Post on 19-Nov-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

CProgramming9/8/2016

Page 2: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Announcements

• Writtenhomework#1isdueby4pmtomorrow.

• FigureoutyourpartnerforfuturelabsbyTuesday.TherewillbeaPiazzapostwithmoreinformation.

Page 3: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

FromTuesday:howcanwetellwhereastringends?A. Marktheendofthestringwithaspecialcharacter.

B. Associatealengthvaluewiththestring,andusethattostoreitscurrentlength.

C. Astringisalwaysthefulllengthofthearrayit’scontainedwithin(e.g.,char name[20]mustbeoflength20).

D. Allofthesecouldwork(whichisbest?).

E. Someothermechanism(suchas?).

Page 4: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

CharactersandStrings

• Acharacter(typechar)isnumericalvaluethatholdsoneletter.• Astringisamemoryblockcontainingcharacters,oneafteranother,withanullterminator(numerical0)attheend.• Examples:

charmessage[20]=“hello”;

h e l l o[0] [1] [2] [3] [4]

\0[5]

…[6] [7] [18][19]

Page 5: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

StringsinC

• CStringlibraryfunctions:#include <string.h>• Commonfunctions(strlen,strcpy,etc.)makestringseasier• LessfriendlythanPythonstrings

• Moreonstringslater,inlabs.

• Fornow,rememberaboutstrings:• Allocateenoughspacefornullterminator!• Ifyou’remodifyingacharacterarray(string),don’tforgettosetthenullterminator!

• Ifyouseecrazy,unpredictablebehaviorwithstrings,checkthesetwothings!

Page 6: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Pythonvs.C:HelloWorldPython C

# hello worldimport math

def main():print “hello world”

main()

// hello world #include <stdio.h>

int main( ) {printf(“hello world\n”);return 0;

}

#:singlelinecomment //:singlelinecomment

importlibname:includePython libraries #include<libname>: includeClibraries

Blocks:indentation Blocks:{} (indentationforreadability)

print: statementtoprintoutstring printf:functiontoprintoutformat string

statement:eachonseparateline statement:eachendswith;

def main()::themainfunctiondefinition int main( ):themainfunctiondefinition(int specifiesthereturntype ofmain)

Page 7: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

“WhiteSpace”

• Pythoncaresabouthowyourprogramisformatted.Spacinghasmeaning.

• CcompilerdoesNOTcare.Spacingisignored.• Thisincludesspaces,tabs,newlines,etc.• Goodpractice(foryourownsanity):

• Puteachstatementonaseparateline.• Keepindentationconsistentwithinblocks.

Page 8: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Thesearethesameprogram…

#include <stdio.h>

int main() {

int number = 7;

if (number>10){

do_this();

} else {

do_that();

}

}

#include <stdio.h>

int main(){intnumber=7; if (number>10) do_this(); else do_that();}

Page 9: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Types

• Everythingisstoredasbits.

• Typetellsushowtointerpretthosebits.

• “Whattypeofdataisit?”• integer,floatingpoint,text,etc.

Page 10: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

TypesinC• Allvariableshaveanexplicittype!

• You(programmer)mustdeclarevariabletypes.• Where:atthebeginningofablock,beforeuse.• How:<variabletype><variablename>;

• Examples:int humidity; floattemperature;humidity=20; temperature=32.5

Page 11: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Whatvalueswillweseeforx,y,andz?/* a multiline comment:

anything between slash-star and star-slash */

#include <stdio.h> // C’s standard I/O library (for printf)

int main() {// first: declare main’s local variables int x, y;float z;

// followed by: main function statementsx = 6; y = (x + 3)/2;z = x; z = (z + 3)/2;

printf(…) // Print x, y, z}

X Y Z

A 4 4 4

B 6 4 4

C 6 4.5 4

D 6 4 4.5

E 6 4.5 4.5

Clickerchoices

Page 12: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Operators:needtothinkabouttype• Arithmetic:+,-,*,/,% (numerictypeoperands)

/:operation&resulttypedependsonoperandtypes:• 2int ops: int divisiontruncates: 3/2is1• 1or2floatordouble:floatordoubledivision:3.0/2is1.5

%:modoperator:(onlyint orunsignedtypes)• Givesyouthe(integer)remainderofdivision.

13%2 is127%3 is0

Shorthandoperators:• var op= expr;(var =var opexpr):

x+=4isequivalenttox=x+4

• var++; var--;(var =var+1;var =var-1):x++ issameasx=x+1 x-- issameasx=x-1;

Page 13: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Operators:needtothinkabouttype

• Relational (operandsanytype,resultint “boolean”):• <,<=,>,>=,==,!=

• 6!=(4+2) is0(false)• 6>3 somenon-zerovalue(wedon’tcarewhichone)(true)

• Logical (operandsint “boolean”,resultint “boolean”):• !(not):!6is0 (false)• &&(and):8&&0is0 (false)• ||(or):8||0isnon-zero(true)

Page 14: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

BooleanvaluesinC

• Thereisno“boolean”typeinC!

• Instead,integerexpressions usedinconditionalstatementsareinterpretedastrueorfalse

• Zero(0)isfalse,anynon-zerovalueistrue

Page 15: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

BooleanvaluesinC• Zero(0)isfalse,anynon-zerovalueistrue• Logical(operandsint “boolean”->resultint “boolean”):

• !(not): invertstruthvalue• &&(and): trueifbothoperandsaretrue• ||(or): trueifeitheroperandistrue

#1 #2

A True True

B True False

C False True

D False False

ClickerchoicesDothefollowingstatementsevaluatetoTrueorFalse?

#1:(!10) || (5 > 2)

#2:(-1) && ((!5) > -1)

Page 16: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

ConditionalStatements

VerysimilartoPython,justremember{}areblocks

Basic ifstatement: With optionalelse:if(<boolean expr>) {if-true-body

}

if(<boolean expr) {if-true-body

} else {else body(expr-false)

}

Chainingif-elseif Withoptionalelse:if(<boolean expr1>) {if-expr1-true-body

} else if (<bool expr2>){else-if-expr2-true-body(expr1 false)

}... } else if (<bool exprN>){else-if-exprN-true-body

}

if(<boolean expr1>) {if-expr1-true-body

} else if (<bool expr2>){else-if-expr2-true-body

}...} else if (<bool exprN>){else-if-exprN-true-body

} else {else body(all exprX’s false)

}

Page 17: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Forloopsfor (<init>; <cond>; <update>) {

for-loop-body-statements}<next stmt after loop>;

1. Evaluate<init>onetime,whenfirsteval for statement2. Evaluate<cond>,ifitisfalse,dropoutoftheloop(<nextstmt after>)3. Evaluatethestatementsintheforloopbody4. Evaluate<update>5. Goto step(2)

for(i=1; i <= 10; i++) { // example for loopprintf(“%d\n”, i*i);

}

Page 18: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

WhileLoops• BasicallyidenticaltoPythonwhileloops:while (<boolean expr>) {

while-expr-true-body

}

x = 20;while (x < 100) {y = y + x;x += 4; // x = x + 4;

}<next stmt after loop>;

x = 20;while(1) { // while truey = y + x;x += 4;if(x >= 100) {

break; // break out of loop }

}<next stmt after loop>;

Page 19: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Whatcan/can’twhileloopsandforloopsdoinC?a) AnythingyoucancomputewithaCwhile

loop(andmore)canbecomputedwithaCfor loop.

b) AnythingyoucancomputewithaCforloop(andmore)canbecomputedwithaCwhile loop.

c) C’swhile loopsandfor loopscanperformcompletelydisjointsetsofcomputations.

d) C’swhile loopsandfor loopscanperformpartiallyoverlappingsetsofcomputations.

e) C’swhile loopsandfor loopscanperformexactlythesamecomputations.

Page 20: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

whileloopà forloop

while(condition){body;

}

for(;condition;){body;

}

forloopà whileloop

for(init; cond;update){

body;}

init;while(cond){body;update;

}

Page 21: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

DataCollectionsinC

• Manycomplexdatatypesoutthere(CS35)

• Chasafewsimpleonesbuilt-in:• Arrays• Structures(struct)• Strings

• Oftencombinedinpractice,e.g.:• Anarrayofstructs• Astruct containingstrings

Page 22: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Arrays• C’ssupportforlistsofvalues• Arraybucketsstoreasingletypeofvalue• Needtospecifythefullcapacity(num buckets)whenyoudeclareanarrayvariable

<type> <var_name>[<num buckets>];int arr[20]; // declare array of 20 intsfloat rates[40]; // an array of 40 floats

Bucketsoftenaccessedw/loop:for(i=0; i < 20; i++) {

arr[i] = i;rates[i] = (arr[i]*1.387)/4;

}arr

[0] [1] [2] [19]

Arraybucketindices.

Get/Setvalueusingbrackets[]toindexintoarray.

rates

[0] [1] [2] [39]…

Page 23: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

ArrayCharacteristicsint temps[30];

• Nameofarrayvariablealone(temps) evaluatestothethebeginningofthememorychunk(baseaddress)

(rememberthisforlater)• Indicesstartat0!Why?

• Indexnumberisanoffsetfrombeginningofarray• temps[0]:int atoffset0frombaseaddr ofarray

• CdoesNOT doboundschecking.• Askfortemps[35]?

• Python:error• C:okey dokey

“temps”:locationofbucket[0]inmemory

[0] [1] [2] [3] [4] [28][29]…

Arraybucketindices.

?[35]

temps

Demo!

Page 24: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

structs

• Treatacollectionofvaluesasasingletype:• Cisnotanobjectorientedlanguage,noclasses• Astruct islikejustthedatapartofaclass

• Rules:1. Defineanewstruct typeoutsideofanyfunction2. Declarevariablesofthenewstruct type3. Usedotnotationtoaccessthedifferentfieldvaluesofthe

struct variable

Page 25: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

NeedtoThinkaboutType!• Supposewewanttorepresentastudent type.

struct student {

char name[20];

int grad_year;

float gpa;

};

struct student jo;

Whattypeis:jojo.gpa

jo.name[3]

jo.name

fieldnames storedvalues(memoryspace)jo: name: …

grad_year:

gpa:

jo: struct student

jo.gpa: float

jo.name[3]: char

jo.name: arrayofchar

Page 26: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Struct Example// 1. define a new struct type (outside a function):

struct student { // struct <name> {

char name[20]; // <type> <field name>;

int grad_year;

float gpa;

};

// 2. Declare var of new type:

int main() {

struct student jo; // jo’s typeis“struct student”

// 3. Use dot notation to access field values:

strcpy(jo.name, “Jo Schmoe”); // Set name with strcpy()

jo.grad_year = 2016;

jo.gpa = 3.1;

printf(“Name: %s, year: %d, GPA: %f”, jo.name, jo.grad_year, jo.gpa);

}

fieldnames: storedvalues(memoryspace)

jo: name: ‘J’ ‘o’ ‘ ’ ‘S’ ‘c’ ‘h’ …

grad_year:

2017

gpa: 3.1

Page 27: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Functions:examplefromlab2void open_file_and_check(char *filename);

int main (int argc, char *argv[]) {//...

}

void open_file_and_check(char *filename){int ret; ret = open_file(filenameif(ret == -1) {

printf("bad error: can't open %s\n",filename);

exit(1);}

}

Declaration

Definition

Page 28: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Functions:SpecifyingTypes• Needtospecifythereturntypeofthefunction,andthetypeofeachparameter:

<return type> <func name> ( <param list> ) {// declare local variables first// then function statements

return <expression>;}

// my_function takes 2 int values and returns an intint my_function(int x, int y) { int result;result = x;if(y > x) {result = y+5;

}return result*2;

}

Compilerwillyellatyouifyoutrytopassthewrongtype!

Page 29: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

FunctionArguments

• Argumentsarepassedbyvalue• Thefunctiongetsaseparatecopy ofthepassedvariable

int func(int a, int b) {

a = a + 5;return a - b;

}

int main() {

int x, y; // declare two integersx = 4;

y = 7;y = func(x, y);printf(“%d, %d”, x, y);

}

Stack

main:x:

y:

func:a:

b:

4

7

4

7

4

7

Page 30: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

FunctionArguments

• Argumentsarepassedbyvalue• Thefunctiongetsaseparatecopy ofthepassedvariable

int func(int a, int b) {

a = a + 5;return a - b;

}

int main() {

int x, y; // declare two integersx = 4;

y = 7;y = func(x, y);printf(“%d, %d”, x, y);

}

Stack

main:x:

y:

func:a:

b:

4

7

9

7

Note:Thisdoesn’tchange!

Page 31: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

FunctionArguments

• Argumentsarepassedbyvalue• Thefunctiongetsaseparatecopy ofthepassedvariable

int func(int a, int b) {

a = a + 5;return a - b;

}

int main() {

int x, y; // declare two integersx = 4;

y = 7;y = func(x, y);printf(“%d, %d”, x, y);

}

Stack

main:x:

y:

4

2

Output:4,2

Page 32: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

TheStackandPassbyValue

• Localvariablesandparameters:• storagelocationsallocatedonthestack• storevaluesofdefinedtypeonthestack

// function prototype:// declares functionint func(int a, int b);

int main() {int x, y;x = 4; y = 7;y = func(x, y);printf(“%d %d\n”, x, y);

}

// function definition:// implementation of funcint func(int a, int b) {a = a + 5;return a - b;

}

func:a: 4

b: 7

result:

main:x: 4

y: 7

STACK

ArgumentsarePassedByValue:parametergetsacopyofitsargument’svalue

ModifyingaparameterCANNOTchangeitsargument’svalue

Page 33: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

int func(int a, int y, int arr[]) {

y = 1;

arr[a] = 0;

arr[y] = 8;

return y;

}

int main() {

int x;

int values[2];

x = 0;

values[0] = 5;

values[1] = 10;

x = func(x, x, values);

printf(“%d, %d, %d”,

x, values[0], values[1]);

}

A. 0,5,8B. 0,5,10C. 1,0,8D. 1,5,8E. 1,5,10

Hint:Whatdoesthenameofanarraymeantothecompiler?

Whatwillthisprint?

Page 34: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

ArraysandFunctions• ArrayParameters:

• Specifythetype,butnottheexactsizeofthearray• makesthefunctionmoregeneric--worksforanysizearray

• Needtopassthesizeofthearray(notnec.capacity)• thenumberofbucketsinusetothefunction

• FunctionCalltakesthenameofthearray(baseaddress)

void printArray(int a[], int n) {int I;for(i=0; I < n; i++) {

printf(“a[%d] = %d\n”, i, a[i]);}

}int main() {

int array[20], list[40];...printArray(array, 20);printArray(list, 40);

Page 35: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

PassingArraysisPassbyValue

• Aparameteralwaysgetsthevalueofitsargument• Thevalueofanarrayargumentisitsbaseaddress

Arrayname==memorylocation(theaddressof)its0th bucket• ArrayparameterREFERSTOsamearraystorageasitsargument

è changingabucketvalueinafunctionchangesthecorrespondingbucketvalueinitsargument

void test(int a[], int n) {a[3] = 8;n = 3;

}int main() {

int i, array[5],;for(i=0; i<5; i++) {

array[i] = i;}test(array, 5);printf(“%d”, array[3]);

}

Page 36: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

PassbyValue:ArrayArgumentsvoid test(int a[], int n) {

a[3] = 8;n = 3;

}

int main() {int array[5], n = 5;for(i=0; i<n; i++) {

array[i] = i;}test(array, n);printf(“%d”, array[3]);

}

The values of the arguments are passed:n: 5array: memory location (the address)

of the start of array

test:n: 5

a: mem addressof array

result:

main:n: 5

STACK

array: 0 1 2 3 4

Page 37: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

PassbyValue:ArrayArgumentsvoid test(int a[], int n){

a[3] = 8;n = 3;

}int main() {

int array[5], n = 5;for(i=0; i<n; i++) {

array[i] = i;}test(array, n);

}

Changing value stored in bucket of an array parameter (a[3] = 8), changes value stored in corr. argument (array[3]):a and array refer to the same memory location

test:n: 3

a: mem addressof array

result:

main:n: 5

STACK

array: 0 1 2 8 4

Page 38: w02b C programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates: 3/2 is 1 • 1 or 2 float or double: float or double division: 3.0/2 is 1.5 %: mod

Fearnot!

• Don’tworry,Idon’texpectyoutohavemasteredC.• It’saskillyou’llpickupasyougo.• We’llrevisitthesetopicswhennecessary.

• Whenindoubt:solvetheprobleminEnglish,whiteboardpictures,whateverelse!• TranslatetoClater.• Eventually,you’llstarttothinkinC.