Top Banner

of 99

Unit 1 Introduction to C Final

Jun 01, 2018

Download

Documents

Jaffer Raza
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/9/2019 Unit 1 Introduction to C Final

    1/99

    C Programming

    Introduction

    1

  • 8/9/2019 Unit 1 Introduction to C Final

    2/99

    High-level Computer Languagesand Their Inventors

    FORTRAN John W. Backus, 1954 BASIC George e!en" an# To! ur$%, 19&4

    'asca( N)co(as W)r$h C *enn)s +. R)$ch)e C B-arne S$rous$ru Ja/a Ja!es Gos()ng C0 An#ers e-(s2erg

    2

  • 8/9/2019 Unit 1 Introduction to C Final

    3/99

    Programming LanguagePopularity

    http://langpop.com/

    3

    http://langpop.com/http://langpop.com/
  • 8/9/2019 Unit 1 Introduction to C Final

    4/99

    TIOB Programming CommunityInde! "or #ugust$ %&'&

    http://(((.tio)e.com/inde!.php/content/paperin"o/tpci/inde!.html

    4

    http://www.tiobe.com/index.php/content/paperinfo/tpci/index.htmlhttp://www.tiobe.com/index.php/content/paperinfo/tpci/index.htmlhttp://www.tiobe.com/index.php/content/paperinfo/tpci/index.htmlhttp://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
  • 8/9/2019 Unit 1 Introduction to C Final

    5/99

    '& *easons to Learn Chttp://iel.ucdavis.edu/pu)lication/+hyC.htm

    l 1. C is one of foundations for modern information technology andcomputer science.

    2. C is the most commonly used programming language in industry.3. C is a standardized programming language with international

    standards.4. Writing computer programs is essential to sol ing comple!science and engineering pro"lems.

    #. Computer programming is "ecoming a necessary s$ill for manyprofessions.

    %. Computer programming can de elop student&s critical thin$ingcapa"ilities.

    '. C is one of the most commonly used programming languages incolleges and uni ersities.

    (. C is the language of choice for programming em"edded andmechatronic systems with hardware interface.

    ). C e!cels as a model programming language.1*. +nce you ha e learned C, you can pic$ up other languages

    without much di-culty "y yourself "ecause all other modernlanguages "orrowed hea ily from C.

    #

    http://iel.ucdavis.edu/publication/WhyC.htmlhttp://iel.ucdavis.edu/publication/WhyC.htmlhttp://iel.ucdavis.edu/publication/WhyC.htmlhttp://iel.ucdavis.edu/publication/WhyC.html
  • 8/9/2019 Unit 1 Introduction to C Final

    6/99

    History o" C3 C

    In ented "y itchie "ased on /, a simpli0ed ersion of

    /CP . sed to de elop ni! operating system and ni!

    commands. ost system software such as + are written in C or C55. eplacement for assem"ly language for hardware

    interface.

    /y late 1)'*&s C had e ol ed to 67 8 C6.

    3 C ,tandards 1 st C standard created in 1)() "y 9: I, rati0ed "y I + in

    1))*. It is called C(). ome call it C)*.

    2 nd C standard was rati0ed in 1))), called C)). :umerical e!tensions such as comple! num"ers, aria"le length

    arrays, and I;;; or enhancementin C)). C)) will "e pointed out whene er features in C)) only arepresented.

    ?he current C standard, which has "een informally namedC11, was rati0ed in 2*11. @+ur compiler supports some, %

  • 8/9/2019 Unit 1 Introduction to C Final

    7/99

    3 Deitel & Deitel provide a C Programming Resource Center thathas links to multiple resources, including the C99 standard.

    http://www.deitel.com/ResourceCenters/Programming/C/tabid/199/Default.aspx

    3 Other useful sites include

    !he "#$% C $tandard i'rar(

    http ))***.csse.u*a.edu.au)programming)ansic+li'rar(.html

    !he C i'rar( Reference uide -'( ric /uss0, *hich provides protot(pes and information a'out most C functions

    http ))***.acm.uiuc.edu)*e'monke(s)'ook)c1guide )

    ,ome *esource Lin s

    http://www.deitel.com/ResourceCenters/Programming/C/tabid/199/Default.aspxhttp://www.deitel.com/ResourceCenters/Programming/C/tabid/199/Default.aspxhttp://www.csse.uwa.edu.au/programming/ansic-library.htmlhttp://www.acm.uiuc.edu/webmonkeys/book/c_guide/http://www.acm.uiuc.edu/webmonkeys/book/c_guide/http://www.acm.uiuc.edu/webmonkeys/book/c_guide/http://www.csse.uwa.edu.au/programming/ansic-library.htmlhttp://www.csse.uwa.edu.au/programming/ansic-library.htmlhttp://www.deitel.com/ResourceCenters/Programming/C/tabid/199/Default.aspxhttp://www.deitel.com/ResourceCenters/Programming/C/tabid/199/Default.aspx
  • 8/9/2019 Unit 1 Introduction to C Final

    8/99

    Phases o" Compilation-Based!ecution o" a C Program

    1. Edit

    2. Preprocess3. Compile

    4. Link

    5. Load

    6. Execute

    (

  • 8/9/2019 Unit 1 Introduction to C Final

    9/99

    Phases o" Compilation-Based!ecution o" a C Program --

    dit3 !his is accomplished *ith an editor program .3 $oft*are packages for the C)C22 integrated program

    development environments such as clipse and3icrosoft 4isual $tudio have editors that areintegrated into the programming environment.

    3 C programs are t(ped in *ith the editor, correctionsare made if necessar(, and the program is stored on asecondar( storage device such as a hard disk.

    3 C program file names should end *ith the .c e5tension.

    )

  • 8/9/2019 Unit 1 Introduction to C Final

    10/99

    Phases o" Compilation-Based!ecution o" a C Program --

    Preprocessing3 %n a C s(stem, a preprocessor e5ecutes automaticall(

    'efore the compiler6s translation phase 'egins.

    3 !he C preprocessor o'e(s special commands called preprocessor directives , *hich indicate that certainmanipulations are to 'e performed on the program 'eforecompilation.

    1*

  • 8/9/2019 Unit 1 Introduction to C Final

    11/99

    Phases o" Compilation-Based!ecution o" a C Program --

    Preprocessing3 !hese manipulations usuall( consist of including other files inthe file to 'e compiled, performing various te5t replacements,defining various macros, etc..

    3 References: %n Deitel & Deitel, the( are discussed in Chapter 78, p 7:.

    3 Examples include:

    #include

    #define

    11

  • 8/9/2019 Unit 1 Introduction to C Final

    12/99

    Phases o" Compilation-Based!ecution o" a C Program --

    Preprocessing3 %n $tep 8, the compiler translates the C source code -afterthe preprocessing steps have 'een done0 into object codeand stores it on the disk. O';ect code is essentiall( machine code, a series of 76s and

  • 8/9/2019 Unit 1 Introduction to C Final

    13/99

    Phases o" Compilation-Based!ecution o" a C Program --

    Lin ing3 " linker links the o';ect code *ith the code for

    the missing functions to produce an e5ecuta'leimage -*ith no missing pieces0.

    3 During linking, multiple o';ect files might 'ecom'ined into one e5ecuta'le.

    13

  • 8/9/2019 Unit 1 Introduction to C Final

    14/99

    Phases o" Compilation-Based!ecution o" a C Program

    Loading and !ecuting3 !he ne5t phase is called loading .3 >efore a program can 'e e5ecuted, the program must

    first 'e placed in memor(.3 !his is done '( the loader , *hich takes the e5ecuta'le

    image from disk and transfers it to memor(.3 "dditional components from shared li'raries that

    support the program are also loaded.3 ?inall(, the computer, under the control of its CP=,

    e5ecutes the program one instruction at a time.

    14

  • 8/9/2019 Unit 1 Introduction to C Final

    15/99

    1#

  • 8/9/2019 Unit 1 Introduction to C Final

    16/99

    1%

    !

  • 8/9/2019 Unit 1 Introduction to C Final

    17/99

    rom g = e e rogram o !ecu a eBile@from C55A

    1

  • 8/9/2019 Unit 1 Introduction to C Final

    18/99

    # ,imple C Program

    /* File: hello.cPrint Hello, world on the screen */

    #include

    int main!"

    printf!$Hello, world%n&"' return (') // end function main!"

    1(

  • 8/9/2019 Unit 1 Introduction to C Final

    19/99

    /* File: hello.cPrint Hello, world on the screen */

    #include #include

    int main!"

    printf!$Hello, world%n&"'

    s+stem !$pause "' return (') // end function main!"

    # ,imple C Program

    1)

  • 8/9/2019 Unit 1 Introduction to C Final

    20/99

    3 Comments

    ?e!t surrounded "y / and / is ignored "ycomputer

    sed to descri"e program

    3 0include 1stdio.h2 Preprocessing directi e = tells computer to

    load contents of a header 0le

    1stdio.h2 allows standard inputDoutput

    /* File: hello.cPrint Hello, world on the screen */

    #include

    int main!"

    printf!$Hello, world%n&"' return (')

    2*

  • 8/9/2019 Unit 1 Introduction to C Final

    21/99

    3 int main34 C programs contain one or more functions,

    e!actly one of which must "e main Parenthesis used to indicate a function int means that main EreturnsE an integer

    alue /races indicate a "loc$3 ?he "odies of all functions must "e

    contained in "races3 We will enforce this style with "races.

    /* File: hello.cPrint Hello, world on the screen */

    #include

    int main!"

    printf!$Hello, world%n&"' return (')

    21

  • 8/9/2019 Unit 1 Introduction to C Final

    22/99

    3 print"3 5hello$ (orld6n7 48 Instructs computer to perform an action

    3 peci0cally, prints string of characterswithin Fuotes

    ;ntire line called a statement3 #ll statements must end (ith asemicolon.

    6 = escape character3 Indicates that print" should do

    something out of the ordinary.3 6n is the newline character.

    /* File: hello.cPrint Hello, world on the screen */

    #include

    int main!"

    printf!$Hello, world%n&"' return (')

    22

  • 8/9/2019 Unit 1 Introduction to C Final

    23/99

    /* File: hello.cPrint Hello, world on the screen */

    #include

    int main!"

    printf!$Hello, world%n&"' return (')

    3 return &8 9 way to e!it a function.

    return & , in this case, means that the programterminated normally.

    ?he returned alue of * is displayed in the e!it status

    in ChIG;.

    3 *ight )race 9 Indicates end of main has "een reached.

    23

  • 8/9/2019 Unit 1 Introduction to C Final

    24/99

    ,tructure o" a C Program

    24

  • 8/9/2019 Unit 1 Introduction to C Final

    25/99

    Preprocessorirectives

    ;lo)aleclarationsaria"les

    function prototypesint main !"

    )

    ocal declarations

    tatements

    -ther functions...

    oid xxx!"

    )

    oid xxx!"

    )

    2#

  • 8/9/2019 Unit 1 Introduction to C Final

    26/99

    Preprocessorirectives

    ;lo)aleclarations

    aria"les

    int main !"

    )

    ocal declarations

    tatements

    -ther functions...

    oid xxx!"

    )

    oid xxx!"

    )

    2%

  • 8/9/2019 Unit 1 Introduction to C Final

    27/99

    2'

  • 8/9/2019 Unit 1 Introduction to C Final

    28/99

    2(

  • 8/9/2019 Unit 1 Introduction to C Final

    29/99

    ,ome Common rrors3even (ith simple programs 4

    3 %t6s helpful to get to kno* (our compiler and the errorsit produces under various conditions.

    3issing statement terminators %nvalid preprocessor directives 3issing program 'lock identifiers

    %nvalid escape se@uences -possi'le *arning0 %nvalid comment 'locks 3issing function protot(pes

    2)

  • 8/9/2019 Unit 1 Introduction to C Final

    30/99

    ata Types in C3 =nlike Aava, C contains onl( four standard data t(pes void ,

    c ar , inte!er t"pes , and #loatin! point t"pes .

    3 "s *e *ill see, the siBe of these data t(pes is machine and s(stemdependent.

    3 $ince *e sometimes need to kno* the siBe of a data t(pe atruntime, C provides an operator, si eof!" , that *ill return thesiBe of an( data t(pe in '(tes.

    3 5ample

    /* x will contain 0 on most s+stems */int x 1 si eof !int"'

    3*

  • 8/9/2019 Unit 1 Introduction to C Final

    31/99

    ata Types in C

    3 =nlike Aava, C contains onl( four standard data t(pes void ,c ar , inte!er t"pes , and #loatin! point t"pes .

    3 void hen used as a return value from a function, indicates

    that nothing is returned.3 char

    =suall( a single '(te. =suall( represents a value from the "$C%% ta'le.

    Can also 'e interpreted as a small signed integer -'et*een +7 E and7 :0.

    Declared using the char ke(*ord. Character literals al*a(s in single @uotes.

    31

  • 8/9/2019 Unit 1 Introduction to C Final

    32/99

    #,CII Ta)le

    32

  • 8/9/2019 Unit 1 Introduction to C Final

    33/99

    ata Types in C3 int %nteger data t(pe. Comes in different flavors,

    depending on the modifiers - short or lon2 , si2ned orunsi2ned 0

    33

  • 8/9/2019 Unit 1 Introduction to C Final

    34/99

    ata Types in C3 int %nteger data t(pe.

    3 #ote that unsigned integers can store positive num'ersappro5imatel( t*ice as large as the signed integer of thesame t(pe.

    3 "#$% standard re@uires thatsiBeof -short int0 FG siBeof -int0 FG siBeof -long int0

    34

  • 8/9/2019 Unit 1 Introduction to C Final

    35/99

    ata Types in C

    3 float ?loating point data t(pe. Comes in three siBes float , dou le , lon2 dou le .

    3 "#$% standard enforcessiBeof -float0 FG siBeof -dou'le0 FG siBeof -long dou'le0

    3#

  • 8/9/2019 Unit 1 Introduction to C Final

    36/99

    ata Types in C -- ,ummary

    3%

    P d < d C t t "

  • 8/9/2019 Unit 1 Introduction to C Final

    37/99

    Prede

  • 8/9/2019 Unit 1 Introduction to C Final

    38/99

    Prede

  • 8/9/2019 Unit 1 Introduction to C Final

    39/99

    3 A valid identifier in C can consist of

    letters -'oth lo*er and upper case0 underscores -10 digits

    3 Notes:

    !he first character must not 'e a digit. %n the "#$% C standard, an identifier can 'e of an( length, 'ut the

    compiler *ill onl( look at the first 87 characters. "n identifier cannot duplicate a reserved *ord.

    3 Further Notes: #ote that, in contrast to Aava, HI6 is not a valid character in a C

    identifier. ike Aava and C22, C is case sensitive. =se of leading underscores is discouraged for general use.

    =alid Identi

  • 8/9/2019 Unit 1 Introduction to C Final

    40/99

    3 Variables are named locations in memory that containa alue.

    3 Haria"le declarations are made in C >ust li$e in a a. < aria le name>'

    int num-f;tudents'float numHoursAorBed'

    3 9nd of course, aria"les can "e declared and initializedin the same statementJint num-f;tudents 1 CC'float numHoursAorBed 1 DC.CF'

    3 ater we will see that we can de0ne and declare ourown data types.3 In the earlier 9: I C standard, all declarations in afunction must precede any e!ecuta"le statements. ?his was changed in C)), which allows aria"les to "e declared

    anywhere inside a function. If you chec$, youKll 0nd that Hisual C55 2*1* and earlier does

    not implement C)) in this regard, "ut H 2*13 does.

    =aria)le eclarations

    4*

  • 8/9/2019 Unit 1 Introduction to C Final

    41/99

    =aria)le eclarations3 ,ome good rules "or varia)le names J

    se either capitalization or underscores to create multi=wordidenti0ers. 9""re iations should "e long enough to clearly indicate what is

    "eing a""re iated. 9 oid the use of generic names. GonKt create se eral aria"le names that diLer only "y one or

    two characters.

    41

  • 8/9/2019 Unit 1 Introduction to C Final

    42/99

    ata Types in Ci>erences (ith ?ava

    3 #ote that there is no 'oolean data t(pe in C. >oolean evaluations are done through integers -a < represents false, a

    non+Bero value represents true0.

    3 !here is no $tring class in C -or its e@uivalent0. $trings in C are represented as arra(s of characters terminated '( a

    null -J

  • 8/9/2019 Unit 1 Introduction to C Final

    43/99

    Constants3

    Constants are values that cannot 'e changed duringthe e5ecution of a program.

    3 e6ll consider three t(pes of constants

    literals Ldefine preprocessor directives =se of the const declaration on a varia'le.

    43

  • 8/9/2019 Unit 1 Introduction to C Final

    44/99

    iterals3 "s *e kno*, a variable is a named storage location in

    the computer6s memor(.

    3 " literal , on the other hand, is a constant value that ishard coded into the program. %t is not associated *ith a named location in memor(. !he value does not change.

    3 Character literals are enclosed in single @uotes a , %n , %( !4 " char ch 1 a ' -#ote that the escape characters, like %n or % , are considered

    single characters -even though it takes t*o characters to *rite them0.0

    44

  • 8/9/2019 Unit 1 Introduction to C Final

    45/99

    iterals3 Integer literals are num'ers *ithout decimal values.

    C, ED , Gint x 1 C'

    >( default, an integer literal is considered a-n0 I .

    3 Floating point literals are num'ers *ith decimalvalues.D.J0JCKfloat pi 1 D.J0JCK' // =ompiler warnin2

    float pi 1 D.J0JCKF' // 4o compiler warnin2 >( default, a floating point literal is considered a-n0 I .

    4#

  • 8/9/2019 Unit 1 Introduction to C Final

    46/99

    iterals3 Integer literals are num'ers *ithout decimal values.

    C, ED , Gint x 1 C'

    >( default, an integer literal is considered an int .

    3 Floating point literals are num'ers *ith decimalvalues.D.J0JCKfloat pi 1 D.J0JCK' // =ompiler warnin2

    float pi 1 D.J0JCKF' // 4o compiler warnin2 >( default, a floating point literal is considered a dou le .

    4%

    it l

  • 8/9/2019 Unit 1 Introduction to C Final

    47/99

    iterals3 String literals are character strings in dou'le @uotes.

    $Hello Aorld$h$

    3 !here is no strin2 -or ;trin2 0 class in C.

    3 $trings in C are arra(s of characters terminated '( a #= . !he( are operated on '( functions that receive the string as an input

    parameter.

    3 5ample !here is no string concatenation operator in C -H260.

    3 !o concatenate t*o strings use the strcat -char M, char M0 function in Fstring.hN.

    ;u5taposition of strings *ill *ork *ith string literals printf -/i there0*ill print /i there

    4'

    it l

  • 8/9/2019 Unit 1 Introduction to C Final

    48/99

    3 String Declarations3 $trings can 'e declared *ith statements like the follo*ing

    char strLM 1 $Hello 'char *str 1 $Hello '

    3 ith declarations like this, C creates a character arra( asfollo*s

    !he varia'le str is a charM that points to the first element in the arra(.

    !he HJ

  • 8/9/2019 Unit 1 Introduction to C Final

    49/99

    Preprocessor Constants#define

    3 #define constants are macros that replace theFidentifierN *ith the te5t that follo*s 3odel #define

    5am #define ;8 N;65896 85N (.(OEC

    3 !he preprocessor performs a simple te5t replacementthroughout the file 'efore it is sent to the compiler.

    3 #o varia'le is created, no memor( is allocated.

    4)

    P C

  • 8/9/2019 Unit 1 Introduction to C Final

    50/99

    Preprocessor Constants#define

    3 !he header file Fmath.hN contains man( predefinedconstants that *e can use -e.g., 31P%, 31 , ...0.

    3 /o*ever, to use them in 4isual C22, *e must includethe follo*ing preprocessor directive in our filesbe#ore *e include Fmath.hN

    #define 6 ;N6785H6?NF34N;

    #*

    H i "l C t t

  • 8/9/2019 Unit 1 Introduction to C Final

    51/99

    Haria"le Constants3 !he final *a( of declaring a constant is '( declaring a varia'le

    constantconst int 9 1 EC'const float P3 1 D.J0JCKF'

    3 !his declaration does create a varia'le in memor(, 'ut the const modifier tells C that its value cannot 'e changed.

    3 Notes !he modifier const comes 'efore the data t(pe.

    !he varia'le must 'e initialiBed to 'e used effectivel(. %f not, its value*ill 'e *hatever is in memor( *hen the declaration is e5ecuted.

    3 Note this is different from C22, *hich re@uires const varia'les to 'einitialiBed *hen the( are declared. %n C, no compile error if not initialiBed.

    Once created, the value cannot 'e changed.#1

  • 8/9/2019 Unit 1 Introduction to C Final

    52/99

    Bormatted Input and+utput

    3 e6ll introduce our primar( input and outputstatements

    printf!"

    scanf!"

    #2

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    53/99

    Bormatted Input and +utputprintf!"

    3 Function printf()3 Precisel( formatted output can 'e accomplished using the output function

    printf!" .

    3 !he printf() function is defined in Fstdio.hN.

    3 !he printf() function has the follo*ing formatprintf! formatGcontrolGstrin2, ar2uments "'

    ?ormat+control+string3 "l*a(s enclosed in dou'le @uotation marks.3 =ses format specifications to descri'e output format. ach specification 'egins *ith

    a percent sign - 0 and ends *ith a conversion specifier.3 scape se@uences can also 'e em'edded in the format string.

    arguments3 are matched *ith the conversion specifiers in the format+control+string in 'oth t(pe

    and num'er. !he matching is done left+to+right.

    #3

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    54/99

    Bormatted Input and +utputprintf!"

    3 Conversion Specifiers3 ?ollo* the template

    con ersionGcode

    3 lements that are in angle 'rackets -F N0 are optional.3 Conversion code

    !here are a'out 8< of these, 'ut *e are onl( concerned *ith a fe*. $ee chart ne5t page.

    #4

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    55/99

    Bormatted Input and +utputprintf!"

    3 Some common printf() conversion codes"rgument !(pe Conversion Code in the

    ?ormat+Control+$tringchar c

    signed char, short, int dunsigned char, short, int u

    octal num'er o

    he5adecimal num'er 5, Q

    float f

    dou'le f or lf

    string s

    pointer p##

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    56/99

    Bormatted Input and +utputprintf!"

    3 printf() conversion codesConversion Code ata Type

    Mc Char

    Ms tring

    Md igned IntegerMu nsigned integer

    Mf Bloat

    Mlf Gou"le

    M f ong Gou"le

    Mp Pointer alue

    M!, MN e!adecimal alue@lettersA

    Mo +ctal Halue

    Me, M; cienti0c notation#%

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    57/99

    Bormatted Input and +utputprintf!"

    3 Conversion Specifiers3 ?ollo* the template con ersionGcode

    3

    Consists of the letters Hh6 -short0, Hl6 -long0, or H 6 -long0. Onl( applies to short int , lon2 int , lon2 lon2 int , and lon2 dou le

    data t(pes.

    #'

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    58/99

    Bormatted Input and +utputprintf!"

    3 Conversion Specifiers3 ?ollo* the template con ersionGcode

    3

    =sed to specif( the minimum num'er of positions in the output. -4er( useful *hen printing in columns.0

    Default is right ;ustified *ithin the field specified -use minus sign flag to left ;ustif(0. printf!" *ill override the *idth specified if the output is larger.

    int x 1 EC'

    printf !$ Cd , x"'

    printf !$ GCd , x"'

    printf !$ (Cd , x"'

    EC

    EC

    (((EC

    #(

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    59/99

    Bormatted Input and +utputprintf!"

    3 Conversion Specifiers3 ?ollo* the template con ersionGcode

    3

    =sed onl( *ith floating point data t(pes. =sed to specif( the precision -num'er of decimal places0 in the output.

    float x 1 EC.DC F'

    printf !$ f , x"'

    printf !$ K.Ef , x"'

    printf !$ GK.Ef , x"'

    EC.DC (J

    EC.D

    EC.D

    #)

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    60/99

    Bormatted Input and +utputprintf!"

    3 Conversion Specifiers3 ?ollo* the template con ersionGcode

    3

    3ost common flags are H26, H+6, H

  • 8/9/2019 Unit 1 Introduction to C Final

    61/99

    Bormatted Input and +utputprintf!"

    3 Escape sequences

    %1

  • 8/9/2019 Unit 1 Introduction to C Final

    62/99

    %2

  • 8/9/2019 Unit 1 Introduction to C Final

    63/99

    %3

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    64/99

    Bormatted Input and +utputscanf!"

    3 scanf () is the standard input function for C.3 4er( precise input formatting can 'e accomplished *ith

    scanf!" .

    3 ?unction scanf!" has the follo*ing input formatting capa'ilities-not e5clusive0

    3 %nputting all t(pes of data.3 %nputting specific characters from an input stream.3 $kipping specific characters in the input stream.3 %nputting onl( those characters *e specif(.3 $kipping onl( those characters *e specif(.3 $pecif(ing the num'er of characters to 'e input.

    %4

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    65/99

    Bormatted Input and utputscanf!"

    3 ike printf!" , the first argument in a call to scanf!" is a formatting

    string *hich can contain conversion specifiers. /o*ever, the list ofsu'se@uent arguments is no* a list of addresses , rather than varia'les orconstants.

    int i' float x'scanf !$ d f , Ri, Rx"'

    %#

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    66/99

    p pscanf!"

    3 !he conversion specifiers in scanf -0 are ver( similar -*ith afe* e5ceptions0 to those used in printf -0.

    %%

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    67/99

    p pscanf!"

    %'

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    68/99

    scanf!"

    %(

    B tt d I t d + t t

  • 8/9/2019 Unit 1 Introduction to C Final

    69/99

    3 #ote that conversion specifier %i is capa'le ofinputting decimal, octal and he5adecimalintegers *ith one specifier.

    3 hich one is inputted depends on the formatof the input a leading

  • 8/9/2019 Unit 1 Introduction to C Final

    70/99

    '*

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    71/99

    3 hen inputting floating+point num'ers, an( of thefloating+point conversion specifiers e , E, f , g or can 'e used.

    3 !he follo*ing program reads three floating+pointnum'ers, one *ith each of the three t(pes offloating conversion specifiers, and displa(s all threenum'ers *ith conversion specifier f .

    3 !he program output confirms the fact that floating+ point values are imprecise this is highlighted '(the third value printed.

    Bormatted Input and +utputscanf!"

    '1

  • 8/9/2019 Unit 1 Introduction to C Final

    72/99

    '2

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    73/99

    3 Characters and strings are input using the conversion specifiersc and s , respectivel(.

    3 !he ne5t program prompts the user to enter a string.

    3 !he program then inputs the first character of the string *ith %c and stores it in the character varia'le x , then inputs theremainder of the string *ith %s and stores it in character arra(! .

    3 #ote that the s conversion specifier automaticall( appends a #= to the end of the string.

    %t is up to the programmer to make sure there is enough room in thecharacter arra( for all of the characters, including the #= KK

    Bormatted Input and +utputscanf!"

    '3

  • 8/9/2019 Unit 1 Introduction to C Final

    74/99

    3 Note !he name of a string is considered a charM. !hus, no addressoperator is re@uired in a scanf-0 that reads a string.

    3 Note !he string is read from the input a #= -HJ

  • 8/9/2019 Unit 1 Introduction to C Final

    75/99

    3 " se@uence of characters can 'e input using a scan set .3 " scan set is a set of characters enclosed in s@uare 'rackets,

    "# , and preceded '( a percent sign in the format controlstring.

    3 " scan set scans the characters in the input stream, lookingonl( for those characters that match characters contained inthe scan set.

    3 ach time a character is matched, it is stored in the scan set6scorresponding argument a pointer to a character arra(.

    3 !he scan set stops inputting characters *hen a character thatis not contained in the scan set is encountered.

    Bormatted Input and +utputscanf!"

    '#

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    76/99

    3 %f the first character in the input stream does notmatch a character in the scan set, onl( the nullcharacter is stored in the arra(.

    3 !he ne5t program uses the scan set "aeiou# toscan the input stream for vo*els.3 #otice that the first seven letters of the input are

    read.3 !he eighth letter - h0 is not in the scan set and

    therefore the scanning is terminated.

    Bormatted Input and +utputscanf!"

    '%

  • 8/9/2019 Unit 1 Introduction to C Final

    77/99

    ''

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    78/99

    3 !he scan set can also 'e used to scan for characters notcontained in the scan set '( using an inverted scan set .

    3 !o create an inverted scan set, place a caret -S0 in the s@uare 'rackets 'efore the scan characters.

    3 !his causes characters not appearing in the scan set to 'estored.

    3 hen a character contained in the inverted scan set isencountered, input scanning is terminated.

    3 !he ne5t program uses the inverted scan set "$aeiou# tosearch for consonants more properl( to search fornonvo*els.

    Bormatted Input and +utputscanf!"

    '(

  • 8/9/2019 Unit 1 Introduction to C Final

    79/99

    ')

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    80/99

    3 " field *idth can 'e used in a scanf conversionspecifier to limit the num'er of characters that are readfrom the input stream.

    3 #ote that tokens are separated '( *hitespace. hen the*idth is specified, scanf-0 *ill read until -a0 a *hitespacecharacter is encountered, or -'0 the ma5imum num'er ofcharacters have 'een entered.

    3 ?igure 9. 8 inputs a series of consecutive digits as a t*o+digit integer and an integer consisting of the remainingdigits in the input stream.

    Bormatted Input and +utputscanf!"

    (*

  • 8/9/2019 Unit 1 Introduction to C Final

    81/99

    (1

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    82/99

    3 Often it6s necessar( to skip certain characters in the inputstream.

    3 ?or e5ample, a date could 'e entered as

    3 11 1& 19993 ach num'er in the date needs to 'e stored, 'ut the dashes

    that separate the num'ers can 'e discarded.

    3 !o eliminate unnecessar( characters, include them in theformat control string of scanf -*hite+space characters such as space, ne*line and ta' skip all leading *hite+space0.

    Bormatted Input and +utputscanf!"

    (2

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    83/99

    3 ?or e5ample, to skip the dashes in the input, use thestatement

    3 scanf' "%d-%d-%d" , &month, &day, &year );

    3 "lthough, this scanf does eliminate the dashes in the preceding input, it6s possi'le that the date could 'eentered as

    3 1&/11/1999

    3%n this case, the preceding scanf *ould not eliminatethe unnecessar( characters.

    3 ?or this reason, scanf provides the assignmentsuppression character ) .

    Bormatted Input and +utputscanf!"

    (3

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    84/99

    3 !he assignment suppression character ena'les scanf to read an(t(pe of data from the input and discard it *ithout assigning it to avaria'le.

    3 !he ne5t program uses the assignment suppression character inthe %c conversion specifier to indicate that a character appearingin the input stream should 'e read and discarded.

    3 Onl( the month, da( and (ear are stored.3 !he values of the varia'les are printed to demonstrate that the(

    are in fact input correctl(.

    3 !he argument lists for each scanf call do not contain varia'lesfor the conversion specifiers that use the assignment suppressioncharacter.

    3 !he corresponding characters are simpl( discarded.

    Bormatted Input and +utputscanf!"

    (4

  • 8/9/2019 Unit 1 Introduction to C Final

    85/99

    (#

    Bormatted Input and +utput

  • 8/9/2019 Unit 1 Introduction to C Final

    86/99

    3 ith the e5ception of the character format code - c0,scanf-0 ignores leading *hitespace.3 %f scanf-0 encounters an invalid character *hen it is tr(ing

    to convert the input to the stored data t(pe, the scanning

    stops. " common e5ample of this pro'lem encountering a non+numeric character *hen reading a num'er.

    3 "n( character in the format string other than a *hitespace

    or a conversion specifier must 'e matched '( the userduring input. %f the input stream does not match the characters in the format

    string, scanf-0 stops.

    p pscanf!" O ummary :otes

    (%

    Conversion Specifiersi f() d f()

  • 8/9/2019 Unit 1 Introduction to C Final

    87/99

    printf() and scanf()

    ('

    ata Types in C

  • 8/9/2019 Unit 1 Introduction to C Final

    88/99

    ypPointers

    3 Pointers are varia'les *hose values are memor(addresses -Deitel, ::0. #ormall(, a varia'le directl( contains a specific value. " pointer, on the other hand, contains an address of a varia'le

    that contains a specific value.3 %n this sense, a varia'le name directl( references a value,

    and a pointer indirectl( references a value.

    3 Referencing a value through a pointer is calledindirection .

    ((

    ata Types in C

  • 8/9/2019 Unit 1 Introduction to C Final

    89/99

    ypPointers

    3 Pointers, like all varia'les, must 'e defined 'efore the( can 'e used.

    3 e define a pointer '( using an asterisk 'efore the varia'lename. !hus, the definition

    3 int *countPtr, count;specifies that varia'le countPtr is of t(pe int ) -i.e., a

    pointer to an integer0. #ote that the M onl( applies to countPtr in this definition. !he

    varia'le count is still ;ust a plain integer.

    3 hen ) is used in this manner in a definition, it indicatesthat the varia'le 'eing defined is a pointer.

    3 Pointers can 'e defined to point to o';ects of an( t(pe.

    ()

    ata Types in C

  • 8/9/2019 Unit 1 Introduction to C Final

    90/99

    ypPointers

    3 Pointers are varia'les *hose values are memor(addresses.

    int count'int *countPtr 1 Rcount:

    )*

    ata Types in C

  • 8/9/2019 Unit 1 Introduction to C Final

    91/99

    ypPointers

    3 !he * , or address operator , is a unar( operator that returnsthe address of its operand.3 ?or e5ample, assuming the definitions

    3 int y = 5;int *yPtr;

    the statement3 !Ptr + *!,

    assigns the address of the varia'le ! to pointer varia'le!Ptr .

    3 4aria'le !Ptr is then said to point to ! .3 !he ne5t slide sho*s a schematic representation of memor(

    after the preceding assignment is e5ecuted.

    )1

    ata Types in C

  • 8/9/2019 Unit 1 Introduction to C Final

    92/99

    ypPointers

    3 "gain, assuming the definitions3 int y = 5;int *yPtr;

    the statement3 !Ptr + *!,

    assigns the address of the varia'le ! to pointer varia'le!Ptr -Deitel0.

    )2

    ata Types in C

  • 8/9/2019 Unit 1 Introduction to C Final

    93/99

    Pointers

    3 et6s assume that the integer varia'le ( is stored atlocation T

  • 8/9/2019 Unit 1 Introduction to C Final

    94/99

    Pointers

    3 hen the unar( ) operator, commonl( referred to asthe indirection operator or dereferencing operator , isapplied to a varia'le outside of a declaration, itreturns the value of the o';ect to *hich its operand

    -i.e., a pointer0 points.3 ?or e5ample, the statement

    3 printf' "%d" , *yPtr );

    prints the value of varia'le ! , namel( .3 =sing ) in this manner is called dereferencing a

    pointer .)4

    ata Types in C

  • 8/9/2019 Unit 1 Introduction to C Final

    95/99

    Pointers

    3 !he ne5t figure demonstrates the pointer operators * and ) .

    3 !he printf conversion specifier %p outputs the memor(location as a he5adecimal integer on most platforms.

    3 #otice that the address of a and the value of aPtr areidentical in the output, thus confirming that the address of a is indeed assigned to the pointer varia'le aPtr -line 770.

    3 !he * and ) operators are complements of one another *hen the(6re 'oth applied consecutivel( to aPtr in eitherorder -line 70, the same result is printed.

    )#

  • 8/9/2019 Unit 1 Introduction to C Final

    96/99

    )%

    ata Types in C

  • 8/9/2019 Unit 1 Introduction to C Final

    97/99

    Pointers

    )'

  • 8/9/2019 Unit 1 Introduction to C Final

    98/99

    )(

    ata Types in C

  • 8/9/2019 Unit 1 Introduction to C Final

    99/99

    Pointers -- ,ummary

    3 Pointers are declared using the asterisk -HM60 in adeclaration

    int *xPtr'float *fltPtr'

    3 Pointers are dereferenced using the asterisk -HM60 onan e5isting varia'le in an e5pression

    printf !$ d , *xPtr"'

    3 !he ampersand -H&60 is used to return the address ofan e5isting varia'le

    int '