Chapter 3 - Introduction to C

download Chapter 3 - Introduction to C

of 63

Transcript of Chapter 3 - Introduction to C

  • 7/28/2019 Chapter 3 - Introduction to C

    1/63

    ENG 054: COMPUTING

    ENGINEERING II

    Chapter 3 :

    Introduction to CProgramming

  • 7/28/2019 Chapter 3 - Introduction to C

    2/63

    Objectives :

    1. To understand the basic components of C

    program

    2. To introduce the concepts of

    - Data types

    - Identifiers : variables & constants

    - Arithmetic operators3. To introduce standard input & output function

    2

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    3/63

    Components of C Program

    C program have parts and components thatserve specific purposes

    BUT, the parts of C programs are not always inthe same place

    3

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    4/63

    Example of C Program

    4

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    5/63

    Output of C program

    5

    output

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    6/63

    Example :Write a program to calculate and display an areaof a cylinder side.

    Area of cylinder side is calculated using the

    following formula :-

    Area of cylinder = 2rh ; where

    r is the radius and h is the height.

    Your program will calculate the area of cylinderside based on the given input (i.e radius andheight) from the user.

    6

  • 7/28/2019 Chapter 3 - Introduction to C

    7/63

    Juliana Jaafar

    2011/2012

    7

    Structure of a C Program

    main() function

    //Written by: Rosmiza Wahida/*This program is to calculate the area

    of a cylinder*/

    #define pi 3.142

    float A_cyl;

    int main()

    {

    float radius, height;

    printf(Please enter radius: );

    scanf(%f,&radius);

    printf(Please enter height: );

    scanf(%f,&height);

    A_cyl = 2*pi*radius*height;

    printf(Area for the cylinder is

    %f , A_cyl);

    return 0;

    }

    Preprocessor directive

    Global declaration

    Local declaration

    Statements

    #include

    Comments

    ReturnStatement

    Function body

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    8/63

    Will be read first before the program is compiled

    Indicated bypound sign (#) together with keyword

    #include to include the contents of another file

    #define to define global variable/constant

    ** No space between # and include

    8

    Preprocessor Directive

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    9/63

    #include

    stdio.h

    Is the name of the file that is to be included.

    Dot h indicates the type of the file header file

    Allow C program to display output on the screen printf() and read input from the keyboard scanf()

    #define pi 3.142 pi - Name of constant

    3.142 value of the constant

    9

    Preprocessor Directive

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    10/63

    main() function

    C Program can have one or more functions, exactly oneMUST be main() function

    int main()

    int stands for Integer. It indicates that the function

    sends an integer back to operating system when it is finishedexecuting

    main() the name of the function

    MUST be followed by set of braces ({ }) indicates a

    block, the beginning and ending of a function

    All statements (function body) that make up a function areenclosed in a set of braces

    10

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    11/63

    Comments

    Use : to document programs and improveprogram readability

    Help other people read and understand othersprogram

    IGNORED by C compiler and DO NOT causeany machine-language object code to begenerated.

    DO NOT cause the computer to perform anyaction when the program is run.

    CAN be put ANYWHERE in the program

    11

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    12/63

    Comments

    Two format Line comment

    Marked by two slashes (//) at the beginning of comment

    For short comment in a single line

    Example://Written by : Rosmiza Wahida

    Block comment Marked by opening token(/*) and closing token (*/)

    For long comment

    Example :/*This program is to calculate the area of a cylinder*/

    Comments CANNOT be nested (comments insidecomments)

    12

    J uliana J aafarCSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    13/63

    Function Body

    Enclosed by a set of braces ({ }) Function contains

    Local declaration

    Declaration of data that will be used for the function/program

    Example :float radius, height;

    Statements @ Program body

    Set of instructions of what the function/program should do

    Return Statement

    Return value that sends back to operating system Example :

    return 0;

    ** 0 usually indicates that a program executes successfully

    13

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

  • 7/28/2019 Chapter 3 - Introduction to C

    14/63

    Common Programming Language

    Elements Syntax

    Rules that must be followed when constructing a

    program Lines

    A line is a single line appear in the body ofprogram

    Statement A complete instruction that causes the computer

    to perform some action

    14

    J uliana J aafar

    CSC 099 Semester 2 2011/2012J uliana J aafCSC 099 Semester 2 2011/201

  • 7/28/2019 Chapter 3 - Introduction to C

    15/63

    Common Programming Language

    Elements Keywords (Reserve Words)

    Words that have special meaning and used forintended purpose

    Programmer-Defined Identifier (Identifier) Words/names defined by programmer. Symbolic

    names refer to variables or functions

    Operators

    Operator perform operations on one or more operands Punctuations

    Punctuation characters mark the beginning or endingof a statement, or separate item in a list

    15

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    16

  • 7/28/2019 Chapter 3 - Introduction to C

    16/63

    Punctuations

    Comma (,) use to separate item in a list Use to separate item in a list

    Example :

    float radius, height;

    Semicolon (;)

    Use at the end of a complete instruction

    Example :

    float radius, height;printf(Please enter radius: );

    A_cyl = 2*pi*radius*height;

    return 0;

    16

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    17

  • 7/28/2019 Chapter 3 - Introduction to C

    17/63

    Reserve Word/Keyword

    Special words reserve for C Program which havespecific meaning and purpose

    CANNOT be used as identifiers or variable name

    Appear in lower case

    17

    C and C++ Reserved Words

    autobreakcase

    charconst

    continuedefault

    dodoubleelse

    enumexternfloatfor

    gotoifint

    longregisterreturnshort

    signedsizeofstaticstructswitchtypedef

    unionunsigned

    voidvolatilewhile

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    18

  • 7/28/2019 Chapter 3 - Introduction to C

    18/63

    Identifiers

    Allows programmers to NAME data and otherobjects in the program

    variable, constant, function etc.

    Rules in naming identifiers

    MUST consist ONLY of alphabetic characters(uppercase or lower case), digits and underscores (_)

    First character MUST be alphabetic character orunderscore

    CANNOT contain spaces CANNOT duplicate with any reserved word

    ** C is CASE-SENSETIVE

    this means that NUM1, Num1, num1, and NuM1 are

    four completely different name.

    18

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    19

  • 7/28/2019 Chapter 3 - Introduction to C

    19/63

    Example of Valid & Invalid

    IdentifiersValid Identifiers Invalid Identifiers

    A

    student_name

    _aSystemName

    Pi

    Al

    stdntNm

    anthrSysNm

    PI

    $sum // $ is illegal

    2names // cant startwith 2

    stdnt Nmbr // cant havespace

    int // reserved word

    19

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    20

  • 7/28/2019 Chapter 3 - Introduction to C

    20/63

    Variables

    Variable names correspond to locations in thecomputer's memory

    Every variable has a NAME, a DATA TYPE, a SIZE

    and a VALUE A variable is created via a declaration where itsname and type are specified.

    Example :

    int integer1, integer2, sum; Whenever a new value is placed into a variable

    (through scanf(), for example), it replaces (anddestroys) the previous value

    20

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    21

  • 7/28/2019 Chapter 3 - Introduction to C

    21/63

    Variable Declaration

    Specifies in the memory to reserve a specific space forthe variable that have the specific location and can storespecific data type.

    MUST be declared before the executable of the statement

    Variable need to FIRST declare before it being used Syntax :

    data type variable name;

    Example

    int maxItems = 0;float payRate;

    double tax;

    char code;

    int a, b; // equivalent to int a; int b;

    21

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    22

  • 7/28/2019 Chapter 3 - Introduction to C

    22/63

    Example of Variable in Memory

    22

    long int

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    23

  • 7/28/2019 Chapter 3 - Introduction to C

    23/63

    Data Types

    Variables are classified according to their data type Determine the kind of information stored in variables

    Address, phone numbers, price, distance, and etc.

    Functions also have types which determine by the data it

    returns C Program have 5 standard data types:-

    void

    int

    Integer e.g. 1244,-87

    char

    Character e.g a, A

    double

    Floating-point e.g 0.5678, -3.25

    float : Floating-point (less precision)

    23

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    24

  • 7/28/2019 Chapter 3 - Introduction to C

    24/63

    Data Type - void

    Has no values and operations

    Usually use for function

    Example :

    void printMessage()

    Both set of values are empty

    24

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    25

  • 7/28/2019 Chapter 3 - Introduction to C

    25/63

    Data Type - char

    Use for storing character Stored in memory as 1-byte integer data type

    WHY? Each printable and non-printable character isrepresented by a unique number in computer memory.

    Observe the output!!

    25

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    26

  • 7/28/2019 Chapter 3 - Introduction to C

    26/63

    Numeric Data Type

    In C Program, numeric data types are brokeninto 2 categories:-

    Integer

    Whole numbers Example : 12, 157, -34 and 2

    Floating point

    Numbers that have decimal point

    Example : 23.7, 189.0231 and 0.987

    26

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    27

  • 7/28/2019 Chapter 3 - Introduction to C

    27/63

    Numeric Data Type

    Both Integer and Floating-point data type can bebroken into more classifications

    Primary consideration for selecting data type:-

    The largest and smallest number that maybe

    stored in the variable How much memory does the variable use

    Whether the variable stores signed or unsignednumbers

    The number of decimal places of precision thevariable has

    The size of variable is the number of bytes of

    memory it uses. (> varible

    > range can hold)

    27

    28

  • 7/28/2019 Chapter 3 - Introduction to C

    28/63

    Integer Data Type

    To store WHOLE NUMBER without fraction

    C program supports 3 different sizes of integer

    short int

    int

    long int

    28

    Type Byte Size Minimum

    Value

    Maximum Value

    short int 2 -32,768 32,767

    unsigned short int 2 0 65,535

    int 2 -32,768 32,767

    unsigned int 2 0 65,535

    long int 4 -2,147,483,648 2,147,483,647

    unsigned long int 4 0 4,294,967,295

    29

  • 7/28/2019 Chapter 3 - Introduction to C

    29/63

    Floating Point Data Type

    To store FLOATING-POINT number

    C program supports 3 different sizes of integer

    float

    double

    long double

    29

    Type Byte

    Size

    Precision Range

    float 4 6 10-37 ..1038

    double 8 15 10-307 ..10308

    long double 16 19 10-4931 ..104932

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    30

  • 7/28/2019 Chapter 3 - Introduction to C

    30/63

    Variable Initialization

    To establish the first value that the variable willcontain

    Syntax :

    data_type variable_name = value; Example :

    int count = 5;

    int sum = 0;

    int count=0 , sum = 0;

    char letter = B;

    30

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    31

  • 7/28/2019 Chapter 3 - Introduction to C

    31/63

    Constants

    To define values that CANNOT be changedduring the execution of a program

    Types of constant Integer constant

    Float constant

    Character constant

    String constant Symbolic constant

    31

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    32

  • 7/28/2019 Chapter 3 - Introduction to C

    32/63

    Constants

    3 ways of defining a constant Literal Constant

    Defined Constant using preprocessor

    Defined Constant using const

    32

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    33

  • 7/28/2019 Chapter 3 - Introduction to C

    33/63

    Literal Constants

    An unnamed constant used to specify data If the data cannot be changed, it can simply code

    the value itself in a statement

    Example :

    A // a char literal

    5 // a numeric literal 5

    a + 5 // numeric literal

    3.1435 // a float literal Hello // a string literal

    33

    34

  • 7/28/2019 Chapter 3 - Introduction to C

    34/63

    Defined Constants

    2 ways :- Using preprocessor : #define

    Example :

    #define pi 3.142

    Using keyword : const Example

    const int a = 1;

    34

    35

  • 7/28/2019 Chapter 3 - Introduction to C

    35/63

    Assignment Operator (=) To assign the value of variable or expression into

    to a variable.

    Example:

    a = b;

    result = n1*n1;areaOfCircle = 3.142 * r * r;

    alphabet = A;

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    36

  • 7/28/2019 Chapter 3 - Introduction to C

    36/63

    Arithmetic Operators

    Use to manipulate numeric values and performarithmetic operation

    Assume ;

    int a=4, b= 5, d;C

    Operation

    Arithmetic

    Operator

    C

    Expression

    Value of d after

    assignment

    Addition + d = a + b 9

    Substraction - d = b - 2 3

    Multiplication * d = a * b 20

    Division / d = a/2 2

    Modulus % d = b%3 2

    37

  • 7/28/2019 Chapter 3 - Introduction to C

    37/63

    Arithmetic Operators Assignment

    OperatorsAssume ;

    int x = 4, y=5, z=8;

    AssignmentOperator

    SampleExpression

    SimilarExpression

    Value of variableafter assignment

    += x += 5 x = x + 5 x=9

    -= y -= x y = y - x y=1

    *= x *= z x = x*z x=32

    /= z /=2 z = z/2 z = 4

    %= y %=x y = y%x y=1

    38

  • 7/28/2019 Chapter 3 - Introduction to C

    38/63

    Arithmetic Operator Increment &

    Decrement OperatorOperator Called Sample

    Expression

    Similar

    Expression

    Explanation

    ++ preincrement ++a a = a +1

    a += 1

    Increment a by 1, then use

    the new value of a in

    expression in which a reside

    ++ postincrement a++ a = a +1

    a += 1

    Use the current value of a in

    the expression which a

    reside, then increment a by 1

    - - predecrement - - a a = a -1

    a -= 1

    Decrement a by 1, then usethe new value of a in

    expression in which a reside

    - - postdecrement a - - a = a -1

    a -= 1

    Use the current value of a in

    the expression which a

    reside, then decrement a by

    1

    39

  • 7/28/2019 Chapter 3 - Introduction to C

    39/63

    Example : Increment Operator

    Statements Outputint c=5;printf( "%d", ++c );

    c=5;printf( "%d", c++ );

    int c=5;++c;printf( "%d", c );

    int c=5;c++;

    printf( "%d", c );

    char alphabet = 'D';alphabet++;printf ("\n%c", alphabet);printf ("\n%c", alphabet++);

    printf ("\n%c", ++alphabet);

    40

  • 7/28/2019 Chapter 3 - Introduction to C

    40/63

    Decision Making : Relational &

    Equality Operator Assume ;

    int y=6, x=5;

    Relational Operators Sample Expression Value

    > y > x T (1)

    = x > = 3 T (1)

    < = y < = x F (0)

    Equality Operators Sample Expression Value

    = = x = = 5 T(1)

    ! = y ! = 6 F(0)J uliana J aafar

    CSC 099 Semester 2 2011/2012

    41

  • 7/28/2019 Chapter 3 - Introduction to C

    41/63

    Logical Operator

    Logical Operators Called Sample Operation

    && AND expression1 && expression 2

    | | OR expression1 | | expression2

    ! NOT ! expression

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    42

  • 7/28/2019 Chapter 3 - Introduction to C

    42/63

    Example : Assume;

    int x=50;

    SampleExpression

    Expression !Expression

    !(x==60) 0 (False) 1 (True)

    !(x!=60) 1 (True) 0 (False)

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    43

  • 7/28/2019 Chapter 3 - Introduction to C

    43/63

    Example : AND (&&)

    Assume; int x=4, y = 5, z=8;

    Sample ExpressionExpression1 Expression2 Expression1

    &&

    Expression2

    ( y > 10) && ( z < =x ) 0 (False) 0 (False) 0 (False)

    ( z < = y) && ( x = = 4) 0 (False) 1 (True) 0 (False)

    ( y ! = z) && ( z < x ) 1 (True) 0 (False) 0 (False)

    ( z > = y ) && ( x ! = 3) 1 (True) 1 (True) 1 (True)

    44

  • 7/28/2019 Chapter 3 - Introduction to C

    44/63

    Example : OR (||)

    Assume;int x = 4, y=5, z=8;

    Sample ExpressionExpression1 Expression2 Expression1

    &&

    Expression2

    ( y > 10) || ( z < =x ) 0 (False) 0 (False) 0 (False)

    ( z < = y) || ( x = = 4) 0 (False) 1 (True) 1 (True)

    ( y ! = z) || ( z < x ) 1 (True) 0 (False) 1 (True)

    ( z > = y ) || ( x ! = 3) 1 (True) 1 (True) 1 (True)

    45

  • 7/28/2019 Chapter 3 - Introduction to C

    45/63

    Operator Precedence

    Operators Associative

    ( ) Left to right

    ++ - - + - ! Right to left

    * / % Left to right

    + - Left to right

    < >= Left to right

    = = != Left to right

    && Left to right

    | | Left to right

    = *= += - = /= %= Right to left

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    46

  • 7/28/2019 Chapter 3 - Introduction to C

    46/63

    Example : Operator PrecedenceExample 2

    int a=15, b=6, c=5, d=4;

    d *= ++ba/3 + c

    1. d *= ++ba/3+ c

    2. d*=7- a/3+c

    3. d*=7- 5+c

    4. d*=2 + c

    5. d*= 7

    6. d = d*7

    7. -160

    Example 1

    int a=10, b=20, c=15, d=8;a*b/(-c*31%13)*d

    1. a*b/(-15*31%13)*d

    2. a*b/(-15*31%13)*d

    3. a*b/(-465%13)*d

    4. a*b/(-10)*d

    5. 200/(-10)*d

    6. -200*d

    7. d = 28

    47

  • 7/28/2019 Chapter 3 - Introduction to C

    47/63

    Standard Output & Input Function

    Output function printf() To display information on the computers screen

    Example :

    printf(Programming is great FUN!! Loving IT!);

    Input function scanf()

    To read data typed from the keyboard

    Example :

    printf(Please enter an integer value >>\n);

    scanf(%d, val1);

    ** MUST include header fileJ uliana J aafar

    CSC 099 Semester 2 2011/2012

    48

  • 7/28/2019 Chapter 3 - Introduction to C

    48/63

    Escape Sequence

    Indicates thatprintf() should do something outof the ordinary

    When encountering a backslash(\) in a string,the compiler looks ahead at the next characterand combines it with the backslash to form anescape sequence.

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    49

  • 7/28/2019 Chapter 3 - Introduction to C

    49/63

    Standard Output Function

    2 Syntax ofprintf()

    printf(FormatControlString);

    Example : printf (Hello Dear, \n);

    printf(FormatControlString Format specifier,PrintList);

    Example : int year=2006;

    printf(Year is %d, year);

    Specifier for printing an

    integer value

    To read the value of an

    integer from this variableJ uliana J aafar

    CSC 099 Semester 2 2011/2012

    50

  • 7/28/2019 Chapter 3 - Introduction to C

    50/63

    Common Output Format Specifiers

    Specifies the argument type

    Data Type Format Specifiers

    int %d

    float %f

    double %lfchar %c

    string %s

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    51

  • 7/28/2019 Chapter 3 - Introduction to C

    51/63

    Example :printf() function

    printf( "Sum is %d\n", sum );

    %d means decimal integer will be printed sum specifies what integer will be printed

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    52

  • 7/28/2019 Chapter 3 - Introduction to C

    52/63

    Different Ways of Formattingprintf()

    Display normal messageprintf("Hello Welcome to C");

    Display spaceprintf("\tWelcome");

    Display new lineprintf("\n");

    Printing value of variableprintf("Addition of two Numbers : %d",sum);

    Printing value of the calculationprintf("Addition of two Numbers : %d", num1+num2);

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    53

  • 7/28/2019 Chapter 3 - Introduction to C

    53/63

    Different Ways of Formattingprintf()

    Multiple format specifier

    printf("I Love %c %s",'c',"Programming");

    Display integer in different styles

    printf(\n%d",1234);printf(\n%3d",1234);

    printf(\n%6d",1234);

    printf(\n%-6d",1234);

    printf(\n%06d",1234);

    Output1234

    1234

    ##1234

    1234##

    001234J uliana J aafar

    CSC 099 Semester 2 2011/2012

    54

  • 7/28/2019 Chapter 3 - Introduction to C

    54/63

    Different Ways of Formattingprintf()

    Display fraction number in different stylesprintf("\n%f",1234.12345);

    printf("\n%.4f",1234.12345);

    printf("\n%3.2f",1234.12345);

    printf("\n%-15.2f",1234.12345);printf("\n%15.2f",1234.12345);

    Output

    1234.123450 //by default, it will print 6 values after the decimal

    1234.1235

    1234.121234.12########

    ########1234.12

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    55

  • 7/28/2019 Chapter 3 - Introduction to C

    55/63

    Different Ways of Formattingprintf()

    Display fraction number in different styleschar str[]="Programming"; // Length = 11printf("\n%s",str); // Display Complete Stringprintf("\n%10s",str); // 10 < string Length, thus display Complete

    Stringprintf("\n%15s",str); // Display Complete String with RIGHT

    alignment

    printf("\n%-15s",str); // Display Complete String with LEFTalignment

    printf("\n%15.5s",str); //Width=15 and show only first 5 characterswith RIGHT alignment

    printf("\n%-15.5s",str); //Width=15 and show only first 5 characterswith LEFT alignment

    OutputProgrammingProgramming####ProgrammingProgramming##############ProgrProgr########## J uliana J aafar

    CSC 099 Semester 2 2011/2012

    56

  • 7/28/2019 Chapter 3 - Introduction to C

    56/63

    Standard Input Function

    Syntax ofscanf() scanf(FormatControlString, InputList);

    Example: int age;scanf(%d, &age);

    ** FormatControlString MUST consist of formatspecifiers only

    ** Each element in InputList must be an ADDRESS to a

    memory location for which it must be made into** Address of memory location is specified by prefixing

    the variable name with an ampersand character (&)address operator

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    57

  • 7/28/2019 Chapter 3 - Introduction to C

    57/63

    Common scanf() Format Specifiers

    Data Type Format Specifiers

    int %d

    float %f

    double %lf

    char %c

    string %s

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    58

  • 7/28/2019 Chapter 3 - Introduction to C

    58/63

    Example : scanf() Function

    scanf( "%d", &integer1 );

    %d - indicates data should be an integer value

    &integer1 - location in memory to store variable

    ** When executing the program the user respondsto the scanf() statement by typing in a number,

    then pressing the enter (return) key

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    59

  • 7/28/2019 Chapter 3 - Introduction to C

    59/63

    Example : scanf() Functiondouble height;

    int year;

    scanf(%lf, &height);

    scanf(%d, &year);

    scanf(%lf, height); /* This is an error!! */

    Juliana Jaafar

    2011/2012

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    60

  • 7/28/2019 Chapter 3 - Introduction to C

    60/63

    Example : Inputting Multiple

    Values with a single scanf()int height;

    char ch;

    double weight;

    scanf(%d %c %lf, &height, &ch , &weight);

    Put space between the specifiers

    ** It is always better to use multiple scanf()s, whereeach reads a single value

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    611 /* Fig. 2.5: fig02_05.c

    2 Addition program */

  • 7/28/2019 Chapter 3 - Introduction to C

    61/63

    Juliana Jaafar

    2011/2012

    1. Initializevariables

    2. Input

    2.1 Sum

    3. Print

    Program Output

    2 Addition program /3 #include 45 int main()6 {7 int integer1, integer2, sum; /*declaration */89 printf( "Enter first integer\n" ); /*prompt */10 scanf( "%d", &integer1 ); /* readan integer */11 printf( "Enter second integer\n" ); /*

    prompt */12 scanf( "%d", &integer2 ); /* readan integer */13 sum = integer1 + integer2; /*assignment of sum */14 printf( "Sum is %d\n", sum ); /*print sum */1516 return 0; /* indicate that program endedsuccessfully */17}

    Enter first integer45Enter second integer72

    Sum is 117

    62

  • 7/28/2019 Chapter 3 - Introduction to C

    62/63

    ExampleofC Program

    #include

    int main()

    {

    int num1;

    scanf(%d,&num1 );

    printf(You key in %d\n,num1);

    return 0;

    }

    J uliana J aafar

    CSC 099 Semester 2 2011/2012

    63

  • 7/28/2019 Chapter 3 - Introduction to C

    63/63

    Juliana Jaafar

    2011/2012

    Structure of a C Program