Sam Key-C Programming Professional Made Easy-Creat

Embed Size (px)

DESCRIPTION

C programming

Citation preview

  • CProgrammingProfessionalMadeEasySamKey

    ExpertCProgrammingLanguageSuccessInADayForAnyComputerUser!

    2ndEdition

  • Copyright2015bySamKey-Allrightsreserved.

    Innowayisitlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineitherelectronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibitedandanystorageofthisdocumentisnotallowedunlesswithwrittenpermissionfromthepublisher.Allrightsreserved.

  • TableOfContents

    Introduction

    Chapter1TheBasicElementsOfC

    Chapter2WhatisCProgrammingLanguage

    Chapter3UnderstandingCProgram

    Chapter4LearnCProgramming

    Chapter5StorageClasses

    Chapter6Operators

    Chapter7DecisionMaking

    Chapter8CLoops

    Chapter9TypeCastingandErrorHandling

    Conclusion

    PreviewOfAndroidProgramming

    CheckOutMyOtherBooks

  • IntroductionIwanttothankyouandcongratulateyoufordownloadingthebook, ProfessionalCProgrammingMadeEasy:ExpertCProgrammingLanguageSuccessInADayForAnyComputerUser! .

    ThisbookcontainsprovenstepsandstrategiesonhowtounderstandandperformCprogramming.Cisoneofthemostbasicprogrammingtoolsusedforawidearrayofapplications.Mostpeoplestayawayfromitbecausethelanguageseemcomplicated,withallthosecharacters,letters,sequencesandspecialsymbols.

    ThisbookwillbreakdowneveryelementandexplainindetaileachlanguageusedintheCprogram.By the timeyouaredonewith thisbook,Cprogramming languagewillbeeasy tounderstandandeasytoexecute.

    Readonandlearn.

    Thanksagainfordownloadingthisbook.Ihopeyouenjoyit!

  • Chapter1TheBasicElementsOfCTheseeminglycomplicatedCprogramiscomposedofthefollowingbasicelements:

    CharacterSet

    ThealphabetinbothupperandlowercasesisusedinC.The0-9digitsarealsoused,includingwhitespacesandsomespecialcharacters.TheseareusedindifferentcombinationstoformelementsofabasicCprogramsuchasexpressions,constants,variables,etc.

    Specialcharactersincludethefollowing:

    +,.*/%=&!#?^|/(){}[];:@~!

    Whitespacesinclude:

    Blankspace

    Carriagereturn

    Horizontaltab

    Formfeed

    Newline

    Identifiers

    AnidentifierisanamegiventothevariouselementsoftheCprogram,suchasarrays,variablesandfunctions. These contain digits and letters in various arrangements. However, identifiers shouldalwaysstartwithaletter.Thelettersmaybeinuppercase,lowercaseorboth.However,thesearenotinterchangeable. C programming is case sensitive, as each letter in different cases is regarded asseparatefromeachother.Underscoresarealsopermittedbecauseitisconsideredbytheprogramasakindofletter.

    Examplesofvalididentifiersincludethefollowing:

    ab123

    A

    stud_name

    average

    velocity

    TOTAL

  • Identifiersneed to startwith a letter and shouldnot contain illegal characters.Examplesof invalididentifiersincludethefollowing:

    2nd-shouldalwaysstartwithaletter

    Jamshedpur-containstheillegalcharacter()

    studname-containsablankspace,whichisanillegalcharacter

    stud-name-containsanillegalcharacter(-)

    In C, a single identifiermay be used to refer to a number of different entitieswithin the sameCprogram.Forinstance,anarrayandavariablecanshareoneidentifier.Forexample:

    Thevariableis intdifference,average,A[5];//sum,average

    Theidentifieris A[5] .

    Inthesameprogram,anarraycanbenamedA,too.

    __func__

    The __func__ isapredefinedidentifierthatprovidesfunctionsnamesandmakestheseaccessibleandready for use anytime in the function. The complier would automatically declarethe __func__immediatelyafterplacing theopeningbracewhendeclaring the functiondefinitions.Thecompilerdeclaresthepredefinedidentifierthisway:

    staticconstchar__func__[]=Alex;

    Alex referstoaspecificnameofthisparticularfunction.

    Takealookatthisexample:

    #include

    voidanna1(void){

    printf("%sn",__func__);

    return;

    }

    intmain(){

  • myfunc();

    }

    Whatwillappearasanoutputwillbeanna1

    Keywords

    ReservedwordsinCthatcomewithstandardandpredefinedmeaningsarecalledkeywords.Theusesfor thesewordsare restricted to theirpredefined intendedpurpose.Keywordscannotbeutilizedasprogrammer-definedidentifiers.InC,thereare32keywordsbeingused,whichincludethefollowing:

    auto

    break

    char

    case

    continue

    const

    do

    default

    double

    float

    else

    extern

    enum

    goto

    for

    if

    long

    int

  • register

    short

    return

    sizeof

    signed

    switch

    typedef

    struct

    union

    switch

    void

    unsigned

    while

    volatile

    DataTypes

    Therearedifferent typesofdatavalues thatarepassedinC.Eachof the typesofdatahasdifferentrepresentations within the memory bank of the computer. These also have varying memoryrequirements.Datatypemodifiers/qualifiersareoftenusedtoaugmentthedifferenttypesofdata.

    Supported data types in C include int, char, float, double, void, _Bool, _Complex, arrays, andconstants.

    int

    Integerquantitiesarestored in this typeofdata.Thedata type int canstoreacollectionofdifferentvalues,startingfromINT_MAXtoINT_MIN.Anin-headerfile,,definestherange.

    Theseintdatatypesusetypemodifierssuchasunsigned,signed,long,longlongandshort.

    Shortintmeansthattheyoccupymemoryspaceofonly2bytes.

    Alongintuses4bytesofmemoryspace.

  • Shortunsignedintisadatatypethatuses2bytesofmemoryspaceandstorepositivevaluesonly,rangingfrom0to65535.

    Unsigned int requiresmemoryspace similar to thatof shortunsigned int.For regularandordinaryint,thebitattheleftmostportionisusedfortheinteger ssign.

    Long unsigned int uses 4 bytes of space. It stores all positive integers ranging from 0 to4294967295.

    Anintdataisautomaticallyconsideredassigned.

    Long long intdata typeuses64bitsmemory.This typemayeitherbeunsignedor signed.Signed long long data type can store values ranging from9,223,372,036,854,775,808 to9,223,372,036,854,775,807. Unsigned long long data type stores value range of 0 to18,446,744,073,709,551,615.

    char

    SinglecharacterssuchasthosefoundinCprogramscharactersetarestoredbythistypeofdata.Thechardatatypeuses1byteinthecomputer smemory.AnyvaluefromCprogramscharactersetcanbestoredaschar.Modifiersthatcanbeusedareeither unsigned or signed .

    A charwould always use 1 byte in the computer smemory space,whether it is signed orunsigned.Thedifference ison thevalue range.Values that canbe storedasunsignedcharrange from0 to255.Signedchar storesvalues ranging from128 to+127.Bydefault, achardatatypeisconsideredunsigned.

    Foreachofthechartypes,thereisacorrespondingintegerinterpretation.Thismakeseachcharaspecialshortinteger.

    float

    A float is a data type used in storing real numbers that have single precision. That is,precisiondenotedashaving6moredigitsafteradecimalpoint.Floatdatatypeuses4bytesmemoryspace.

    Themodifierforthisdatatypeis long ,whichusesthesamememoryspaceasthatofdoubledatatype.

    double

    Thedoubledata type isusedforstoringrealnumbers thathavedoubleprecision.Memoryspaceusedis8bytes.Doubledatatypeuses long asatypemodifier.Thisusesupmemorystoragespaceof10bytes.

    void

    Voiddatatypeisusedforspecifyingemptysets,whichdonotcontainanyvalue.Hence,void

  • datatypealsooccupiesnospace(0bytes)inthememorystorage.

    _Bool

    ThisisaBooleantypeofdata.Itisanunsignedtypeofinteger.Itstoresonly2values,whichis0and1.Whenusing_Bool,include.

    _Complex

    Thisisusedforstoringcomplexnumbers.InC,threetypesof_Complexareused.Thereisthe float _Complex , double _Complex , and long double _Complex . These are found infile.

    Arrays

    Thisidentifierisusedinreferringtothecollectionofdatathatsharethesamenameandofthesametypeofdata.Forexample,allintegersorallcharactersthathavethesamename.Eachofthedataisrepresentedbyitsownarrayelement.Thesubscriptsdifferentiatethearraysfromeachother.

    Constants

    Constants are identifiers used in C. The values of identifiers do not change anywhere within theprogram.Constantsaredeclaredthisway:

    constdatatypevarname=value

    const isthekeywordthatdenotesordeclaresthevariableasthefixedvalueentity,i.e.,theconstant.

    InC,thereare4basicconstantsused.Theseincludetheintegerconstant,floating-point,characterandstring constants. Floating-point and integer types of constant do not contain any blank spaces orcommas.Minussignscanbeused,whichdenotesnegativequantities.

    IntegerConstants

    Integerconstantsare integervaluednumbersconsistingofsequenceofdigits.Thesecanbewrittenusing3differentnumbersystems,namely,decimal,octalandhexadecimal.

    Decimalsystem(base10)

    Anintegerconstantwritteninthedecimalsystemcontainscombinationsofnumbersrangingfrom0to9.Decimalconstantsshouldstartwithanynumberotherexcept0.Forexample,adecimalconstantiswritteninCas:

    constintsize=76

    Octal(base8)

    Octal constants are anynumber combinations from0 to 7.To identify octal constants, thefirstnumbershouldbe0.Forexample:

  • constinta=043;constintb=0;

    Anoctalconstantisdenotedinthebinaryform.Taketheoctal0347.Eachdigitisrepresentedas:

    0347=011100111=3*82+4*81+7*80=231---------347

    Hexadecimalconstant(base16)

    This typeconsistsofanyof thepossiblecombinationsofdigits ranging from0 to9.Thistype also includes letters a to f, written in either lowercase or uppercase. To identifyhexadecimalconstants,theseshouldstartwithoXor0X.Forexample:

    constintc=0x7FF;

    Forexample,thehexadecimalnumber0x2A5isinternallyrepresentedinbitpatternswithinCas:

    0x2A5=001010100101=2*162+10*161+5*160=677------------2A5

    Wherein,677isthedecimalequivalentofthehexadecimalnumber0x2 .

    Prefixesforintegerconstantscaneitherbelongorunsigned.Alongintegerconstant(longint)endswith a l of L , such as 67354L or 67354l . The last portion of an unsigned long integer constantshould either be ul or UL , such as 672893UL or 672893ul . For an unsigned long long integerconstant, UL or ul shouldbeat thelastportion.Anunsignedconstantshouldendwith U or u ,suchas 673400095u or 673400095U .Normal integer constants arewrittenwithout any suffix, such as asimple 67458 .

    FloatingPointConstant

    Thistypeofconstanthasabase10orbase16andcontainsanexponent,adecimalpointorboth.Forafloatingpointconstantwithabase10andadecimalpoint, thebase is replacedbyan E or e .Forexample,theconstant1.8*10-3iswrittenas1.8e-3or1.8E-3.

    Forhexadecimalcharacterconstantsandtheexponentisinthebinaryform,theexponentisreplacedby P or p .Takealookatthisexample:

    Thistypeofconstantisoftenprecisionquantities.Theseoccupyaround8bytesofmemory.Differentadd-onsareallowedinsomeCprogramversions,suchas F forasingleprecisionfloatingconstantor L foralongfloatingpointtypeofconstant.

    CharacterConstant

  • A sequence of characters, whether single or multiple ones, enclosed by apostrophes or singlequotation marks is called a character constant. The character set in the computer determines theintegervalueequivalent toeachcharacterconstant.Escapesequencesmayalsobe foundwithin thesequenceofacharacterconstant.

    Singlecharacterconstantsenclosedbyapostrophesisinternallyconsideredasintegers.Forexample,Aisasinglecharacterconstantthathasanintegervalueof65.ThecorrespondingintegervalueisalsocalledtheASCIIvalue.Becauseofthecorrespondingnumericalvalue,singlecharacterconstantscan be used in calculations just like how integers are used.Also, these constants can also be usedwhencomparingothertypesofcharacterconstants.

    Prefixes used in character constants such as L , U or u are used for character literals. These areconsideredaswide typesofcharacterconstants.Character literalswith theprefix L areconsideredunder the type wchar_t ,whicharedefinedas under theheader file.Character constantsthat use the prefix U or u are considered as type char16_t or char32_t . These are considered asunsignedtypesofcharactersandaredefinedundertheheaderfileas .

    Thosethatdonothavetheprefix L areconsideredanarroworordinarycharacterconstant.Thosethathaveescapesequencesorarecomposedofatleast2charactersareconsideredasmulticharacterconstants.

    Escape sequences are a type of character constant used in expressing non-printing characters likecarriage return or tab. This sequence always begins with a backward slash, followed by specialcharacters.ThesesequencesrepresentasinglecharacterintheClanguageeveniftheyarecomposedofmorethan1character.Examplesofsomeofthemostcommonescapesequences,andtheirinteger(ASCII)value,usedinCincludethefollowing:

    CharacterEscapeSequenceASCIIValue

    Backspace\b008

    Bell\a007

    Newline\n010

    Null\0000

    Carriage\r013

    Horizontaltab\t009

    Verticaltab\v011

    Formfeed\f012

    StringLiterals

  • Multibyte characters that form a sequence are called string literals. Multibyte characters have bitrepresentations that fit into 1 or more bytes. String literals are enclosed within double quotationmarks, for example, A and Anna . There are 2 types of string literals, namely, UTF-8 stringliterals andwide string literals.Prefixesused forwide string literals include u , U or L .Prefix forUTF-8stringliteralsis u8 .

    Additional characters or extended character sets included in string literals are recognized andsupportedbythecompiler.Theseadditionalcharacterscanbeusedmeaningfullytofurtherenhancecharacterconstantsandstringliterals.

    Symbolicconstants

    Symbolicconstantsaresubstitutenamesfornumeric,stringorcharacterconstantswithinaprogram.Thecompilerwouldreplacethesymbolicconstantswithitsactualvalueoncetheprogramisrun.

    Atthebeginningoftheprogram,thesymbolicconstantisdefinedwitha#definefeature.Thisfeatureiscalledthepreprocessordirective.

    Thedefinitionofasymbolicconstantdoesnotendwithasemicolon,likeotherCstatements.Takealookatthisexample:

    #definePI3.1415

    (//PIistheconstantthatwillrepresentvalue3.1415)

    #defineTrue1

    #definename"Alice"

    Forallnumericconstantssuchasfloatingpointandinteger,non-numericcharactersandblankspacesare not included. These constants are also limited byminimum andmaximum bounds, which areusuallydependentonthecomputer.

    Variables

    Memorylocationswheredataisstoredarecalledvariables.Theseareindicatedbyauniqueidentifier.Names for variables are symbolic representations that refer to a particular memory location.Examplesarecount,car_noandsum.

    Ruleswhenwritingthevariablenames

    Writingvariablenames followcertain rules inorder tomake sure thatdata is storedproperlyandretrievedefficiently.

    Letters (in both lowercase and uppercase), underscore (_) and digits are the onlycharactersthatcanbeusedforvariablenames.

  • Variablesshouldbegineitherwithanunderscoreoraletter.Startingwithanunderscoreisacceptable,butisnothighlyrecommended.Underscoresatthebeginningofvariablescancomeinconflictwithsystemnamesandthecompilermayprotest.

    There is no limit on the length of variables.The compiler can distinguish the first 31characters of a variable. This means that individual variables should have differentsequencesforthe1st31characters.

    Variablesshouldalsobedeclaredatthebeginningofaprogrambeforeitcanbeused.

  • Chapter2WhatisCProgrammingLanguage?InC,theprogramminglanguageisalanguagethatfocusesonthestructure.Itwasdevelopedin1972,atBellLaboratories,byDennisRitchie.ThefeaturesofthelanguagewerederivedfromB,whichisanearlierprogramminglanguageandformallyknownasBCPLorBasicCombinedProgrammingLanguage.TheCprogramminglanguagewasoriginallydevelopedtoimplementtheUNIXoperatingsystem.

    StandardsofCProgrammingLanguage

    In 1989, the American National Standards Institute developed the 1st standard specifications. Thispioneering standard specification was referred to as C89 and C90, both referring to the sameprogramminglanguage.

    In1999,arevisionwasmadeintheprogramminglanguage.TherevisedstandardwascalledC99.Ithad new features such as advanced data types. It also had a few changes,which gave rise tomoreapplications.

    TheC11standardwasdeveloped,whichaddednewfeaturestotheprogramminglanguageforC.Thishad a library-like generic macro type, enhanced Unicode support, anonymous structures, multi-threading,bounds-checkedfunctionsandatomicstructures.IthadimprovedcompatibilitywithC++.SomepartsoftheC99libraryinC11weremadeoptional.

    The Embedded C programming language included a few features that were not part of C. Theseincludedthenamedaddressspaces,basicI/Ohardwareaddressingandfixedpointarithmetic.

    CProgrammingLanguageFeatures

    Therearealotoffeaturesoftheprogramminglanguage,whichincludethefollowing:

    Modularity

    Interactivity

    Portability

    Reliability

    Effectiveness

    Efficiency

    Flexibility

    UsesoftheCProgrammingLanguage

  • This language has found several applications. It is now used for the development of systemapplications,whichformahugeportionofoperatingsystemssuchasLinux,WindowsandUNIX.

    SomeoftheapplicationsofClanguageincludethefollowing:

    Spreadsheets

    Databasesystems

    Wordprocessors

    Graphicspackages

    Networkdrivers

    CompilersandAssemblers

    Operatingsystemdevelopment

    Interpreters

  • Chapter3UnderstandingCProgram

    TheCprogramhasseveralfeaturesandstepsinorderforanoutputorfunctioniscarriedout.

    BasicCommands(forwritingbasicCProgram)

    ThebasicsyntaxandcommandsusedinwritingasimpleCprogramincludethefollowing:

    #include

    Thiscommandisapreprocessor.standsforstandardinputoutputheaderfile.ThisisafilefromtheClibrary,whichisincludedbeforetheCprogramiscompiled.

    intmain()

    ExecutionofallCprogrambeginswiththismainfunction.

    {

    Thissymbolisusedtoindicatethestartofthemainfunction.

    }

    Thisindicatestheconclusionofthemainfunction.

    /**/

    Anythingwritteninbetweenthiscommandwillnotbeconsideredforexecutionandcompilation.

    printf( output );

    Theprintfcommandprintstheoutputonthescreen.

    getch();

    Writingthiscommandwouldallowthesystemtowaitforanykeyboardcharacterinput.

    return0

    WritingthiscommandwillterminatetheCprogramormainfunctionandreturnto0.

    AbasicCProgramwouldlooklikethis:

  • #includeintmain(){/*OurfirstsimpleCbasicprogram*/printf(HelloPeople!);getch();return0;}

    Theoutputofthissimpleprogramwouldlooklikethis:

    HelloPeople!

  • Chapter4LearnCProgrammingAfterlearningthebasicelementsandwhatthelanguageisallabout,timetostartprogramminginC.Herearethemostimportantsteps:

    Downloadacompiler

    AcompilerisaprogramneededtocompiletheCcode.Itinterpretsthewrittencodesandtranslatesitintospecificsignals,whichcanbeunderstoodbythecomputer.Usually,compilerprogramsarefree.Therearedifferentcompilersavailable forseveraloperatingsystems.MicrosoftVisualStudioandMinGWarecompilersavailableforWindowsoperatingsystems.XCodeisamongthebestcompilersforMac.AmongthemostwidelyusedCcompileroptionsforLinuxisgcc.

    BasicCodes

    ConsiderthefollowingexampleofasimpleCprograminthepreviouschapter:

    #include

    intmain()

    {

    printf("HelloPeople!\n");

    getchar();

    return0;

    }

    At the start of the program, #include command is placed. This is important in order to load thelibrarieswheretheneededfunctionsarelocated.

    The referstothefilelibraryandallowsfortheuseofthesucceedingfunctions getchar()and printf().

    Thecommand intmain() sendsamessagetothecompilertorunthefunctionwiththenamemainandreturnacertainintegeronceitisdonerunning.EveryCprogramexecutesamainfunction.

    Thesymbol {} isusedtospecifythateverythingwithinitisacomponentofthemainfunctionthatthecompilershouldrun.

  • Thefunction printf() tells thesystemtodisplaythewordsorcharacterswithintheparenthesisontothecomputerscreen.ThequotationmarksmakecertainthattheCcompilerwouldprintthewordsorcharactersasitis.Thesequence \n informstheCcompilertoplaceitscursortothesucceedingline.Attheconclusionoftheline,a ; (semicolon)isplacedtodenotethatthesequenceisdone.MostcodesinCprogramneedsasemicolontodenotewherethelineends.

    Thecommand getchar() informs the compiler to stop once it reaches the end of the function andstandbyforaninputfromthekeyboardbeforecontinuing.ThiscommandisveryusefulbecausemostcompilerswouldruntheCprogramandthenimmediatelyexitsthewindow.The getchar() commandwouldpreventthecompilertoclosethewindowuntilafterakeystroke.ismade.

    Thecommand return0 denotesthatthefunctionhasended.ForthisparticularCprogram,itstartedasan int ,whichindicatesthattheprogramhastoreturnanintegeronceitisdonerunning.The 0 isanindicationthatthecompilerrantheprogramcorrectly.Ifanothernumberisreturnedattheendoftheprogram,itmeansthattherewasanerrorsomewhereintheprogram.

    Compilingtheprogram

    Tocompiletheprogram,typethecodeintotheprogramscodeeditor.Savethisasatypeof*.cfile,thenclicktheRunorBuildbutton.

    Commentingonthecode

    Any comments placed on codes are not compiled. These allow the user to give details on whathappens in thefunction.Commentsaregoodremindersonwhat thecode isallaboutandforwhat.Commentsalsohelpotherdeveloperstounderstandwhatthecodewhentheylookatit.

    Tomakeacomment,adda /* atthebeginningofthecomment.Endthewrittencommentwitha */ .Whencommenting,commentoneverythingexceptthebasicportionsofthecode,whereexplanationsarenolongernecessarybecausethemeaningsarealreadyclearlyunderstood.

    Also,commentscanbeutilizedforquickremovalofcodepartswithouthavingtodeletethem.Justenclose portions of the code in /**/ , then compile.Remove these tags if these portions are to beaddedbackintothecode.

    USINGVARIABLES

    Understandingvariables

    Definethevariablesbeforeusingthem.Somecommononesinclude char , float and int .

    Declaringvariables

    Again,variableshavetobedeclaredbeforetheprogramcanusethem.Todeclare,enterdatatypeandthenthenameofthevariable.Takealookattheseexamples:

    charname;

  • floatx;

    intf,g,i,j;

    Multiplevariablescanalsobedeclaredallonasingleline,onconditionthatallofthembelongtothesamedatatype.Justseparatethenamesofthevariablescommas(i.e., intf,g,i,j; ).

    Whendeclaringvariables,alwaysendthelinewithasemicolontodenotethatthelinehasended.

    Locationondeclaringthevariables

    Declaringvariablesisdoneatthestartofthecodeblock.Thisistheportionofthecodeenclosedbythe brackets {} . The program wont function well if variables are declared later within the codeblock.

    Variablesforstoringuserinput

    Simpleprogramscanbewrittenusingvariables.Theseprogramswillstoreinputsoftheuser.Simpleprogramswill use the function scanf ,which searches the user s input for particular values. Take alookatthisexample:

    #include

    intmain()

    {

    intx;

    printf("45:");

    scanf("%d",&x);

    printf("45%d",x);

    getchar();

    return0;

    }

    Thestring &d informsthefunction scanf tosearchtheinputforanyintegers.

  • Thecommand & placedbeforethe x variableinformsthefunction scanf whereitcansearchforthespecificvariableso that thefunctioncanchange it. Italso informs thefunction tostore thedefinedintegerwithinthevariable.

    Thelastprintf tellsthecompilertoreadbacktheintegerinputintothescreenasafeedbackfortheusertocheck.

    Manipulatingvariables

    Mathematicalexpressionscanbeused,whichallowuserstomanipulatestoredvariables.Whenusingmathematicalexpressions,itismostimportanttoremembertousethe=distinction.Asingle = willsetthevariablesvalue.A == (doubleequalsign)isplacedwhenthegoalistocomparethevaluesonbothsidesofthesign,tocheckifthevaluesareequal.

    Forexample:

    x=2*4;/*setsthevalueof"x"to2*4,or8*/

    x=x+8;/*adds8totheoriginal"x"value,anddefinesthenewxvalueasthespecificvariable*/

    x==18;/*determinesifthevalueof"x"isequalto18*/

    x=8TRUE

    !=/*notequalto*/

    4!=5TRUE

    ==/*equalto*/

    7==7TRUE

    HowtowriteabasicIFconditionalstatement

    A conditional IF statement is used in determining what the next step in the program is afterevaluationofthestatement.Thesecanbecombinedwithothertypesofconditionalstatementsinordertocreatemultipleandpowerfuloptions.

    Takealookatthisexample:

    #include

    intmain()

    {

    if(4B)isnottrue.

    < Itcheckswhetherornotthe value of the leftoperandis lessthanthevalue of the rightoperand.Ifitis,thentheconditionistrue.

    (A= Itcheckswhetherornotthe value of the leftoperand is bigger thanthe value of the rightoperand.Ifitis,thentheconditionistrue.

    (A>=B)isnottrue.

  • LogicalOperators

    LetA=1andB=0.

    Operator Description Example&& It is known as the

    LogicalANDOperator.Iftheoperandsarenon-zero, the condition istrue. Otherwise, it isfalse.

    (A&&B)isfalse.

    || It is known as theLogical OR Operator.If one of the twooperands is non-zero,theconditionistrue.

    (A||B)istrue.

    ! It is known as theLogicalNOTOperator.It isusedtoreversethelogical state of theoperand. If thecondition is true, theLogicalNOTOperatorwillmakeitfalse.

    !(A&&B)istrue.

    BitwiseOperators

    Theseoperatorsworkonbitsandperformbit-by-bitoperation.ThisistheTruthTablefor|,^,and&.

    p q p&q p|q p^q0 0 0 0 00 1 0 1 11 1 1 1 01 0 0 1 1

    IfA=6andB=13:

    A=00111100

  • B=00001101

    ----------------

    A&B=00001100

    A|B=00111101

    A^B=00110001

    ~A=11000011

    LetA=60andB=13.

    Operator Description Example& It is known as the

    Binary AND Operator.Itcopiesabitifitexistsinbothoperands.

    (A&B)=12,which isequivalent to 00001100inbinary.

    | It is known as theBinaryOROperator. Itcopies a bit if it existsin either one of theoperands.

    (A | B) = 61, which isequivalent to 00111101inbinary.

    ^ It is known as theBinary XOR Operator.Itcopiesabitifitexistsinjustoneoperand.

    (A ^ B) = 49, which isequivalent to 00110001inbinary.

    ~ It is known as theBinary OnesComplement Operator.It is unary and has theflippingbitseffect.

    (~A) = -60, which isequivalent to 11000011inbinary.

    It is known as theBinary Right ShiftOperator. The value of

    A >> 2 = 15, which isequivalent to 00001111inbinary.

  • the left operand ismoved to the rightdepending on howmany bits the rightoperandspecified.

    AssignmentOperators

    Operator Description Example= It is an assignment

    operator. It allocatesvalues from the rightoperand to the leftoperand.

    C = A + B assigns thevalueofA+BintoC.

    += It is known as the addAND assignmentoperator. It adds therightoperandtotheleftoperand and thenassigns thevalue to theleftoperand.

    C+=A is equal toC=C+A

    -= It is known as thesubtract ANDassignment operator. Itsubtracts the rightoperand from the leftoperand and thenassigns thevalue to theleftoperand.

    C-=AisequaltoC=CA

    *= It is known as themultiply ANDassignment operator. Itmultiplies the rightoperand with the leftoperand and thenassigns thevalue to theleftoperand.

    C*=A is equal toC=C*A

    /= ItisknownasthedivideAND assignmentoperator. It divides theleft operand with theright operand and thenassignstheresult tothe

    C /=A is equal to C =C/A

  • leftoperand.%= It is known as the

    modulus ANDassignment operator. Ittakes modulus usingtwo operands andassignstheresult totheleftoperand.

    C%=AisequaltoC=C%A

    >2

    &= It is known as thebitwise ANDassignmentoperator.

    C&=2isequaltoC&2

    ^= It is known as thebitwise exclusive ORand assignmentoperator.

    C^=2isequaltoC^2

    |= It is known as thebitwise inclusive ORand assignmentoperator.

    C|=2isequaltoC|2

  • Chapter7DecisionMaking

    The structures for decision making require you to specify at least one condition to be tested orevaluatedbytheprogram,alongwithstatementsthathavetobeexecutediftheconditionisfoundtobetrue.However,statementsthatwerefoundtobefalsecanalsobeexecutedoptionally.Thegeneralform of a decision making structure in most programming languages looks something like theexamplegivenbelow:

    TheCprogramminglanguageassumesallnon-nullandnon-zerovaluestobetrue.Ifthereiseitheranullorzero,Cassumesittobefalse.TheCprogramminglanguagealsomakesuseofthefollowingdecisionmakingstatements:

    TheIfStatement

    AnifstatementconsistsofaBooleanexpressionthatisfollowedbyatleastonemorestatement.

    Syntax

    Thesyntaxofanifstatementisgenerally:

  • If(Booleanexpression)

    {

    /*thestatement(s)tobeexecutediftheBooleanexpressionistrue

    */

    }

    If the Boolean expression is found to be true, then the code inside the if statement is executed.Otherwise,thefirstsetofcodeattheendoftheifstatementisexecuted.

    Asmentionedearlier,theCprogramminglanguageassumesallnon-nullandnon-zerovaluestobetruewhileitassumesallnullorzerovaluestobefalse.

    FlowDiagram

    Example:

  • #include

    intmain()

    {

    /*localvariabledefinition*/

    inta=10;

    /*usetheifstatementtochecktheBooleancondition*/

    if(a14);

  • break;

    case=14:

    printf(Number=14);

    break;

    case

  • casevar:

    printf(Number=1);

    break;

    }

    FlowDiagram

    Example:

    #include

    intmain()

    {

    /*localvariabledefinition*/

    chargrade=B;

    switch(grade)

  • {caseA:

    printf(Excellent!\n);

    break;

    caseB:

    caseC:

    printf(Welldone\n);

    break;

    caseD:

    printf(:Youpassed\n);

    break;

    caseF:

    printf(Bettertryagain\n);

    break;

    default:

    printf(Invalidgrade\n);

    }

    printf(Yourgradeis%c\n,grade);

    return0;

    }

    Oncetheabovecodeisexecuted,thefollowingoutputisshown:

    Welldone

    YourgradeisB

  • NestedSwitchStatements

    If you are wondering whether or not it is possible to use a switch in an outer switch statementsequence,theanswerisyes.Youcanincludeaswitchinthestatementsequencewithoutencounteringanyconflictseventhoughthecaseconstantsoftheouterandinnerswitchhavecommonvalues.

    Syntax

    Thisisthegeneralsyntaxforanestedswitch:

    switch(ch1)

    {

    caseA:

    printf(ThisAispartoftheouterswitch);

    switch(ch2)

    {

    caseA:

    printf(ThisAispartoftheinnerswitch);

    break;

    caseB:

    /*casecode*/

    }

    break;

    caseB:

    /*casecode*/

    }

    Example:

    #include

  • intmain()

    {

    /*localvariabledefinition*/

    inta=100;

    intb=200;

    switch(a)

    {

    case100:

    printf(Thisispartoftheouterswitch\n,a);

    switch(b)

    {

    case200:

    printf(Thisispartoftheinnerswitch\n,a);

    }

    }

    printf(Theexactvalueofais:%d\n,a);

    printf(Theexactvalueofbis:%d\n,b);

    return0;

    }

    Oncetheabovecodeisexecuted,thefollowingoutputisshown:

    Thisispartoftheouterswitch

    Thisispartoftheinnerswitch

    Theexactvalueofais:100

    Theexactvalueofbis:200

  • The?:Operator

    Youcanusethe?:operatorasareplacementforanifelsestatement.Itsgeneralformisasfollows:

    Exp1?Exp2:Exp3;

    Exp1,Exp2,andExp3aretypesofexpressions.Makesurethatyoutakenoteoftheplacementofthecoloninthestatement.Keepinmindthatthevalueof?isdeterminedassuch:

    Exp1 is first assessed. If it is proven to be true,Exp2 is assessed next and it serves as the currentexpressionvalue.Ontheotherhand,ifExp1isproventobefalse,thenExp3isassessednextanditsvalueservesasthecurrentexpressionvalue.

  • Chapter8CLoopsIn case you have to execute a block of code a few times, you should execute the statementssequentially.Thismeans thatyouhave toexecute thefirststatement ina functionfirst,and then thesecond,andsoon.

    A loop statement allows you to execute a statement or a number of statements several times. Thefollowingisthegeneralformofaloopstatement:

    TheDifferentTypesofLoops

    WhileLoop

    Thewhilelooprepeatedlyexecutesaparticularstatementifthegivenconditionistrue.

    Syntax

    Thegeneralsyntaxofawhileloopisasfollows:

    while(condition)

    {

    statement(s);

  • }You can use a single statement or a block of statements in a while loop. Also, you can give aconditionofanyexpression,butnon-zerovaluesareconsideredtrue.Aslongastheconditionistrue,theloopcontinuestoiterate.Oncetheconditionbecomesfalse,theprogramcontrolpassestothelinethatimmediatelyfollowstheloop.

    FlowDiagram

    Iftheconditionofthewhileloopistestedandfoundtobefalse,thenthefirststatementafterthewhileloopisexecutedwhiletheloopbodyisskipped.

    Example:

    #include

    intmain()

    {

    /*localvariabledefinition*/

    intx=10;

    /*whileloopexecution*/

  • while(x