w02b c programming - cs.swarthmore.edubryce/cs31/f16/... · • 2 intops: intdivision truncates:...
TRANSCRIPT
CProgramming9/8/2016
Announcements
• Writtenhomework#1isdueby4pmtomorrow.
• FigureoutyourpartnerforfuturelabsbyTuesday.TherewillbeaPiazzapostwithmoreinformation.
FromTuesday:howcanwetellwhereastringends?A. Marktheendofthestringwithaspecialcharacter.
B. Associatealengthvaluewiththestring,andusethattostoreitscurrentlength.
C. Astringisalwaysthefulllengthofthearrayit’scontainedwithin(e.g.,char name[20]mustbeoflength20).
D. Allofthesecouldwork(whichisbest?).
E. Someothermechanism(suchas?).
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]
StringsinC
• CStringlibraryfunctions:#include <string.h>• Commonfunctions(strlen,strcpy,etc.)makestringseasier• LessfriendlythanPythonstrings
• Moreonstringslater,inlabs.
• Fornow,rememberaboutstrings:• Allocateenoughspacefornullterminator!• Ifyou’remodifyingacharacterarray(string),don’tforgettosetthenullterminator!
• Ifyouseecrazy,unpredictablebehaviorwithstrings,checkthesetwothings!
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)
“WhiteSpace”
• Pythoncaresabouthowyourprogramisformatted.Spacinghasmeaning.
• CcompilerdoesNOTcare.Spacingisignored.• Thisincludesspaces,tabs,newlines,etc.• Goodpractice(foryourownsanity):
• Puteachstatementonaseparateline.• Keepindentationconsistentwithinblocks.
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();}
Types
• Everythingisstoredasbits.
• Typetellsushowtointerpretthosebits.
• “Whattypeofdataisit?”• integer,floatingpoint,text,etc.
TypesinC• Allvariableshaveanexplicittype!
• You(programmer)mustdeclarevariabletypes.• Where:atthebeginningofablock,beforeuse.• How:<variabletype><variablename>;
• Examples:int humidity; floattemperature;humidity=20; temperature=32.5
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
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;
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)
BooleanvaluesinC
• Thereisno“boolean”typeinC!
• Instead,integerexpressions usedinconditionalstatementsareinterpretedastrueorfalse
• Zero(0)isfalse,anynon-zerovalueistrue
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)
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)
}
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);
}
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>;
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.
whileloopà forloop
while(condition){body;
}
for(;condition;){body;
}
forloopà whileloop
for(init; cond;update){
body;}
init;while(cond){body;update;
}
DataCollectionsinC
• Manycomplexdatatypesoutthere(CS35)
• Chasafewsimpleonesbuilt-in:• Arrays• Structures(struct)• Strings
• Oftencombinedinpractice,e.g.:• Anarrayofstructs• Astruct containingstrings
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]…
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!
structs
• Treatacollectionofvaluesasasingletype:• Cisnotanobjectorientedlanguage,noclasses• Astruct islikejustthedatapartofaclass
• Rules:1. Defineanewstruct typeoutsideofanyfunction2. Declarevariablesofthenewstruct type3. Usedotnotationtoaccessthedifferentfieldvaluesofthe
struct variable
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
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
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
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!
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
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!
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
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
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?
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);
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]);
}
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
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
Fearnot!
• Don’tworry,Idon’texpectyoutohavemasteredC.• It’saskillyou’llpickupasyougo.• We’llrevisitthesetopicswhennecessary.
• Whenindoubt:solvetheprobleminEnglish,whiteboardpictures,whateverelse!• TranslatetoClater.• Eventually,you’llstarttothinkinC.