computer programming 1(lecture3)

Upload: mohamed-mohy

Post on 09-Apr-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Computer Programming 1(Lecture3)

    1/41

    Computer Programming 1

    Lecture 3

  • 8/8/2019 Computer Programming 1(Lecture3)

    2/41

    ConstantsThere are four basic types of constants in C. They are integer

    constants, floating-point constants, character constants and stringconstants (there are also enumeration constants, which arediscussed later). Moreover, there are several different kinds ofinteger and floating-point constants, as discussed below.

    Integer and floating-point constants represent numbers. They areoften referred to collectively as numeric-type constants. The

    following rules apply to all numeric-type constants.

    1. Commas and blank spaces cannot be included within the constant.

    2. The constant can be preceded by a minus (-) sign if desired. (Actuallythe minus sign is an operatorthat changes the sign of a positiveconstant, though it can be thought of as a part of the constant

    itself.)3. The value of a constant cannot exceed specified minimum and

    maximum bounds. For each type of constant, these bounds willvary from one C compiler to another.

  • 8/8/2019 Computer Programming 1(Lecture3)

    3/41

    Integer ConstantsAn integer constantis an integer-valued number.

    Thus it consists of a sequence of digits. Integerconstants can be written in three differentnumber systems: decimal (base lO), octal (base 8)and hexadecimal (base 16). Beginning

    programmers rarely, however, use anything otherthan decimal integer constants.

    A decimalinteger constant can consist of anycombination of digits taken from the set 0through 9. If the constant contains two or moredigits, the first digit must be something otherthan 0.

  • 8/8/2019 Computer Programming 1(Lecture3)

    4/41

    EXAMPLE 2.4 Several valid decimal integer constants are

    shown below.0 1 7435280 32767 9999

    The following decimal integer constants are writtenincorrectly for the reasons stated.

    12,245 illegal character (, ).36.0 illegal character (.).

    10 20 30 illegal character (blank space).123-45-6789 illegal character (-).0900 the first digit cannot be a zero.

  • 8/8/2019 Computer Programming 1(Lecture3)

    5/41

    An octalinteger constant can consist of any combination of digits

    taken from the set 0 through 7. However the first digit must be 0, inorder to identiQ the constant as an octal number.

    EXAMPLE

    Several valid octal integer constants are shown below.

    0 01 0743 077777

    The following octal integer constants are written incorrectly for thereasons stated.

    743 Does not begin with 0.

    05280Illegal digit (8).

    0777.777 Illegal character ( .).

  • 8/8/2019 Computer Programming 1(Lecture3)

    6/41

    A hexadecimal integerconstant must begin with either Ox or OX. It

    can then be followed by any combination of digits taken from thesets 0 through 9 and a through f (either upper- or lowercase). Notethat the letters a through f (or A through F) represent the (decimal)quantities 10 through 15, respectively.

    EXAMPLE

    Several valid hexadecimal integer constants are shown below.0x 0x 1 0X7FFF 0xabcd

    The following hexadecimal integer constants are written incorrectly forthe reasons stated.

    OX12.34 Illegal character ( .).

    OBE38 Does not begin with Ox or OX.Ox. 4bff Illegal character ( .).OXDEFG Illegal character (G).

  • 8/8/2019 Computer Programming 1(Lecture3)

    7/41

    Floating-Point ConstantsAfloating-pointconstant is a base- 10 number that contains either a decimal

    point or an exponent (or both).

    EXAMPLE 2.8

    Several valid floating-point constants are shown below.

    0. 1 . 0.2 827.60250000. 0.000743 12.3 315.0066

    2 E-8 0.006e-3 1.6667E+8 .12121212e12

    The following are not valid floating-point constants for the reasons stated.

    1 Either a decimal point or an exponent must be present.1,000.0 Illegal character (, ).

    2E+10.2 The exponent must be an integer quantity (it cannot containa decimal point).3E 10 Illegal character (blank space) in the exponent.

  • 8/8/2019 Computer Programming 1(Lecture3)

    8/41

    EXAMPLE

    The quantity 3 x 105 can be represented in C by anyof the following floating-point constants.

    300000. 3e5 3e+5 3E53.Oe+ .3e6 0.3E6 30E430.E+4 300e3Similarly, the quantity 5.026 x IO-l7 can be

    represented by any of the following floating-pointconstants.

    5.026E-17 .5026e-1650.26e-18 .0005026E-13

  • 8/8/2019 Computer Programming 1(Lecture3)

    9/41

    Charcater Constant

    A character constantis a single character,

    enclosed in apostrophes (i.e., single quotation

    marks).

    EXAMPLE

    Several character constants are shown below.

    A X 3 ?

  • 8/8/2019 Computer Programming 1(Lecture3)

    10/41

    Escape SequencesCertain nonprinting characters, as well as the

    backslash (\) and the apostrophe ( I ), can beexpressed in terms ofescape sequences.Anescape sequence always begins with a

    backward slash and is followed by one ormore special characters. For example, a linefeed (LF), which is referred to as a newline inC, can be represented as \n. Such escape

    sequences always represent single characters,even though they are written in terms of twoor more characters.

  • 8/8/2019 Computer Programming 1(Lecture3)

    11/41

    The commonly used escape sequences are listed below.

    Character Escape Seauence ASCIIValue

    bell (alert) \a 007 backspace \b 008

    horizontal tab \t 009

    vertical tab \v 011

    newline (line feed) \n 010 form feed \f 012

    carriage return \r 013

    quotation mark (") \ 034

    apostrophe (') \ 039

    question mark (?) \? 063

    Backslash (\) \\ 092

    null \0 000

  • 8/8/2019 Computer Programming 1(Lecture3)

    12/41

    String ConstantsA string constantconsists of any number of consecutive characters (including none),

    enclosed in (double) quotation marks.

    EXAMPLESeveral string constants are shown below.

    green Washington, D.C. 20005 270-32-3456$19.95 THE CORRECTANSWER IS: * ( I+3)/J Line l\nLine 2\nLine 3

    Note that the string constant "Line 1\nLine 2\nLine 3" extends over three lines, because ofthe newline characters that are embedded within the string. Thus, this string would bedisplayed as

    Line 1

    Line 2

    Line 3

    EXAMPLE

    The following string constant includes three special characters that are represented by theircorresponding escape sequences.

    " \tTo continue, press the \"RETURN\" key\n;

    The special characters are \t (horizontal tab), \ I' (double quotation marks, which appears

    twice), and \ n (newline).

  • 8/8/2019 Computer Programming 1(Lecture3)

    13/41

    VARIABLESA variable is an identifier that is used to represent some

    specified type of information within a designatedportion of the program. In its simplest form, a variableis an identifier that is used to represent a single dataitem; i.e., a numerical quantity or a character constant.The data item must be assigned to the variable at some

    point in the program. The data item can then beaccessed later in the program simply by referring to thevariable name.

    A given variable can be assigned different data items atvarious places within the program. Thus, theinformation represented by the variable can changeduring the execution of the program. However, thedata type associated with the variable cannot change.

  • 8/8/2019 Computer Programming 1(Lecture3)

    14/41

    EXAMPLE

    A C program contains the following lines.

    int a, b, c;char d;. . .a = 3;

    b = 5;c = a + b;d = a;a = 4;

    b = 2;c = a - b;d = W;

  • 8/8/2019 Computer Programming 1(Lecture3)

    15/41

    DECLARATIONSA declaration associates a group of variables with a

    specific data type. All variables must be declaredbefore they can appear in executable statements.

    A declaration consists of a data type, followed by one or

    more variable names, ending with a semicolon.

    EXAMPLE

    A C program contains the following type declarations.

    int a, b, c ;

    float root1 , root2;

    char flag, zone;

  • 8/8/2019 Computer Programming 1(Lecture3)

    16/41

    These declarations could also have been written

    as follows.

    int a;

    intb;

    int c;

    floatroot1;

    floatroot2;char flag;

    char zone;

  • 8/8/2019 Computer Programming 1(Lecture3)

    17/41

    EXPRESSIONSAn expression represents a single data item, such as a

    number or a character. The expression may consist of asingle entity, such as a constant, a variable, an arrayelement or a reference to a function. It may alsoconsist of some combination of such entities,interconnected by one or more operators. The use of

    expressions involving operators is particularly commonin C, as in most other programming languages.

    Expressions can also represent logical conditions that areeither true or false. However, in C the conditions true

    andfalse are represented by the integer values 1 and0,respectively. Hence logical-type expressions reallyrepresent numerical quantities.

  • 8/8/2019 Computer Programming 1(Lecture3)

    18/41

    An expression is a combination of variables constants and

    operators written according to the syntax of C language. In C

    every expression evaluates to a value i.e., every expression

    results in some value of a certain type that can be assigned to

    a variable

  • 8/8/2019 Computer Programming 1(Lecture3)

    19/41

    Evaluation ofExpressionsExpressions are evaluated using an assignment statement of the form

    Variable = expression;

    Variable is any valid C variable name. When the statement isencountered, the expression is evaluated first and then replaces the

    previous value of the variable on the left hand side. All variablesused in the expression must be assigned values before evaluation isattempted.

    Example of evaluation statements are

    x = a * b cy = b / c * az = a b / c + d;

  • 8/8/2019 Computer Programming 1(Lecture3)

    20/41

    The following program illustrates the effect of presence of

    parenthesis in expressions.

    main ()

    { float a, b, c, x, y, z;a = 9;b = 12;c = 3;x = a b / 3 + c * 2 1;y = a b / (3 + c) * (2 1);z = a ( b / (3 + c) * 2) 1;

    printf (x = %fn,x);printf (y = %fn,y);printf (z = %fn,z);

    }

    output

    x = 10.00y = 7.00z = 4.00

  • 8/8/2019 Computer Programming 1(Lecture3)

    21/41

    Precedence in Arithmetic Operators

    An arithmetic expression without parenthesis will be evaluated from left toright using the rules of precedence of operators. There are two distinct

    priority levels of arithmetic operators in C.

    High priority * / %Low priority + -

    Rules for evaluation of expression

    First parenthesized sub expression left to right are evaluated. If parenthesis are nested, the evaluation begins with the innermost sub

    expression.

    The precedence rule is applied in determining the order of application of operatorsin evaluating sub expressions.

    The associability rule is applied when two or more operators of the sameprecedence level appear in the sub expression.

    Arithmetic expressions are evaluated from left to right using the rules ofprecedence.

    When Parenthesis are used, the expressions within parenthesis assume highestpriority.

  • 8/8/2019 Computer Programming 1(Lecture3)

    22/41

    Type conversions in expressions

    Implicit type conversion

    C permits mixing of constants and variables of differenttypes in an expression. C automatically converts anyintermediate values to the proper type so that theexpression can be evaluated without loosing anysignificance. This automatic type conversion is know asimplicit type conversion

    During evaluation it adheres to very strict rules andtype conversion. If the operands are of different types

    the lower type is automatically converted to the highertype before the operation proceeds. The result is ofhigher type.

  • 8/8/2019 Computer Programming 1(Lecture3)

    23/41

    Type conversions in expressionsThe following rules apply during evaluating expressions

    All short and char are automatically converted to int then

    1. If one operand is long double, the other will be converted to long double and

    result.....will be long double.

    2. If one operand is double, the other will be converted to double and result will

    be double.

    3. If one operand is float, the other will be converted to float and result will be

    float.4. If one of the operand is unsigned long int, the other will be converted into

    unsigned.....long int and result will be unsigned long int.

    5. If one operand is long int and other is unsigned int then

    .....a. If unsigned int can be converted to long int, then unsigned int operand will

    be ..........converted as such and the result will be long int.

    .....b. Else Both operands will be converted to unsigned long int and the result willbe ..........unsigned long int.

    6. If one of the operand is long int, the other will be converted to long int and the

    result will be long int. .

    7. If one operand is unsigned int the other will be converted to unsigned int and

    the .....result will be unsigned int.

  • 8/8/2019 Computer Programming 1(Lecture3)

    24/41

    Explicit ConversionMany times there may arise a situation where we want to force a type

    conversion in a way that is different from automatic conversion.

    Consider for example the calculation of number of female and malestudents in a class

    female_studentsRatio = -------------------

    male_studentsSince if female_students and male_students are declared as integers, the

    decimal part will be rounded off and its ratio will represent a wrong figure.This problem can be solved by converting locally one of the variables tothe floating point as shown below.

    Ratio = (float) female_students / male_students

    The operator float converts the female_students to floating point for thepurpose of evaluation of the expression. Then using the rule of automaticconversion, the division is performed by floating point mode, thus

    retaining the fractional part of the result. The process of such a localconversion is known as explicit conversion or casting a value. The generalform is

    (type_name) expression

  • 8/8/2019 Computer Programming 1(Lecture3)

    25/41

    EXAMPLE

    Several simple expressions are shown below.

    a + bx = yc = a + bx

  • 8/8/2019 Computer Programming 1(Lecture3)

    26/41

    The fourth expression will have the value 1 (true) if the value of x is less thanor equal to the value of y. Otherwise, the expression will have the value 0(false). In this expression,

  • 8/8/2019 Computer Programming 1(Lecture3)

    27/41

  • 8/8/2019 Computer Programming 1(Lecture3)

    28/41

    STRUCTURE OF THE

    C LANGUAGE

  • 8/8/2019 Computer Programming 1(Lecture3)

    29/41

  • 8/8/2019 Computer Programming 1(Lecture3)

    30/41

    Pseudocode

    Pseudocode

    Artificial, informal language that helps us develop

    algorithms

    Similar to everyday English

    Not actually executed on computers

    Helps us think out a program before writing it

    Easy to convert into a corresponding C program

    Consist only of executable statements, i.e. without

    comments and variable definition.

  • 8/8/2019 Computer Programming 1(Lecture3)

    31/41

    Flowchart

    Flowchart

    Graphical representation of an algorithm

    Drawn using certain special-purpose symbols connected byarrows called flowlines

    Rectangle symbol (action symbol): Indicates any type of action

    Oval symbol: Indicates the beginning or end of a program or a section of code

    Single-entry/single-exit control structures Connect exit point of one control structure to entry point of the

    next (control-structure stacking)

    Makes programs easy to build

  • 8/8/2019 Computer Programming 1(Lecture3)

    32/41

    Control Structures

    Sequential execution (by default) Statements executed one after the other in the order written

    Transfer of control When the next statement executed is not the next one in

    sequence Overuse of goto statements led to many problems

    All programs written in terms of three control structures Sequence structures: Built into C. Programs executed

    sequentially by default

    Selection structures: C has three types: if, ifelse, andswitch Repetition structures: C has three types:while, dowhile

    and for

  • 8/8/2019 Computer Programming 1(Lecture3)

    33/41

    Flowcharting Cs sequence structure

  • 8/8/2019 Computer Programming 1(Lecture3)

    34/41

    The if Selection Statement

    Selection structure: Used to choose among alternative courses of action

    Pseudocode:If students grade is greater than or equal to 60

    Print Passed

    If condition true Print statement executed and program goes on to next

    statement

    If false, print statement is ignored and the program goes ontothe next statement Indenting makes programs easier to read

    C ignores whitespace character

  • 8/8/2019 Computer Programming 1(Lecture3)

    35/41

    The if Selection StatementDiamond symbol (decision symbol)

    Indicates decision is to be made

    Contains an expression that can be true or false

    Test the condition, follow appropriate path

    Grade 60 print Passed

  • 8/8/2019 Computer Programming 1(Lecture3)

    36/41

    The ifelse Selection Statement

    if Only performs an action if the condition is true

    ifelse Specifies an action to be performed both when the

    condition is true and when it is false

    Psuedocode:

    If students grade is greater than or equal to 60

    Print Passed

    elsePrint Failed

    Note spacing/indentation conventions

  • 8/8/2019 Computer Programming 1(Lecture3)

    37/41

    The ifelse Selection Statement

    C code:

    if ( grade >= 60 )

    printf( "Passed\n");

    else

    printf( "Failed\n");

    Ternary conditional operator (?:)

    Takes three arguments (condition, value iftrue, value if false)

  • 8/8/2019 Computer Programming 1(Lecture3)

    38/41

    The ifelse Selection Statement

    Flow chart of the ifelse selection statement

    Nested ifelse statements

    Test for multiple cases by placing ifelse selection statementsinside ifelse selection statement

    Once condition is met, rest of statements skipped

    Deep indentation usually not used in practice

  • 8/8/2019 Computer Programming 1(Lecture3)

    39/41

  • 8/8/2019 Computer Programming 1(Lecture3)

    40/41

    The ifelse Selection StatementCompound statement:

    Set of statements within a pair of braces

    Example:

    if ( grade >= 60 )printf( "Passed.\n" );

    else {printf( "Failed.\n" );printf( "You musttake this course

    again.\n" );}

    Without the braces, the statement

    printf( "You musttake this course again.\n" );would be executed automatically

  • 8/8/2019 Computer Programming 1(Lecture3)

    41/41

    Programming Errors in ifelse SelectionStatement

    Syntax errors

    E.g. Forget one or both of the braces that delimit a

    compound statement

    Caught by compiler

    Logic errors:

    Have their effect at execution time

    Non-fatal: program runs, but has incorrect output

    Fatal: program exits prematurely