Computer Finals Reviewer

Embed Size (px)

Citation preview

  • 8/18/2019 Computer Finals Reviewer

    1/20

    Memory Location in C+

    +

    Internal Memory

    • Inside every computer is a component

    called internal memory.

    •Computer’s internal memory iscomposed of memory locations, eachwith a unique numeric address.

    • Memory location is similar to collection

    of storage bins.

    • Each address can store one item at a

    time.

    Memory Location

    • Address or memory location can

    contain numbers, tet, or programinstructions

    •  !o use a memory location,

    programmer must reserve theaddress, called declaring.

    • "eclaring a memory location is done

    with an instruction that assigns a datatype, identi#er and initial value$optional%.

    • Data Type & indicates what type of

    information the address will store$e.g., numeric or tetual%.

    • Identifer & allows the programmer to

    refer to the memory locationelsewhere in the program.

    & 'ames made up by the programmer.

    Types o Identifer

    • Variables - are memory locationswhose values can change duringruntime $when the program isrunning%. Most memory locations arevariables.

    • Constants & are memory locations

    whose content cannot be changedduring program eecution. (ftennamed in uppercase letters.

    • Eample) *I $constant%, radius

    $variable%

    Rules In Naming Identifers!ariables"

    • 'ame must begin with a letter and

    contain only letters, numbers, andthe underscore character

    • 'o punctuation mar+s, spaces, or

    other special characters $such as or -% are allowed

    • Cannot be a +eyword $word that has

    special meaning in C%

    • 'ames are case sensitive

    Eample) discount is di/erentfrom "I0C(1'! and from

    "iscount

    Valid or In!alid Variables

    • total0ales

    •  !otal20al3s

    •  !otal 0ales

    • total.0ales

    • 4th5tr0ales

    • total0ale

    •  !6ta7sales

    C++ #ey$ords

    • 8eywords are prede#ned reserved

    words or reserved identi#ers that havespecial meanings.

    •  !hey cannot be used as identi#ers in

    your program

    auto

    const

    double

    9oat

    int

    short

  • 8/18/2019 Computer Finals Reviewer

    2/20

    struct

    endl

    Data Types

    • Memory locations come in di/erent

    types and si:es

    • A memory location will only accept an

    item that matches its data type.

    • "ata type of a memory location is

    determined by the programmer whendeclaring the location.

    %undamental Data Types in C++

     short

     int

     9oat

     double

     bool

     char

      string user-defned data

    type"

    • bool & stores ;oolean values $true or <

    and false or 6%

    • s&ort and int & store integers

    $numbers without a decimal place%

    o "i/erences are range of values

    and memory used $int has thegreater of both%

    • 'oat and double - store real numbers

    $numbers with a decimal place%

    o "i/erences are range of values,

    precision, and memory used$double has the greater ofeach%

    • c&ar & stores characters $letter,

    symbol, or number that will not beused in a calculation%

    o (nly one character stored at a

    time

    • string - is a user&de#ned data type,

    can store :ero $blan+% or morecharacters

    Declaring Memory Location

    • =hen declaring a memory location a

    data type and an identi#er $variable orconstant% must be provided

    • 0ynta for declaring a variable in C

    o DataType Identifer (

    o )*amples

    string age>

    9oat length>

    Int width>

    string lastname>

    ,ssigning %loating-point Valuesto Integer Variables

    • If a 9oating&point value is assigned to

    an integer variable

    o  !he fractional part will be

    truncated $i.e., ?chopped o/@and discarded%

    o  !he value is not rounded

    int rainall ./00(

    cout 11 rainall(

    22 Displays .

    3tring Literals

    • Can store a series of characters in

    consecutive memory locations.

  • 8/18/2019 Computer Finals Reviewer

    3/20

    45ello4

    o Enclosed in a double quotation 4 4 

    • Can de#ne string data type in

    programs string name(

    C&ar !s string literal constants

    • Character literal constants initiali:e

    c&ar data types

    o Consist of one character in

    single quotation mar+s

    • 0tring literal constants initiali:e string

    data types

    o ero or more characters

    enclosed in double quotation

    mar+s

    o Empty string $? @% is a valid

    string literal constant.

    Reading in a 3tring 3tatement

    & Beads in a string with no blan+s

    string name( 

    cin 66 name( 

    & Beads in a string that may contain blan+s

    string name(

    getlinecin7 name"( 

    3ystem 8cls9" (

    system$ % is used to run the "(0commands from the C

    • cls is the clear screen command

    Ma:ing Decisions 2

    Conditional 3tatements

    %our ;rogram 3tructures

    • 0equence

    • "ecision

    • Bepetition

    • Case

  • 8/18/2019 Computer Finals Reviewer

    4/20

    • If expression" is true, then thestatement(s) in the body are eecuted.

    • If expression" is alse, then thestatement(s) are s+ipped.

    • Eample if 0tatements

    i score 6 >?"  cout 11 4@ou ;assedAA4 11endl(

    i number B"

      cout11 4It is number BAA4 11endl(

    i 3tatement Notes

    • "o not place > after expression"

     !he parentheses surrounding theevaluated epression in the ifstatement are essential

    • ? is alse( any other value is true

    • Any value other than 6, even anegative value, is considered to betrue.

    •  !hus, the statement if $&F% coutGG?(8@> would display ?(8@.

    • Most frequently, you create an ifstatement’s ;oolean epression usingone of the si relational operators)

    T&e i2else 3tatementT&e Dual-,lternati!e i 

    •  !he dual alternati!e i , also calledi else structure, ta+es one actionwhen its ;oolean epression isevaluated as true, and uses an elseclause to de#ne the actions to ta+ewhen the epression is evaluated asfalse.

    • It ta+es the form)

      if (Boolean expression)

      action/statement if true;

      else

      action/statement if false;

    %ormat o t&e i-else 3tatement

    • Allows a choice between statementsdepending on whether expression" is true or alse

      i expression"

     

    statement set1(

    E

    else

     

      statement set2(

    E

    5o$ t&e i2else For:s

    • If expression" is true, statement

    set 1 is eecuted and statement set 2 is s+ipped.

    • If expression" is alse, statementset 1 is s+ipped and statement set2 is eecuted.

    =hat if the two persons are the sameageH

    •  !he program incorrectly says thesecond person is older.

    •  !o solve this we must handle all threepossibilities.

    i2else 3tatements

    •  !he if&else statement allows a choiceto be made between two possiblealternatives.

    • 0ometimes a choice must be madebetween more than two possibilities.

  • 8/18/2019 Computer Finals Reviewer

    5/20

    • Consider using a the ifelse ifstatement.

    • Chain of i statements that test inorder until one is found to be true

    • ifelse if also allows a choice of morethan two or many alternatives.

    i2else i  Dormat

    i expression"

      statement set 1(

    else i expression"

      statement set 2(

     

    G

    else i expression"  statement set n(

    =sing a Trailing else

    • 1sed with i2else i  statement whennone of expression" is true

    • *rovides a default statement or action

    • Can be used to catch invalid values or

    handle other eceptional situations

    Create a C program that determine ifyou can vote else you’re not yet eligibleto vote.

    • Avoid Common *itfallswith if 0tatements

    • Dorgetting that C comparisons arecase sensitive

    • Assuming that indentation has alogical purpose

    • Adding an unwanted semicolon

    • Dorgetting curly braces

    • 1sing J instead of JJ

    • Ma+ing unnecessary comparisons

    %orgetting t&at C++ comparisonsare case sensiti!e

    • =hen you ma+e a charactercomparison, you must remember thatC comparison are case sensitive.

    •  !he program genderCode for instance,the character Kf’ is di/erent from thecharacter KD’ for ?Demale@.

    • "on’t be surprised when the program

    displays the message ?Invalid Code@.

    • Assuming that Indentation has a7ogical *urpose, Adding an 1nwanted0emicolon and Dorgetting Curly ;races

    • Bemember that C ignoreindentation.

    • (nly the placement of semicolons andcurly braces matters in determining

    where statements and bloc+s end.

    • E) if $age< L age%>

      else>

    =sing Instead o

    • "on’t use a single equal sign whenyour intention is to compare values.

    • Eample) if $number J N% 'otice thesingle equal sign) if $number JJ N%

    • if $genderCode JJ KMO%

    Ma:ing =nnecessary Comparisons

    •  A program that determines whether

    the user can vote.

    if $age LJ

    if $age G  An if – else statement that avoids the

    unnecessary comparison

    i age 6

  • 8/18/2019 Computer Finals Reviewer

    6/20

    T&e s$itc& 3tatement

    • 1sed to select among statements fromseveral alternatives

    • May sometimes be used instead ofi2else i  statements

    • s$itc& 0tatement Dormat

    s$itc& expression"

    case exp1 statement set 1(

     break;

    case exp2 statement set 2(

     break;

    case expn statement set n(

    deault statement set (

    E

    s$itc& 0tatement Bequirements

  • 8/18/2019 Computer Finals Reviewer

    7/20

    ,rray InitialiKation

    Seneral 0ynta)

    datatype arrayname TindeU >

    • Eample) int score T

    9oat lenght TPU >

    • In C, an array consisting of Fvariables of type int can be declaredas follows)

    int score J (

    int data type of arrayvariable $base type%

    score  variable used for thearray

     [ 5 ] si:e of the array $declaredsi:e%

    • Is also written as)

    int scoreT6U, scoreT

    •  !his array can be viewed in thecomputer as)

    ne Dimensional ,rray InitialiKation

    • int scoreT3U>

    scoreT6U J V6>

    scoreT

    scoreTU J

    • int scoreT3U J WV6, VF,

    • int scoreT U J WV6, VF,

    Indeed variables not provided withinitiali:ers are initiali:ed to :ero.

    • (ne&Array Initiali:ation0ource Code

    • Array Initiali:ation (utput

    • (ne "imensionalArray Initiali:ation

    • (ne "imensionalArray Initiali:ation

    • 0ample *rogram$without array%

    F&at is T$o-Dimensional ,rray

    • Arrays are also useful in formingtables or matrices.

    • It can de#ne one array for multiplesets of data.

    • It is li+e a table in a spreadsheet $hasrows and columns%

    • 1se two si:e $inde% declarators inde#nition

    int numberOJ.J(

  • 8/18/2019 Computer Finals Reviewer

    8/20

    OJ'umber of rows

    .J'umber of columns

    Pinclude 1iomanip6

    • A header #le for inputoutputmanipulator

    • Is a library that is used to manipulate

    the output of our program

    3ome Manipulators=sed in t&e ;rogram

    setios9ags includes)

    • iosf*ed

    • ioss&o$point

    • setprecision

    • set$iosf*ed

    • "isplay 9oating point values usingnormal notation $will not use ascienti#c notation%

    •  !herefore we’ll never see a numberdisplayed as

  • 8/18/2019 Computer Finals Reviewer

    9/20

    %ield - it is a group of characters

    ta+en as one. It is a logical unit ofdata.

    E. 'ame, Address, *hone

    Record - it is a group of related #elds

    pertaining to one entity.

    • (ne record is displayed from

    the Employee !able above. !hetable contains P #elds.

    %ile - it is a group of related recordspertaining to subZect. A #le issometimes called a table.

    E. 0tudent, *rofessor, Course,

    0chedule

    Database

    It is a collection of related #les

    pertaining to one subZect.

    • Eamples of ;usiness "atabases

    •  !elephone boo+

    • 0tudent data

    • Music

    • Dingerprint database

    • "ictionaries

    • Customer data

    • Beal estate listings

    • ospitalpatient data

    • Inventory

    Le!els o Data rganiKation

    perators and

    Mat&ematical

    )*pressions

    Mat&ematical )*pressions

    • An epression can be a constant, a

    variable, or a combination of constantsand variables combined withoperators.

    • Can create comple epressions using

    multiple mathematical operators.

    • Eample mathematical epressions

    Q

    &eig&t

    a + b 2 c=sing Mat&ematical )*pressions

    • Can be used in assignment

    statements, with cout, and in othertypes of statements

    • Eamples)

    area Q U ;I U radius(

    cout 11 4border is 4 11

    QUl+$""(,ssignment 3tatement

    • 1ses the equal sign operator

    • as a single variable on the left side

    and a value on the right side

    • Copies the value on the right into the

    variable on the left

    * ( y >( K O(

    RECORD

  • 8/18/2019 Computer Finals Reviewer

    10/20

    * * + y(

    y y + O(

    K + * + K(

    perators

    •  !hese are the symbols that tells the

    compiler to perform a speci#cmathematical or logical manipulation.

    Types o perators

      Q + Q U Q Q" Q

     Q + Q" U Q Q" ?

    • Eample) Evaluate the following

    epressions

    a J $F 4% [ 3

    b J F 4 [ 3

    c J F6

  • 8/18/2019 Computer Finals Reviewer

    11/20

    3ome ;redefned %unctions in C++

    • *rede#ned functions & are functions

    that are built into C to performsome standard operations.

    •  !hese functions were prede#ned for

    you, meaning that you didnOt have totell the computer how to compute the

    square root and power of a number.

    •  !he header #le required for

    mathematical functions is Pinclude1cmat&6

    Relational perators• 1sed to compare numbers to

    determine relative order

    • Belational (perators)

    Relational )*pressions

    • Belational epressions are ;oolean

    $i.e., evaluate to true or alse"

    • Eamples)

  • 8/18/2019 Computer Finals Reviewer

    12/20

     

    Logical ;recedence

      5ig&est A 

    XX

      Lo$est YY

      )*ample

      Q 1 ." YY 6 >" XX B 6 0"

      is true because A'" is done before (B

    More on ;recedence

    )*ample

      P G N \\ F JJ Y is true

    RDM3 and T,L)

    R)L,TIN35I;3 IN ,CC)33

    Relational Database

    •  !he Belational Model was developed in

  • 8/18/2019 Computer Finals Reviewer

    13/20

    ;rimary #ey

      & A candidate +ey that is chosen torepresent a record uniquely. !hat is, a tablemay consist of many candidate +eys, but('7Q ('E can be selected as a primary +ey.'ote that a primary +ey can have more thanone attribute.

    %oreign #eys

      - is a column or group of columns in arelational database table that provides a lin+between data in two tables.

    Table Relations&ip

    A Relations&ip - is how you tell theprogram that a piece of information meansthe same thing in more than one table.

     !able relationships can be created betweentwo tables as long as they have a commonattribute.

    Belationships are created using a ;rimary#ey from one table and lin+ing it to a related#eld in another table $now called a %oreign#ey%.

    • *rimary +eys are used to uniquely

    identify a table while a foreign +ey isused to lin+ tables using one of the

    primary +eys.

    Types o Relations&ips bet$een Tables

    thecon#dential information is put in atable with a one&to&one relationship tothe main table, and access to thesecond table is restricted.

    ne-to-one

    Q/ ne-to-many

    • ^ery common, one record in theprimary table can be lin+ed to manyrecords in the related table, but eachrecord in the related table can belin+ed to only one in the primary table.

    • Eamples) A mother can have many

    children, but each child has only onemother> a salesman can ma+e manysales, but any given sale is credited toonly one salesman> a person can havemany library boo+s chec+ed out but

    each boo+ can be chec+ed out by onlyone person $at a time%.

    ne-to-many

    ./ Many-to-many

    • ^ery common, when a single record in

    one table can relate to many recordsin another, and a single record in thatsecond table can also relate to manyrecords in the #rst.

    • Eamples) one author can write many

    boo+s, and one boo+ can have severalauthors> one student can ta+e many

  • 8/18/2019 Computer Finals Reviewer

    14/20

    classes and one class will have manystudents> one order can contain manyitems, and one item can appear inmany orders.

    •  !hese relationships are not

    established directly> they must beaccomplished through a 8Zunctiontable9 li+e Srades below.

    )norce Reerential Integrity

    • An orp&an record is one that refers

    to a noneistent record in anothertable, such as the orders placed bynoneistent customers.

    •  !he purpose of using referential

    integrity is to prevent orphan recordsand to +eep references synchroni:edso that you donOt have any recordsthat reference other records that nolonger eist.

    •  Qou enforce referential integrity by

    enabling it for a table relationship.•

    (nce enforced, Access reZects anyoperation that would violatereferential integrity for that tablerelationship.

    • Access reZects updates that change

    the target of a reference, and alsodeletions that remove the target of areference.

    ,ter you &a!e enorced reerentialintegrity7 t&e ollo$ing rules apply

     Qou cannot enter a value in the foreign+ey #eld of a related table if that valuedoesnOt eist in the primary +ey #eld of the primary table _ doing so createsorphan records.

    •  Qou cannot delete a record from a

    primary table if matching records eistin a related table. Dor eample, youcannot delete an employee recordfrom the Employees table if there are

    orders assigned to that employee inthe (rders table.

    •  Qou cannot change a primary +ey

    value in the primary table if doing sowould create orphan records. Doreample, you cannot change an ordernumber in the (rders table if there areline items assigned to that (rder in

    the (rder "etails table.

    Reerential Integrity ptions

    Cascade =pdate Related %ields

    - permits the change of the primary +ey ofthe ?one@ table and modi#es the relatedrecords in the ?many@ table to match $e.g. ifa library patron loses her card, any boo+sshe has chec+ed out can be switched to hernew card number.%

    Reerential Integrity

    Cascade Delete Related %ields

    - permits the deletion of a record in the?one@ table and deletes all related records inthe ?many@ table.

    [[ !hese options are usually turned on whenneeded and turned (DD the rest of the time.

    )dit a Relations&ip

    • In the Belationships window, doubleclic+ the relationship line to reopen theEdit Belationships bo.

    Delete a Relations&ip

    • In the Belationships window, right clic+

    the relationship line and choose "eletefrom the pop&up menu, or clic+ "eletein the +eyboard.

    Repetition 3tructure

    Repeating ;rogram Instructions

    •  !he repetition structure, or loop,

    processes one or more instructionsrepeatedly.

    • 7oop allows you to perform statements

    repeatedly, and Zust as importantly, soto stop the action when warranted.

  • 8/18/2019 Computer Finals Reviewer

    15/20

     *rocess A QE0

    • Drequently, it’s the decision&ma+ing

    that ma+es the programs seemssmart, but looping ma+es programpowerful.

    • ;y using loops, you can $rite one

    set o instructions t&at e*ecutest&ousands or e!en millions o

    times/

    • Every loop contains a ;oolean

    condition that controls whether theinstructions are repeated.

    • A looping condition says whether to

    continue looping $repeating% throughinstructions

    • A loop e*it condition says whether

    to stop looping $repeating% through the

    instructions

      !ake hay while the sunshine." 

    -  !he ?while the sunshine@ is thelooping condition, because it tells youwhen to continue ma+ing hay.

    !ake hay until the sun is no longer

    shining." 

    & In this case ?until the sun is no longershining@ is the loop eit condition, because it

    indicates when you should stop ma+ing hay.

    •  !herefore every looping condition has

    an opposing loop eit condition.

    • C uses looping conditions in

    repetition structures

    • A repetition structure can be pretest or

    posttest

    • In a pretest loop, the condition is

    evaluated #efore the instructions inthe loop are processed

    • In a posttest loop, the condition is

    evaluated after  the instructions in theloop are processed

    • In both cases, the condition is

    evaluated with each repetition

    •  !he instructions in a posttest loop will

    always be processed at least once

    • Instructions in a pretest loop may not

    be processed if the condition initiallyevaluates to false

    •  !he repeatable instructions in a loop

    are called the loop body

    •  !he condition in a loop must evaluate

    to a ;oolean value

    ;erorming Loops

    • 'otice the use of the diamond symbol.

    A loop tests a condition, and if thecondition eists $!rue%, it performs anaction. !hen it tests the conditionagain. If the condition still eists, theaction is repeated. !his continues untilthe condition no longer eists.

    • In the 9owchart, the question 8is * 1

    y9 is as+ed. If the answer is yes, then*rocess A is performed. !he question?is G yH@ is as+ed again. *rocess A isrepeated as long as is less than y.=hen is no longer less than y, therepetition stops and the structure iseited.

    T&e Increment and Decrementperators

    • ++ adds one to a variable

      *++( is the same as *  * +

  • 8/18/2019 Computer Finals Reviewer

    16/20

  • 8/18/2019 Computer Finals Reviewer

    17/20

    • 3entinel

    • 0ome loops require the user to enter aspecial sentinel value to end the loop .

    • 3entinel is a value that determineswhen a loop will end.

    • It is a special value that cannot be

    confused with a valid value, e.g. enter-< to stop

    • 1sed to terminate input when usermay not +now how many values willbe entered

    • 3entinel )*ample

    int points(

    cout 11 4)nter points earned 4

      11 4or -< to [uit" 4(cin 66 points(

    $&ile points A -

  • 8/18/2019 Computer Finals Reviewer

    18/20

    %orgetting curly braces and %ailing toalter a loop control !ariable

    int number J

    while $number GJ

    number >

    %ailing to initialiKe a loop control!ariable

    int number>

    while $number GJ

    W

    cout GG number GG endl>

    number >

    X

    In C an uninitiali:ed variable has anun+nown value> programmers call thisun+nown value a garbage !alue/

    Counters and ,ccumulating Totals

    =sing Counters and ,ccumulators

    • Many computer programs display

    totals.

    • Dor instance, when you receive a

    credit card or telephone service bill,you are usually provided withindividual transaction details, but it isthe total bill in which you are mostinterested.

    • 0imilarly, some programs total the

    number of credit hours generated bycollege students, the gross payroll forall employees and the li+e.

    •  !hese totals are accumulated that

    is, gathered together and added into a#nal sum, by processing individualrecords one at a time in a loop.

    •  !o calculate a total or average, you

    use a counter, accumulator or both.

    • A counter & is a numeric variable used

    for counting something. It is a variablethat is incremented or decrementedeach time a loop repeats

    • An accumulator & is a numeric

    variable used for accumulating$adding together% multiple values

    •  !wo tas+s are associated with counters

    and accumulators) initialiKing andupdating/

    • InitialiKing means assigning a

    beginning value to a counter oraccumulator $usually 6% happensonce, before the loop is processed.

    • =pdating $or incrementing% means

    adding a number to the value of acounter or accumulator.

    • A counter is updated by a constant

    value $usually

  • 8/18/2019 Computer Finals Reviewer

    19/20

     !he sales manager at Miguel’s MusicCompany wants a program that allows him toenter the quarterly sales amount made ineach three regions) Begion epression > update % W

    < or more statements>

     X

    • Initiali:ation represent any steps you

    want to ta+e at the beginning of thestatement.

    • Most often this includes initiali:ing a

    loop control variable.• Epression $condition% any C

    epression that is evaluated as falseor true.

    • If the epression is true any

    statements in the body of the for loopare eecuted.

    • If the epression is false the loop will

    be eited, bypassing the body of thefor loop.

    • 1pdate represents any C

    statements that ta+e place aftereecuting the loop body.

    • 1sually contains an epression that

    updates the counter variable

    • In for loop, the variable is often

    declared and initiali:ed inside the forloop statement.

    for $int J GJ %

    coutGG GG ] ] >

    • 0olution to for

    0quare 7oop

    • \t is used for tab $must be place in

    cout statement%

    • coutGG ? `t ?

    Re!ie$ o ;retest !s/ ;osttest Loops

    • =hether you use a while loop or for

    loop, the loop body might nevereecute.

    • ;oth of these loops are pretest loops loops in which the loop controlvariable is tested before the loop bodyis eecuted.

    • 0ometimes, you want to ensure that a

    loop body eecutes at least once.

    •  !hat way, the code de#nitely would

    eecute one time even if the loop wasnever entered.

    • An alternative is to use posttest loop one in which the loop control variableis test after the loop body eecutes.

    •  !herefore, the instructions in a

    posttest loop will always be processedat least once

    • =hile the instructions in a pretest loop

    may not be processed if the conditioninitially evaluates to false

  • 8/18/2019 Computer Finals Reviewer

    20/20

    T&e do-$&ile Loop

    • do&while 7oop controls a loop that

    tests the loop&continuing condition atthe end, or bottom, of the loop.

    • do&while) a posttest loop $expression is

    evaluated after the loop eecutes%

    • Dormat)

    do

    W

    % or more statements; 

    X while $expression%>

    Deciding F&ic& Loop to =se

    •  while) pretest loop $loop body may

    not be eecuted at all%•  do&while) posttest loop $loop body will

    always be eecuted at least once%

    •  for) pretest loop $loop body may not

    be eecuted at all%> has initiali:ationand update code> is useful withcounters or if precise number ofrepetitions is +nown