introduction to c++ general rules, conventions and styles · introduction to c++ general rules,...

37
Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni Dept. of Computer Science, UCSB

Upload: others

Post on 17-Jun-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

IntroductiontoC++GeneralRules,ConventionsandStyles

CS16:SolvingProblemswithComputersILecture#2

ZiadMatni

Dept.ofComputerScience,UCSB

Page 2: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

Administrative

•  ThisclassiscurrentlyFULLandthewaitlistisCLOSED– Willnotbeaddinganyoneelse Pleasedonotaskagain

•  Lab#1andsubmit.csissues

•  Homework#1andworkingonGauchoSpace

•  Reminder:Don’tleaveyourvaluablesbehindinthelab(orclass)!

4/5/18 Matni,CS16,Sp18 2

Page 3: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

LectureOutline

•  BasicRulesandConventionsofC++

•  VariablesandAssignments

•  DataTypesandExpressions

•  InputandOutput

4/5/18 Matni,CS16,Sp18 3

Page 4: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

4/5/18 Matni,CS16,Sp18 4

1-4: Programstart5: Variabledeclaration6-20: Statements21-22: Programend

cout<<“somestringoranother”; //outputstreamstatement

cin>>some_variable; //inputstreamstatement

coutandcinareobjectsdefinedinthelibraryiostream

Notetheuseofta

bbedsp

aces

Page 5: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

What’sTheDifference???

4/5/18 Matni,CS16,Sp18 5

#include<iostream>usingnamespacestd;intmain(){intn=5;while(n<10){ cout<<n; n=n+1;}

return0;}

#include<iostream>usingnamespacestd;intmain(){intn=5;while(n<10){cout<<n;n=n+1;}return0;}

Acompilerprogramcanreadeitherone!ButwhichonecanYOUreadbetter?!?!J

Page 6: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

ProgramStyle

•  Thelayoutofaprogramisdesignedmainlytomakeitreadablebyhumans

•  C++Compilersacceptalmostanypatternsoflinebreaksandindentations!–  Solayoutconventionsaretherenotforthemachine,butforthehuman–  Conventionvs.Rules–what’sthedifference??

•  Conventionshavebeenestablished,forexample:1.  Placeopeningbrace‘{‘andclosingbrace‘}’onalinebythemselves2.  Useindentedstatements(i.e.usetabbedspaces)3.  Useonlyonestatementperline

4/5/18 Matni,CS16,Sp18 6

Wewillcheckforthisconventionuseinyour

labassignments!

Page 7: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

SomeC++RulesandConventions

•  Variablesaredeclaredbeforetheyareused–  Typicallyatthebeginningofprogram

•  Statements(notalwayslines)endwithasemi-colon;

•  Usecurly-brackets{…} toencapsulategroupsofstatementsthatbelongtogether–  Parentheses(…)haveadifferentuseinC++–  Asdosquarebrackets[…]–  Theyarenotinterchangeable!

4/5/18 Matni,CS16,Sp18 7

Breakingtheserulesisconsideredasyntaxerror:yourprogramwon’tcompile!

Page 8: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

SomeC++RulesandConventions

•  Includedirectives(like#include<iostream>)arealwaysplacedinthebeginningoftheprogrambeforeanycode–  Tellsthecompilerwheretofindinformationaboutobjectsusedintheprogram

•  usingnamespacestd;–  Tellsthecompilertousenamesofobjectsiniostreamina“standard”way

•  mainfunctionsendwitha“return0;”statement–  Youshouldalwayshavethis–althoughit’saconvention,notastrictrule

4/5/18 Matni,CS16,Sp18 8

Page 9: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

Reminder:WhatareVariables

•  Avariableisasymbolicreferencetodata

•  Thevariable'snamerepresentswhatinformationitcontains

•  Theyarecalled“variables”becausethedatacanchangewhiletheoperationsonthevariableremainthesame

•  Ifvariablesareofthesametype, youcanperformoperationsonthem

94/5/18 Matni,CS16,Sp18

Page 10: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

VariablesinC++

•  InC++,variablesareplaceholdersformemorylocationsintheCPU

•  Wecanassignavaluetothem•  Wecanchangethatvaluestored•  BUTwecannoterasethememorylocationofthatparticular

variable

4/5/18 Matni,CS16,Sp18 10

Page 11: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

TypesofC++Variables:General•  Thereare3propertiestoavariable:

Variableshaveaname(identifier),atype,andavalueattachedtothem

•  Integers–  Wholenumbers–  Example:122,53,-47

•  FloatingPoint–  Numberswithdecimalpoints–  Example:122.5,53.001,-47.201

•  Boolean–  Takesononeoftwovalues:

“true”or“false”

•  Character–  Asinglealphanumeric–  Example:“c”,“H”,“%”

•  Notetheuseofquotationmarks

•  String–  Astringofcharacters–  Example:“baby”,“whatthe!@$?”

•  Notetheuseofquotationmarks

11

There are many other types of variables – you also make your own types! 4/5/18 Matni,CS16,Sp18

Page 12: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

AboutVariableNames

•  Goodvariablename:indicateswhatdataisstoredinsideit– Agoodvariablenameisa“noun”or“nounphrase”,e.g.:FirstName– Agoodfunctionnameisa“verb”or“verbphrase”,e.g.:SortNumbers()

•  Theyshouldmakesensetoanoncomputerprogrammer– Avoidgenericnames,like“var1”or“x”

•  Example: name=“BobRoberts” isnotdescriptiveenough,but candidate_name=“BobRoberts” isbetter

124/5/18 Matni,CS16,Sp18

Wewillcheckforthisconventionuseinyour

labassignments!

Page 13: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

VariableNameRulesinC++

VariablenamesinC++mustadheretocertainrules.

•  TheyMUSTstartwitheitheraletteroranunderscore(_) •  Theycannotstartwithanumber•  Therestoftheletterscanbealphanumericsorunderscores.•  Theycannotcontainspacesordotsorothersymbols

•  WhichoftheseisalegalvariablenameinC++4MyBae _StopCondition MyLittlePony_007 James.Bond

134/5/18 Matni,CS16,Sp18

Breakingtheserulesisconsideredasyntaxerror:yourprogramwon’tcompile!

Page 14: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

VariableNameCasingWhennamingvariables,functions,etc…

•  SnakeCase: Usingunderscorecharacter(‘_’)–  Example:mortgage_amount function_fun()–  AssociatedwithC,C++programmers

•  CamelCase: Usingupper-caseletterstoseparatewords–  Example: MortgageAmount FunctionFun()–  AssociatedwithJavaprogrammers

•  Forthisclass,YOUCANUSEEITHER!ButPICKONEANDBECONSISTENT!!!

4/5/18 Matni,CS16,Sp18 14

Wewillcheckforthisconventionuseinyour

labassignments!

Page 15: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

ReservedKeywords

•  UsedforspecificpurposesbyC++•  MustbeusedastheyaredefinedinC++•  CannotbeusedasidentifiersEXAMPLE:Youcannotcallavariable“int”or“else”ForalistofallC++keywords,see:http://en.cppreference.com/w/cpp/keyword

4/5/18 Matni,CS16,Sp18 15

Breakingtheserulesisconsideredasyntaxerror:yourprogramwon’tcompile!

Page 16: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

OtherStylingConventions

•  Comments:Musthavethem–  InC++,use//foronelineatatime,or/*…*/formultiplelines

•  TabbingandBraces:– Codeinsideofmain()mustbetabbedappropriately•  Evenone-linerif-statements

– Openandclosecurlybraces{…}onnewlines andalignthemwiththeblock

4/5/18 Matni,CS16,Sp18 16

Wewillcheckforthisconventionuseinyour

labassignments!

Page 17: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

ExampleofGoodStylingintmain(){

//Getuserinputonnumberofpeople//Thendetermineifthereisroomforthemintmax_capacity(100),num_people;cout<<“Enternumberofpeople:”;cin>>num_people;if(num_people>max_capacity){ cout<<“Toomanypeople!Byacountof”; cout<<num_people–max_capacity;}else{ cout<<“Ok!”;}return0;

}

Page 18: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

DeclaringVariables

•  VariablesinC++mustbedeclared___________theyareused!Declarationsyntax:Type_nameVariable_1,Variable_2,...;

Examples:doubleaverage,m_score,total_score;intid_num,height,weight,age,shoesize;intpoints;

4/5/18 Matni,CS16,Sp18 18

before

Page 19: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

Initializing/AssigningVariableValues

•  Whenyoudeclareavariable,it’snotcreatedwithanyvalueinparticular

•  Itisgoodpracticetoinitializevariablesbeforeusingthem–  Otherwisetheywillcontainwhatevervalueisinthatmemorylocation

•  Donotdeclarevariablesinsideloops!!!EXAMPLE:

intnum,doz;num=5;sum(5);doz=num+7;

4/5/18 Matni,CS16,Sp18 19

numisinitializedto5

andsoissum

dozisinitializedto(num+7)

Using=or()forassignmentofdeclaredvaluesisuptoyou!

Page 20: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

Assignmentvs.AlgebraicStatements

•  C++syntaxisNOTthesameasinAlgebraEXAMPLE:

number=number+3InC++,itmeans:– takethecurrentvalueof“number”,– add3toit,– thenreassignthatnewvaluetothevariable“number”

4/5/18 Matni,CS16,Sp18 20

C++shortcut:number+=3Alsoworkswith:

-=*=/=%=etc…

Page 21: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

VariableComparisons

•  Whenvariablesarebeingcomparedtooneanother,weusedifferentsymbols

•  aisequaltob a==b•  aisnotequaltob a!=b•  aislargerthanb a>b•  aislargerthanorequaltob a>=b•  aissmallerthatb a<b•  aissmallerthanorequaltob a<=b

Note:Theoutcomeofthesecomparisonsarealwayseithertrueorfalsei.e.BooleanBooleanvariables:false =0true ≠0(notethelower-case)

4/5/18 Matni,CS16,Sp18

Page 22: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

VariableTypesinC++1.Integers

int:Basicinteger(wholenumbers,positiveORnegative)•  Usually32or64bitswide–  So,ifit’s32bitswide,therangeis-231to+231-1Whichis:-2,147,483,648to+2,147,483,647

•  Youcanexpressevenlarger(+veand–ve)integersusing: longintandlonglongint

•  Youcanexpressonlypositiveintegers(andthusgetalonger+verange)using: unsignedint

4/5/18 Matni,CS16,Sp18 22

Page 23: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

VariableTypesinC++2.Real(rational)numbers

double:Realnumbers,positiveORnegativeTypedoublecanbewrittenintwoways:•  Simpleformmustincludeadecimalpoint–  Examples:34.1,23.0034,1.0,-89.9

•  Alternateform:FloatingPointNotation(ScientificNotation)– 3.41e1 means34.1– 3.67e17 means367000000000000000.0 (17digitsafter“3”)– 5.89e-6 means0.00000589 (6decimalplacesbefore“5”)

•  Numberleftofe(forexponent)doesnotrequireadecimalpoint•  Theexponentcannotcontainadecimalpoint

4/5/18 Matni,CS16,Sp18 23

Page 24: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

VariableTypesinC++3.Characters

char:singlecharacter•  Canbeanysinglecharacterfromthekeyboard•  Todeclareavariableoftypechar:

charletter;

•  Characterconstantsareenclosedinsinglequotescharletter='a';

4/5/18 Matni,CS16,Sp18 24

Page 25: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

VariableTypesinC++4.Strings

string:acollectionofcharacters(astringofcharacters)•  stringisaclass,differentfromtheprimitivedatatypesdiscussedsofar.

–  We’lldiscussclassesfurtherinthecourse

•  UsingC++stringsrequiresyoutoincludethe“string”module:#include<string>

•  Todeclareavariableoftypestring:stringname=“HomerSimpson”;

•  Thereare“older”typesofstringscalledC-StringsthatarestillinuseinC++–  Moreonthoselater…

4/5/18 Matni,CS16,Sp18 25

Page 26: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

Noteon‘vs“•  Singlequotesareonlyusedforchartypes•  Doublequotesareonlyusedforstringtypes

•  So,whichoftheseisokandwhichisn’t?charletter1=“a”;charletter2=‘b’;stringtown1=“Mayberry”;stringtown2=‘Xanadu’;

4/5/18 Matni,CS16,Sp18 26

Page 27: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

TypeCompatibilities

•  GeneralRule:Youcannotoperateondifferentlytypedvariables.–  Exceptwithintanddoubletypes

–  Justlikeinmostcomputerlanguages

•  So,if: then:intmy_var=2; my_var+my_char isasyntaxerror

charmy_char=‘x’;

•  Thereareruleswithoperationsbetweenintanddouble…

4/5/18 Matni,CS16,Sp18 27

Page 28: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

intßàdouble•  Variablesoftypedoubleshouldnotbeassignedtovariablesoftypeint

•  Variableoftypeint,however,cannormallybestoredinvariablesoftypedouble

EXAMPLE: doublenumero; numero=2;

•  numerowillcontain2.0000(unfixednumberofplacesafterdecimalpt)

EXAMPLE: intnumero; numero=2.789;

•  numerowillcontain2

4/5/18 Matni,CS16,Sp18 28

Page 29: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

intßàdouble

4/5/18 Matni,CS16,Sp18 29

So,whathappenswithvariablezhere?intx(9);doubley(4),z;z=x/y;cout<<z;

Thisprintsout:2.25

So,whathappenswithvariablephere?intn(4);doublem(9),p;p=m/n;cout<<p;

Thisprintsout:2.25

Ifoneorbothoperandsaredouble,theresultisdouble

So,whathappenswithvariablechere?inta(9),b(4);doublec;c=a/b;cout<<c;

Thisprintsout:2

Page 30: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

VariableTypesinC++5.Booleans

bool:abinaryvalueofeither“true”(1)or“false”(0).•  YoucanperformLOGICALoperationsonthistype:–  || LogicalOR– && LogicalAND

Also,whendoingcomparisons,theresultisaBooleantype.EXAMPLE:Whatwillthisprintout?? inta=44,b=9; boolc; c=(a==b); cout<<c;

4/5/18 Matni,CS16,Sp18 30

Ans:0

Page 31: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

ArithmeticExpressions

•  Precedencerulesforoperatorsarethesameaswhatyouusedinyouralgebraclasses– EXAMPLE:x+y*z (yismultipliedbyzfirst)

•  Useparenthesestoforcetheorderofoperations(recommended)– EXAMPLE:(x+y)*z (xandyareaddedfirst)

4/5/18 Matni,CS16,Sp18 31

Page 32: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

OperatorShorthands

•  SomeexpressionsoccursooftenthatC++containsshorthandoperatorsforthem

•  Allarithmeticoperatorscanbeusedthisway:

–  count=count+2; ---canbewrittenas---count+=2;–  bonus=bonus*2; ---canbewrittenas---bonus*=2;–  time=time/factor; ---canbewrittenas---time/=factor;–  remainder=remainder%(cnt1+cnt2);

---canbewrittenas---remainder%=(cnt1+cnt2);

4/5/18 Matni,CS16,Sp18 32

Page 33: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

ReviewofBooleanExpressions:AND,OR,NOT

ANDoperator &&•  (expression1)&&(expression2)•  Trueifbothexpressionsaretrue

ORoperator ||•  (expression1)||(expression2)•  Trueifeitherexpressionistrue

NOToperator !•  !(expression)•  False,iftheexpressionisTrue(andviceversa)

Note:nospacebetweeneach‘|’character!

Page 34: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

TruthTablesforBooleanOperations

4/5/18 Matni,CS16,Sp18 34

X Y X&&YF FF TT FT T

X Y X||YF FF TT FT T

FFFT

FTTT

X !XFT

TF

AND OR NOT

4.ANDandORarecommutative,butnotwhenmixed(so,ordermatters)X&&Y=Y&&XX&&(Y||Z)isnotthesameas(X&&Y)||Z

IMPORTANTNOTES:1.ANDandORarenotoppositesofeachother!!2.AND:ifjustoneconditionisfalse,thentheoutcomeisfalse3.OR:ifatleastoneconditionistrue,thentheoutcomeistrue

Page 35: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

PrecedenceRulesonOperationsinC++

4/5/18 Matni,CS16,Sp18 35

•  IfparenthesisareomittedfromC++expressions,thedefaultprecedenceofoperationsis:

Page 36: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

YOURTO-DOs

q  FinishLab1byMondayq  DoHW2byTuesdayq  VisitProf’sandTAs‘officehoursifyouneedhelp!

Ø  Prof.’shoursareMONDAYfrom11AMto12PM(orbyappointment!)

q  Reverseglobalwarmingq  Bonuspointsforendingworldhunger

4/6/18 Matni,CS16,Sp18 36

Page 37: Introduction to C++ General Rules, Conventions and Styles · Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2 Ziad Matni

4/6/18 Matni,CS16,Sp18 37