CS50: Week 1 (Notes & Pset). A good teacher can inspire hope, ignite the imagination, and instill a love of learning. — Brad Henry. Hello, I'm Sunny.
GetunlimitedaccessOpeninappHomeNotificationsListsStoriesWriteCS50:Week1(Notes&Pset)Agoodteachercaninspirehope,ignitetheimagination,andinstillaloveoflearning.—BradHenryHello,I’mSunny.I’vestartedtotake2019CS50.SofarIloveitsomuch!Goal:1.Learneverylessonwell.Finisheveryvideoandtakenotesforfurtherreview.2.Doallproblemsetsforbothlesscomfortableandmorecomfortable.3.FinishthecoursebeforeAug30,2019(approx.4.5months,whilechallengingmachinelearning100-day-challengeatthesametime.)Thiswillbealonganddetailedarticle.ItrepresentseverythingI’velearnedduringclass,walkthrough,andshortsetc.Notesaretakenandorganized,whichreallyhelpedwhileIwasdoingproblemsets.Hopetheyhelpyoutoo.TL;DRsharesaninterestingtweetfromProgrammingWisdomatthebottomofthearticle.Inadvanced,thanksforvisitingandgoodluck!LectureHowtomakethecodework?Terminal$clanghello.c$./a.out$clang-ohellohello.c$./hello$makehello$./helloPseudocodePseudocodemeans"writeyourcodeinEnglishandthinkabouthowtheywork"Header#include#include.hmeans"header"cs50.hIfyouneedtoaskuserforsomeinput,ex.name,it'slikelythatyouneedto#includefortheget_string("What'syourname?\n");orsthlikethat.stdio.hImportantmethod:printfprintf("hello,%s\n",answer);iswithinthestdio.hfile.YoumightprettymuchneedthatheaderinalmostallthefilesIsuppose.Beginningofthefunctionintmain(void){}Binaryistheonlylanguagethatmachinesultimatelyunderstand.ProblemSetSubmitHellothisversionofMarioiffeelinglesscomfortable;thisversionofMarioiffeelingmorecomfortableCashiffeelinglesscomfortable;CreditiffeelingmorecomfortableCommandLine:ls:>Shortfor“list”,thiscommandwillgiveyouareadoutofallthefilesandfoldersintourcurrentdirectory.cd:>Shortfor“changedirectory”,thiscommandchangeyourcurrentdirectoryto,whichyouspecifyinyourworkspaceoronyouroperatingsystem.>Theshorthandnameforthecurrentdirectoryis.>Theshorthandnamefortheparentdirectoryofthecurrentdirectoryis..>Ifevercuriousaboutthenameofthecurrentdirectorythoughtheterminalpromptwilloftentellyou,youcantypepwd(presentworkingdirectory).cp:>Shortfor“copy”,thiscommandwillallowyoutocreateaduplicateofthefileyouspecifyas,whichitwillsavein>Ifyouwishyocopyentiredirectories,you’llneedtomodifythecommandsightly:cp-r>The“-r”standsforrecursive,andtellscptodivedownintothedirectoryandcopyeverythinginsideofit(includinganysubdirectoriesitmightcontain).rm:>Shortfor“remove”,thiscommandwilldeleteafterasksyoutoconfirm(y/n)youwanttodeleteit.>Youcanskiptheconfirmationbytyping:rm-f.Butuseatyourownperil!There’snoundo.>Todeleteentiredirectoriesyouneedtousethe-rflag,justaswasthecasewithcp.rm-r>Youcanalsocombinethe-rand-fflagsinto-rf.Again,careful!There’snoundo!mv:>Shortfor“move”,thiscommandwillallowyoutoeffectivelyrenamefile,movingitfromto.Ifyouwishtoexploreotherinterestingonesbeforeweseethemintheclass,readupon:chmod,ln,touch,rmdir,man,diff,sudo,clear,telnetConditionals:#NormalConditionsif(boolean-expr1){}elseif(boolean-expr2){}#InEnglishVersionif(score>=90){GetsCandy}elseif(wearUniform){GetsChocolate}Addition:Iftheconditionmeets“boolean-expr1”,itwon’tgotothe“elseif”line.InEnglish:Youhavecandies,chocolatestorewardthestudents.Whoeverscores90pointsonthequizgetsacandy.Whoeverwearsuniformtotheschoolgetsachocolates.Derickscores95pointsandwearsuniform.Hedeservesacandyandachocolate.Butwait…Astheabovesolution,Derickonlygetsacandyandisnowwhippingatthecorner😢Whatifyouneedtoconsiderthroughalltheconditions?Thebelowsolutionoccurs.#Iteratethroughthreeexpressionseverytime.if(boolean-expr1){}if(boolean-expr2){}#InEnglishVersionif(score>=90){GetsCandy}if(wearUniform){GetsChocolate}Inthiscase,computerwilliteratethrough“boolean-expr1”,“boolean-expr2”,alltwoconditions,everytime.InEnglish:Derickgetsacandyduetofirstif(score>=90)andgetsachocolateduetothesecondif(wearUniform).Great!Fairandhappyday!P.S.There’ssurelybetterexplanation.Justtryingtointerprettheconceptmyself.Switch:intx=GetInt();switch(x){case1:printf(“One!\n”);case2:printf(“Two!\n”);case3:printf(“Three!\n”);default:printf(“Sorry!\n”);}#Int’simportanttobreak.if:Usebooleanexpressiontomakedecisionsswitch:Userdsicretecasestomakedecisions?::Usetoreplaceaverysimpleif-elsetomakeyourcodelookfancyDatatypes:Int>TheIntdatatypeisusedforvariablesthatwillstoreintegers.>Integersalwaystakeup4bytesofmemory(32bits).Thismeanstherangeofvaluestheycanstoreisnecessarilylimitedto32bitsworthofinformation.UnsignedInt>UnsignedIntisaqualifierthatcanbeappliedtocertaintypes(includingint),whicheffectivelydoublesthepositiverangeofvariablesofthattype,atthecaseofdisallowinganynegativevalues.Chars>TheChardatatypeisusedforvariablesthatwillstoresinglecharacters.>Charactersalwaystakeup1byteofmemory(8bits).Thismeanstherangeofvaluestheycanstoreisnecessarilylimitedto8bitsworthofinformation.>ThankstoASCII,we’vedevelopedamappingofcharacterslikeA,B,C,etc…tonumericvaluesinthepositivesideoftherang.Float>TheFloatdatatypeisusedforvariablesthatwillstorefloating-pointvalues,alsoknownasrealnumbers.>Floatingpointsvaluealwaystakeup4bytesofmemory(32bits).>It’salittlecomplicatedtodescribetherangeofafloatbutsufficeittosaywith32bitsofprecision,someofwhichmightbeusedforanintegerpart,wearelimitedinhowprecisewecanbe.Void>Isatype,butnotadatatype.>Functionscanhaveavoidreturntype,whichjustmeanstheydont’returnavalue.>Theparameterlistofaafunctioncanalsobevoid.Isimplymeansthefunctiontakesparameters.>Fornow,thinkofvoidmoreasplaceholderfor“nothing”.It’smorecomplexthanthat,butthisshouldsufficeforthebetterpartofthecourse.BelowdatatypesneededtoincludeBool>ThebooldatatypeisusedforvariablesthatwillstoreaBooleanvalue.Moreprecisely,theyarecapableonlyofstoringoneoftwovalues:trueandfalse.String>Thestringdatatypeisusedforvariablesthatwillstoreaseriesofcharacters,whichprogrammerstypicallycallastring.>Stringsincludethingssuchaswords,sentences,paragraphs,andthelike.Howtocreateandusethevariables?Creatingavariable>Tobringavariableintoexistence,youneedsimplyspecifythedatatypeofthevariableandgiveitaname.intnumber;charletter;>Ifyouwishtocreatemultiplevariablesofthesametype,youspecifythetypenameonce,andthenlistasmanyvariablesofthattypeasyouwant.intheight,width;floatsqrt2,sqrt3,pi;>Ingeneral,it’sgoodpracticetoonlydeclarevariableswhenyouneedthem.Usingavariable>Aavariablehasbeendeclared,it’snolongernecessarytospecifythatvariable’stype.(Infact,doingsohassomeunintendedconsequences!)intnumber;//declarationnumber=17;//assignmentcharletter;//declarationletter=‘h’;//assignment>Ifyouaresimultaneouslydeclaringandsettingthevalueofavariable(sometimescalledinitializing),youcanconsolidatethistoonestep.intnumber=17;//initializationcharletter=‘H’//initializationLoops:BasicUsagewhile(true){}>Thisiswhatwecallaninfiniteloop.Theselinesofcodebetweenthecurlybraceswillexecuterepeatedlyfromtoptobottom,untilandunlesswebreakoutofit(aswithabreak;statement)orotherwisekillourprogram.ThreetypesofLoops:1.whileloopwhile(boolean-expr){}>iftheboolean-exprevaluatestotrue,alllinesofcodebetweenthecurlybraceswillexecuterepeatedly,inorderfromtop-to-bottom,untilboolean-exprevaluatestofalse.>Somewhatconfusingly,thebehavioroftheScratchblockisreversed,butitistheclosestanalog.2.dowhiledo{}while(boolean-expr);>Thisloopwillexecutealllinesofcodebetweenthecurlybracesonce,andiftheboolean-exprevaluatestotrue,willgobackandrepeatthatprocessuntilboolean-exprevaluatestofalse.3.forloopfor(inti=0;i<10;i++){}>Syntacticallyunattractive,butforloopsareusedtorepeatthebodyofaloopaspecifiednumberoftimes,inthisexample10.>Theprecessundertakeninaforloopis:>Thecountervariable(s)(here,i)isset>Thebooleanexpressionischecked.>Ifitevaluatestotrue,thebodyoftheloopexecutes.>Ifitevaluatestofalse,thebodyoftheloopdoesnotexecute>Thecountervariableisincremented,andthentheBooleanexpressionischeckedagain,etc.Furtherexplanationindetailforforloop:for(start;expr;increment){}>Theprocessundertakeninaforloopis:>Thestatement(s)instartareexecuted>Theexprischecked.>Ifitevaluatestotrue,thebodyoftheloopexecutes.>Ifitevaluatestofalse,thebodyoftheloopdoesnotexecute>Thestatement(s)inincrementareexecuted,andthetheexprischeckedagain,etc.Conclusion:while>Usewhenyouwantalooptorepeatanunknownnumberoftimes,andpossiblynotatall.ex.gamedo-while>Usewhenyouwanttolooptorepeatanunknownnumberoftimes,butatleastonce.ex.promptinginputfor>Usewhenyouwantalooptorepeatadiscretenumberoftimes,thoughyoumaynotknowthenumberatthemomenttheprogramiscompiled.Operators:Arithmeticoperators>InCwecanadd(+),subtract(-),multiply(*)anddivide(/)numbers,asexpected.intx=y+1;x=x*5;>Wealsohavethemodulusoperator,(%)whichgivesyoutheremainderwhenthenumberontheleftoftheoperatorisdividedbythenumberontheright.intm=13%4;//misnow1>Calsoprovidesashorthandwaytoapplyandarithmeticoperatorofasinglevariablex=x*5;x*=5;>Thistrickworkswithallfivebasicarithmeticoperators.Cprovidesafurthershorthandforincrementingordecrementingavariableby1:x++;x--:Booleanexpressions>BooleanexpressionsareusedinCforcomparingvalues.>AllBooleanexpressionsinCevaluatetooneoftwopossiblevalues-trueorfalse.>WecanusetheresultofevaluatingaBooleanexpressioninotherprogrammingconstructssuchasdecidingwhichbranchinaconditionaltotake,ordeterminingwhetheraloopshouldcontinuetorun.>SometimeswhenworkingwithBooleanexpressionswewillusevariablesoftypebool,butwedon'thaveto.>InC,everynonzerovalueisequivalenttotrueandzeroisfalse.>TwomaintypesofBooleanexpressions:logicaloperatorsandrelationaloperators.logicaloperatorsand>LogicalAND(&&)ostrueifandonlyifbothoperandsaretrue,otherwisefalse.or>LogicalOR(||)istrueifandonlyifatleastoneoperandistrue,otherfalse.not>LogicalNOT(!)invertsthevalueofitsoperand.relationaloperators>Thesesbehaveasyouwouldexpectthem,andappearsyntacticallysimilartohowyoumayrecallthemfromelementaryarithmetic.Lessthan(xy)Greaterthanorequalto(x>=y)>Calsocantesttwovariablesforequalityandinequality.Equality(x==y)Inequality(x!=y)>Becareful!It’sacommonmistaketousetheassignmentoperator(=)whenyouintendtousetheequalityoperator(==).TL;DRHavefunandenjoycoding!Ifyouhaveanyquestion,feelfreetoleaveacomment.Ifyouthinkthisarticleishelpful,pleasegivemeaclapormultipleclaps:]MorefromSunny,LeeFollowPassionateSoftwareDeveloper|Swift&React.js👩💻Lovepodcastsoraudiobooks?Learnonthegowithournewapp.TryKnowableRecommendedfromMediumJeromeRanSwitchFileDownloadertoOkDownloadSeamlesslyRobertoSalazarinAnalyticsVidhyaOperationsResearchwithR — DietProblemAntonioDiMarianoHowaKafkaconsumercanstartreadingmessagesfromadifferentoffsetandgetbacktothestart.TacoTacoWrapUp:VenuesMonthDaneMackierinFlutterCommunityFlutterFoundation — GoingfromSetStatetoArchitecture(Asyncbehaviour)joerussoDesigningforthePlatform—APIdesignArunEHowdowedeployJavaOnAwsEc2AdamRossNelsoninTowardsDataScienceGoingFromStatatoPandasAboutHelpTermsPrivacyGettheMediumappGetstartedSunny,Lee371FollowersPassionateSoftwareDeveloper|Swift&React.js👩💻FollowMorefromMediumShuvangkarDasCustomdatastructuredesignforArduinoandMicrocontrollerproject|Part1AshleyTaylorTheStudyofForeignLanguage:Part1TechyRushabhNested-List|HackerRankSolutionsLiamWiseLearningBackendDevelopementHelpStatusWritersBlogCareersPrivacyTermsAboutKnowable