Top Banner

of 134

Operators and expressions,control structures in C

Apr 05, 2018

Download

Documents

Soumya Vijoy
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
  • 7/31/2019 Operators and expressions,control structures in C

    1/134

  • 7/31/2019 Operators and expressions,control structures in C

    2/134

    Operators An operator is a symbol that specifies arithmetic , logical or

    relational operation to be performed.

    The data items that operators act upon are called operands.

    An expression is any computation involving variables and operatorsthat yields a value.

    operators

    arithmetical assignment equality Relational Logical bitwise

    unarybinary

    ternary

  • 7/31/2019 Operators and expressions,control structures in C

    3/134

    ARITHMETIC OPERATORS There are five arithmetic operators in C. They are

    The% operator is also called as modulus operatorArithmetic operators are binary operators because they are operators act upon 2operands

  • 7/31/2019 Operators and expressions,control structures in C

    4/134

    The operands acted upon by arithmetic operators

    must represent numeric values

    The remainder operator(%) requires that both

    operands be integers and the second operand be

    nonzero.

    the division operator(/) requires that the second

    operand be nonzero.

  • 7/31/2019 Operators and expressions,control structures in C

    5/134

    Example a and b 2 integer variables with 14 and 4 as

    values

    a+b=18

    a-b=10

    a*b=56

    a/b=3(decimal part truncated)

    a%b=2(remainder of division)

  • 7/31/2019 Operators and expressions,control structures in C

    6/134

    UNARY OPERATORS

    operators that act upon a single operand to produce a new value arecalled unary operators.

    Unary minus operator

    Unary operator negates the value of its operand

    This operator reverses sign of the operand value

    If a=5 thena will be -5

    If a=-4 thena will be 4

    -a doesnot change the value of a at the location where it permanently

    resides in memory

  • 7/31/2019 Operators and expressions,control structures in C

    7/134

    unary increment and decrement operator(++,--)

    Unary ++ and operators increment or decrement value of a variable by 1

    These operators taking 2 forms

    Prefix

    ++var first add 1 to the variable var . then the result is assigned to thevariable on the left.

    --var first subtract 1 from the variable var . then the result is assigned to the

    variable on the left.

    Postfix-first assigns the value to the variable on left and then

    increments/decrements value of the variable.

  • 7/31/2019 Operators and expressions,control structures in C

    8/134

  • 7/31/2019 Operators and expressions,control structures in C

    9/134

    Example

    Let int i=1printf("i = %d\n", i);printf (i= %d\n", ++i);printf("i = %d\n", i);

    output will be i=1i=2i=2

    printf ("i = %d\n" i);printf("i = %d\n", i++);

    printf("i = %d\n", i);

    output will bei=1i=1

    i=2

  • 7/31/2019 Operators and expressions,control structures in C

    10/134

    Basic rules for using ++ and --

    operators The operand must be a variable but not a constant or

    an expression

    The operator ++ and may precede or succeed theoperand

  • 7/31/2019 Operators and expressions,control structures in C

    11/134

    Sizeof operatorsizeof is a unary compile time operator that returns the number of

    bytes the operand occupies.

    General format

    Sizeof var (where var is a declared variable)

    Or

    Sizeof(type) (where type is a c data type)

    Example

    Int a;

    Printf(size of variable a=%d,sizeof a);Will print size of variable a=2;

  • 7/31/2019 Operators and expressions,control structures in C

    12/134

    RELATIONAL OPERATORS

    Relational operators are used for comparing numerical quantities.

    Relational operators evaluate to 1,representing true outcome or 0

    representing the false

    Expression containing relational operators is called relational expression

  • 7/31/2019 Operators and expressions,control structures in C

    13/134

    The operands of a relational operator must evaluate to a number.

    Characters are valid operands since they are represented by numeric

    values. For ex

    A < F /*will give the output 1 because comparing ascii values of A

    and F

    Relational operators should not be used for comparing strings this

    will results in string addresses being compared , not string contents

    For example HELLO< BYE cause the address of HELLO to be

    compared to the address of BYE.

    For example int i=2,j=3i

  • 7/31/2019 Operators and expressions,control structures in C

    14/134

    Logical operators

    Logical operators&& and || are used to combine two or more

    relational expressions.An expression which combines 2 or more relational expressionis termed as logical expressionLogical And produces 0 if one or both operands evaluate to0.otherwise produces 1

    Logical OR produce 0 if both operands evaluate to 0 otherwiseit roduce 1

  • 7/31/2019 Operators and expressions,control structures in C

    15/134

    Logical not( ! ) is a unary operator negates the logical value of its singleoperand .it causes an expression that is originally true to become false, andvice versa.

  • 7/31/2019 Operators and expressions,control structures in C

    16/134

    Examples of logical expression

    i=4,j=3

    (i>j)||(i==j) this will return 1

    (i>j)&&(i==j) will return 0

    !(i>j) will return 0;

  • 7/31/2019 Operators and expressions,control structures in C

    17/134

    Assignment operatorsassign the value of an expression to an identifier

    assignment operators are used to form assignment expressions

    Assignment expressions are written in the form

    identifier = expression

    identifier generally represents a variable.

    Expression represents a constant, a variable or a more complex

    expression.

  • 7/31/2019 Operators and expressions,control structures in C

    18/134

    Examples of assignment expressions

    a=3

    sum = a + b

    assignment operator = and the equality operator == are distinct.assignment operator is used to assign a value to an identifier,whereas the equality operator is used to determine if twoexpressions have the same value

  • 7/31/2019 Operators and expressions,control structures in C

    19/134

    Multiple assignments of the form

    identifier 1 = identifier 2 = .... = expression

    is permissible in C

    In such situations, the assignments are carried out from right to leftidentifier 1 = identifier 2 = expression

    is equivalent to

    identifier 1 = (identifier 2 = expression)

    Examplei=j=5 here 5 is first assigned to j.then value of j assigned

    to i

  • 7/31/2019 Operators and expressions,control structures in C

    20/134

    Beside = operator, C programming language supportsother short hand format which acts the same assignmentoperator with arithmetic operators a+=b means a=a+b

  • 7/31/2019 Operators and expressions,control structures in C

    21/134

    Conditional(ternary) operator

    C offers a conditional operator(?: that store a value depending on a

    condition.

    A conditional expression is written in the form

    expression 1 ?expression 2 : expression 3

    When evaluating a conditional expression, expression Iis evaluated

    first. Ifexpression 1 is truethen expression 2is evaluated and this

    becomes the value of the conditionalexpression.

    if expression 1 is false, thenexpression 3is evaluatedand this

    becomes the value of the conditional expression.

    For example z = (a > b) ? a : b;

  • 7/31/2019 Operators and expressions,control structures in C

    22/134

    Comma operator

    The comma operator can be used to link related expressions together.

    A comma-linked list of expressions are evaluated left to right and value

    of right most expression is accepted as final result

    The general form of an expression using comma operator is

    Expression M=(expression1,expression2,..............expressionN);

    Since comma has the lowest precedence in operators the parenthesis is

    necessary.

  • 7/31/2019 Operators and expressions,control structures in C

    23/134

    Examples of comma operatorint m=1;

    int n;

    n = (m=m+3 , m%3);Here m =m+3 evaluated first and will assign 4,then m%3

    evaluated and the result 1 is assigned to n

    P d d i ti it f f

  • 7/31/2019 Operators and expressions,control structures in C

    24/134

    Precedence and associativity of of

    operators Precedence is used to determine the order in which different

    operators in a complex expression are evaluated.

    Associativity is used to determine the order in which operatorswith the same precedence are evaluated in a complexexpression.

    Highest priority is for () and lowest for comma.Postfix ++ and - -has higher priority than prefix ++ and - -Unary operators has higher priority than binary operatorsRelational operators having precedence less than arithmetic

    and unary operatorsLogical AND has higher precedence than logical OR

    Operator Associati it

  • 7/31/2019 Operators and expressions,control structures in C

    25/134

    Operator Associativity

    ()[].

    ->++ --(postfix)

    left-to-right

    ++ --(prefix)+ -! ~

    sizeof(type)*(indirection)&(address)

    right-to-left

    * / % left-to-right

    + - left-to-right

  • 7/31/2019 Operators and expressions,control structures in C

    26/134

    =+= -=

    *= /=%= &=^= |=

    =

    right-to-left

    , left-to-right

    > left-to-right

    < >=

    left-to-right

    == != left-to-right

    & left-to-right

    ^ left-to-right| left-to-right

    && left-to-right

    || left-to-right

    ?: right-to-left

  • 7/31/2019 Operators and expressions,control structures in C

    27/134

    Type conversion

    Type conversion occurs when the expression has data of mixed data types.

    example of such expression include converting an integer value in to a float value,

    or assigning the value of the expression to a variable with different data type.

    In type conversion, the data type is promoted from lower to higher because

    converting higher to lower involves loss of precision and value.

  • 7/31/2019 Operators and expressions,control structures in C

    28/134

  • 7/31/2019 Operators and expressions,control structures in C

    29/134

    Implicit conversion

    It is the automatic conversion done by compiler withoutprogrammers intervention

    Rules for implicit conversion1. If either operand is long double, convert the other to long

    double.2. Otherwise, if either operand is double, convert the other

    to double.3. Otherwise, if either operand is float, convert the other tofloat.

    4. Otherwise, convert char and short to int.5. Then, if either operand is long, convert the other to long.

  • 7/31/2019 Operators and expressions,control structures in C

    30/134

    I integer variable with value 7

    F f loat variable with 5.5

    C char variable with value w I+F will have value 12.5

    I+C will have value 126

  • 7/31/2019 Operators and expressions,control structures in C

    31/134

    Explicit conversion Explicit conversion is user defined that forces an expression to be of

    specific type

    Explicit conversion of an operand to a specific type is calledtypecasting

    General form of casting is

    (data type) expression

    The expression is converted to the data type specified inparenthesis

    The data type associated with the expression itself is not changed bya cast. Rather, it is the value of theexpression that undergoes typeconversion

  • 7/31/2019 Operators and expressions,control structures in C

    32/134

    For example i is an integer variable whose value is 7, and

    f is a floating-point variable whose value is 8.5.

    ((int) (i + f)) % 4

    For ex int a=100,b=40

    float c;

    c=a/b will result 2.000000 but actual value required is 2.5 for that

    we have to use c=(float)a/b

  • 7/31/2019 Operators and expressions,control structures in C

    33/134

    The C language is accompanied by a number of library functions

    that carry out various commonly usedoperations or calculations

    Library functions that are functionally similar are usually grouped

    together as (compiled) object programs in separate library files. These

    library files are supplied as a part of each C compiler.

    A library function is accessed simply by writing the function name,

    followed by a list of arguments thatrepresent information being

    passed to the function. The arguments must be enclosed inparentheses and separated by commas.

    Library functions

  • 7/31/2019 Operators and expressions,control structures in C

    34/134

    In order to use a library function it may be necessary to include certain

    specific information within the main portion of the program.

    This information is generally stored in special files which are supplied

    with the compiler. Thus, the required information can be obtained

    simply by accessing these special files. This is accomplished with the

    preprocessor statement #include; i.e.,

    #include

    where filename represents the name of a special file.

    For example #include contains library functions for

    mathematical operations

  • 7/31/2019 Operators and expressions,control structures in C

    35/134

  • 7/31/2019 Operators and expressions,control structures in C

    36/134

    Library functions for string

    operations

    strcat(s,t) Concatenate t to end of s

    strcmp(s,t) return negative, zero, or positive fors t

    strcpy(s,t) Copy t to s

    strlen(s) return length of s

    These library functions defined instring.h

  • 7/31/2019 Operators and expressions,control structures in C

    37/134

    Mathematical Functions

    sin(x) sine of x, x in radians

    cos(x) cosine ofx, x in radiansexp(x) exponential function ex

    log(x) natural logarithm of x

    sqrt(x) square root ofx (x>0)

    abs(i) absolute value of integer

    variable

    pow(x,y) xy

    These functions defined in math.h

  • 7/31/2019 Operators and expressions,control structures in C

    38/134

    Character Class Testing and Conversion

    isalpha(c) non-zero if c is alphabetic, 0 if not

    isupper(c) non-zero if c is upper case, 0 if notislower(c) non-zero if c is lower case, 0 if not

    isdigit(c) non-zero if c is digit, 0 if not

    isalnum(c) non-zero if isalpha(c) or isdigit(c), 0 if not

    toupper(c) Return c converted to upper case

    tolower(c) Return c converted to lower case

  • 7/31/2019 Operators and expressions,control structures in C

    39/134

    Data input and output

  • 7/31/2019 Operators and expressions,control structures in C

    40/134

    Console i/o functions The screen and keyboard together are called a console.

    Console i/o functions classified to two categories

    FormattedUnformatted

  • 7/31/2019 Operators and expressions,control structures in C

    41/134

    Formatted functions

    Type Input Output

    char Scanf() Printf()

    int Scanf() Printf()

    float Scanf() Printf()

    string Scanf() Printf()

    unformatted functions

    Type Input Output

    char Getch()Getche()Getchar()

    Putch()Putchar()

    int

    float

    string Gets() Puts()

    Console input/output fuctions

  • 7/31/2019 Operators and expressions,control structures in C

    42/134

    getch() and getche()Getch() function will read a single character the instant it is typed by

    programmer without waiting for the Enter Key to be hit. The typed

    character is not echoed on screen.

    Getche() function will also read a single character the instant it is

    typed by programmer without waiting for the Enter key to be hit, just like

    getch() function. Getche() echoes the character on screen that you

    typed.

  • 7/31/2019 Operators and expressions,control structures in C

    43/134

    #include

    #include

    Void Main()

    {char ch;

    printf(Press any key to continue");

    getch(); //will not echo the character

    printf(Type any character:");

    ch=getche();

    }

  • 7/31/2019 Operators and expressions,control structures in C

    44/134

    putch() putch() writes a character to the screen.

    #include

    Void Main()

    {

    Char ch=A;

    Putch(ch);

    }

    ng e c aracter nput getc ar

  • 7/31/2019 Operators and expressions,control structures in C

    45/134

    ng e c aracter nput

    getc arfunction

    Getchar() is an input function that reads a single character from

    standard input device.

    The getchar function is a part of the standard C I/O library.

    This function does not require any arguments , but still have to use

    empty parenthesis.

    The getchar has the following form.

    Char_variable = getchar();

    Char_variable must be previously declared character variable.

  • 7/31/2019 Operators and expressions,control structures in C

    46/134

    On end of file the value of EOF is returned.

    Usually EOF will be assigned the value -1, though this may vary fromone compiler to another.

    #include

    main()

    {

    char C;

    printf("Type one character:");

    C=getchar();

    printf(" The character you typed is = %c",C);

  • 7/31/2019 Operators and expressions,control structures in C

    47/134

    SINGLE CHARACTER OUTPUT -putchar FUNCTION

    Single characters can be displayed using the C libraryfunction putchar.

    It transmits a single character to a standard outputdevice

    The general form is

    putchar (char_variable );

    Char_variable must be previously declared character variable

  • 7/31/2019 Operators and expressions,control structures in C

    48/134

    #include

    main()

    {char in;

    printf(" enter one character ");

    in=getchar();

    Printf(entered character is );

    putchar(in);

    }

  • 7/31/2019 Operators and expressions,control structures in C

    49/134

    Formatted input and output

    functionsWhen input and output is required in specified format

    the standard library functions scanf and printf areused.

    scan

  • 7/31/2019 Operators and expressions,control structures in C

    50/134

    scanScanf() allows to enter data from the keyboard that will be formatted

    in a certain way.

    The function returns the number of data items that have been entered

    successfully.

    General form of scanf

    scanf(control string,arg1,arg2.......argn);

    Control string is a string that can consist of format specifiers.it

    indicates the format and type of data to be read from standard input

    device.

    Argl,arg2, . . . argn are arguments that represent the individual input

    data items.

    These arguments are preceded with the address-of operator to

    indicate the address of data item in memory

  • 7/31/2019 Operators and expressions,control structures in C

    51/134

    There is no need to use & for strings stored in arraysbecause array name is already a pointer

    F ifi i f()

  • 7/31/2019 Operators and expressions,control structures in C

    52/134

    Conversion

    CharacterDatatype

    d Signed decimal integer

    i decimal, hexadecimal oroctal integer

    o octal integer

    u unsigned decimal integerx hexadecimal integer

    c single character

    s string

    e Float or doublef Float or double

    g Float or double

    %lf double

    Format specifiers in scanf()

  • 7/31/2019 Operators and expressions,control structures in C

    53/134

    the size qualifier conversion characters may be preceded with certainconversion characters

    main( )

  • 7/31/2019 Operators and expressions,control structures in C

    54/134

    {

    char item[20];

    i n t partno;

    f l o a t cost;

    . . . . .

    scanf("%s %d %f",item, &partno, &cost);

    . . . . .

    }

    %s, indicates that the first argument (item) represents a string.

    %d, indicates that the second argument (&partno) represents a decimal

    integer value

    %f,indicates that the third argument (&cost) represents a floating-point

    value

    More on scanf

  • 7/31/2019 Operators and expressions,control structures in C

    55/134

    While Inputting Integer numbers we can also specify the field width of a

    number.general format is

    %wd

    w integer specifies the field width of the number to be read

    d - integer

    Examples

    Scanf(%2d %5d,&num1,&num2);Data inputted 25 12345 then 25 assigned to num1 and 12345 to num2

    Suppose data inputted is 12345 25 then 12 will be assigned to num1 and

    345 to num2

    Inputting integer numbers

    More on scanfThe format specifier %% is used for single % character in the inputstream.

    We can use following conversion specifications for strings

  • 7/31/2019 Operators and expressions,control structures in C

    56/134

    We can use following conversion specifications for strings

    %[characters]

    %[^characters]

    The specification %[characters]means that only the character

    specified with in the brackets are permissible in the input string.if input

    string contains any other character string will be terminated at the first

    encounter of such character.

    With the help of %[] scanf can be used to read string with blank

    spaces.

    The specification %[^characters] means the characters specified

    after the circumflex(^) are not permitted in the input string. The reading

    of string will be terminated at the encounter of one of these character

    Example of %[]

  • 7/31/2019 Operators and expressions,control structures in C

    57/134

    Example of %[]

    main()

    { char address[80];printf("Enter address\n");scanf("%[a-z]", address);printf(%-80s,address);

    }OutputEnter addressnew york 122345

    new york

    Example of %[^]

  • 7/31/2019 Operators and expressions,control structures in C

    58/134

    Example of %[ ]

    main(){

    char address[80];

    printf("Enter address\n");scanf("%[^\n]", address);printf("%-80s", address);

    }

    OutputEnter addressNew Delhi 110 002New Delhi 110 002

  • 7/31/2019 Operators and expressions,control structures in C

    59/134

    Scanf will stop reading a value of a variable infollowing cases

    A white space character found in numericspecification

    Maximum number of characters have been read

    An error detected

    The end of file is reached

  • 7/31/2019 Operators and expressions,control structures in C

    60/134

    Printf() O/P data can be written from the computer onto a standard O/Pdevice using the library function printf

    General form is

    printf(control string,arg1,arg2.....argn);

    where control string refers to a string that contains formattinginformation, and arg1, arg2, . . . , argn are arguments that representthe individual output data items.

    Control string contain 3 types of items

    characters that are simply printed as they are conversion specification that begin with a % sign

    escape sequence that begin with a \sign

    Format specifiers for printf()

  • 7/31/2019 Operators and expressions,control structures in C

    61/134

    Format specifiers for printf()

    Conversion

    CharacterDatatype

    d Signed decimal integer

    i decimal, hexadecimal oroctal integer

    o octal integer

    u unsigned decimal integerx hexadecimal integer

    c single character

    s string

    e Float or double

    f Float or double

    g Float or double

    %lf double

    the size qualifier

    conversion characters maybe preceded with certainconversion characters.size qualifier charactersare h for short,l for longand L for long double

    More on printf()

  • 7/31/2019 Operators and expressions,control structures in C

    62/134

    More on printf()Outputting integer numbers While outputting a integer number we can also specify minimum field

    width for the output. General format is

    %wd

    w-minimum field width for output.

    if number grater than specified field width it will be printed in full

    overriding minimum specificationd-value to be printed is a integer

    The number is written right justified in the given field width

    Examples

  • 7/31/2019 Operators and expressions,control structures in C

    63/134

    Examples

    Format output

    Printf(%d,1234);

    Printf(%6d,1234);

    1 2 3 4

    1 2 3 4

    1 2 3 4

    Printf(%-6d,1234)

    Printf(%2d,1234);

    1 2 3 4

    Outputting real numbers

  • 7/31/2019 Operators and expressions,control structures in C

    64/134

    For outputting real numbers we can specify number of digits after

    decimal point and minimum number of positions that are to be used for

    display

    General format is

    %w.pf

    w-minimum field width specification

    p- specifies no.of digits to be displayed after decimal point(precision)

    We can also use

    printf(%*.*f,width,precision,number); here width and precision

    supplied at runtime. For example printf(*.*f,7,2,number); is equivalent

    to printf(%7.2f,number);

    examples

  • 7/31/2019 Operators and expressions,control structures in C

    65/134

    examples

    To print Float

    y=98.7654Format

    Printf(%7.4f,y)

    Printf(%7.2f,y)

    Printf(%-7.2f,y)

    Printf( %f,y)

    Printf(%10.2e,y)

    9 8 . 7 6 5 4

    9 8 . 7 7

    9 8 . 7 6 5 4

    9 . 8 8 e + 0 1

    output

    9 8 . 7 7

  • 7/31/2019 Operators and expressions,control structures in C

    66/134

    Outputting stringsA single character can be displayed in desired position

    using %wc

    The character will be displayed right justified in field

    of w columns

    Format specification for outputting string is %w.ps

    wherew specifies the field width for display and p

    specifies only first p characters of the string are to bedisplayed

  • 7/31/2019 Operators and expressions,control structures in C

    67/134

    examplesFor outputting strings NEW DELHI 110001specification output

    %s

    %20s

    %20.10s

    %5s%.5s

    N E W D E L H I 1 1 0 0 0 1

    N E W D E L H I 1 1 0 0 0 1

    N E W D E L H I

    N E W D E L H I 1 1 0 0 0 1

    N E W D

    N E D E L H I%-20.10s

  • 7/31/2019 Operators and expressions,control structures in C

    68/134

    flag meaning

    - left justifies the field; default is right justification.

    + always prefixes a signed value with a sign (+ or -).

    0 pads numeric values with leading zeros. If both 0 and -appear as flags, the 0 flag is ignored.

    # prefixes octal values with 0 and hexadecimal valueswith 0x or 0X.For floating point values, this forces the decimal point to bedisplayed, even if no characters follow it.

    We can also include flags , which affects the appearance ofthe output in printfFlags are used immediately after % sign

    Commonly used flags and their meaning given below

  • 7/31/2019 Operators and expressions,control structures in C

    69/134

    Printf(%07.2f,y)

    Printf(%-+6.1f,5.5)

    0 0 9 8 . 7 7

    + 5 . 5

    String input and output:gets and puts

  • 7/31/2019 Operators and expressions,control structures in C

    70/134

    g p p g p

    The gets function receives the string from standard input device.

    A string is an array or set of characters. string may include whitespace

    characters.

    The standard form of the gets function is

    gets (str)

    Here str is a string variable

    It will reads characters into str from keyboard until newline character is

    encountered and will append a null character to the string

  • 7/31/2019 Operators and expressions,control structures in C

    71/134

    puts outputs the string to the standard output device.

    The standard form for the puts function is

    puts (str)

    where str is a string variable.

    The puts function displays the contents stored in its

    parameter on the screen.

    In puts() function,we cannot pass more than one

    argument.So it can display one string at a time.

  • 7/31/2019 Operators and expressions,control structures in C

    72/134

    #include

    Void main()

    {

    char s[80];

    printf("Type a string less than 80 characters:");

    gets(s);

    Puts( The string types is: );

    puts(s);

    }

  • 7/31/2019 Operators and expressions,control structures in C

    73/134

  • 7/31/2019 Operators and expressions,control structures in C

    74/134

    Control statements C language provides statements that can alter the

    flow of a sequence of instructions. Thesestatements are called control statements.

    These statements help to jump from one part ofthe program to another.

    The statements which specify the order of executionof statements are called control statements

  • 7/31/2019 Operators and expressions,control structures in C

    75/134

    if

    Program control statements

    Conditionaltype

    Selection/branching

    Unconditional type

    If-else

    If-else-if

    switchbreak goto continue

    Iteration/looping

    for while Do-while

  • 7/31/2019 Operators and expressions,control structures in C

    76/134

    Control statements in broadly divided to two

    Branching

    Looping

    Branching is deciding what actions to take and loopingis deciding how many times to take a certain action.

    If statement

  • 7/31/2019 Operators and expressions,control structures in C

    77/134

    If statement

    The simplest form of the control statement is the If statement.

    It is very frequently used in decision making and allowing the flow

    of program execution.

    Syntax

    if (Test expression)

    statement;

    The test expression inside if should not end with a semicolon

    If test expression evaluates to true, corresponding statement is

    executed. If test expression evaluates to false control goes to next

    executable statement.

    The statement can be either simple or compound.

  • 7/31/2019 Operators and expressions,control structures in C

    78/134

  • 7/31/2019 Operators and expressions,control structures in C

    79/134

    Sample program for if construct

    #includemain()

    {

    int number;

    printf("Type a number:");

    scanf("%d",&number);

    if (number < 0)

    number = -number;printf("The absolute value is %d \n", number);

  • 7/31/2019 Operators and expressions,control structures in C

    80/134

    Type a number:11The absolute value is 11

    Type a number:-5The absolute value is 5

    If-else

  • 7/31/2019 Operators and expressions,control structures in C

    81/134

    If...else is an extension of simple if statement.

    General form is

    if(test expression)

    Statement1

    Else

    Statement 2

    if the test expression evaluates to true, then program statement 1 isexecuted, otherwise program statement 2 will be executed.

  • 7/31/2019 Operators and expressions,control structures in C

    82/134

    Flowchart of if else construct

  • 7/31/2019 Operators and expressions,control structures in C

    83/134

    #include

    void main()

    {

    int a,b;

    printf("Enter 2 number");

    scanf("%d%d",&a,&b);if (a>b)

    printf("%d is greater",a);

    else

    printf("%d is greater",b);}

    Nesting of if..else statements

  • 7/31/2019 Operators and expressions,control structures in C

    84/134

    gWhen series of decisions are involved we may have to

    use more than if else statement in nested form.

    A nested ifis a statement that has another ifin itsbody or in it else's body.

    Nested if else having 3 formats

    if(test expression 1){

    if(testexpression 2)statement 1;

    [else

    statement 2;]

    }else

    body of else;

  • 7/31/2019 Operators and expressions,control structures in C

    85/134

    if(test expression 1)

    body-of-if;else

    {

    if(testexpression 2)

    statement 1;

    [else

    statement 2;]

    }

    II

    if(test expression 1 )III

  • 7/31/2019 Operators and expressions,control structures in C

    86/134

    if(test expression 1 ){

    if(test expression 2)statement 1 ;

    [elsestatement 2;]

    }

    else{

    if(test expression 3)statement3;

    [elsestatement4;]

    }

  • 7/31/2019 Operators and expressions,control structures in C

    87/134

  • 7/31/2019 Operators and expressions,control structures in C

    88/134

    /*sample code using nested if else */

  • 7/31/2019 Operators and expressions,control structures in C

    89/134

    /*sample code using nested if-else */if(a>b)

    {if(a>c)printf("%d is larger",a);

    }else if(b>c)printf("%d is larger",b);else

    printf("%d is larger",c);}

    If-else-if ladder When a series of many conditions have to be checked

  • 7/31/2019 Operators and expressions,control structures in C

    90/134

    When a series of many conditions have to be checkedwe may use the ladder else if statement

    General form of ifelse-if ladder is

    if (test Expression 1) statement 1;else if (test Expression 2)

    statement2;else if (test Expression 3)

    statement3;.

    .

    else if (Test Expression n)

    statement n;else

    statement-F;

  • 7/31/2019 Operators and expressions,control structures in C

    91/134

    If expression1 is evaluated to true then statement 1 is executed.if expression2 is true then statement 2 is executed and so on. If none of

    the test expression are true then statement F will be executed

  • 7/31/2019 Operators and expressions,control structures in C

    92/134

    Sample code for ifelse- if ladder{

  • 7/31/2019 Operators and expressions,control structures in C

    93/134

    {

    ----------

    If(score>=80)

    Grade=A;

    Else if(score>=70 && score=60 && score=50 && score

  • 7/31/2019 Operators and expressions,control structures in C

    94/134

    Looping allows set of instructions to be performed repeatedly until a

    certain condition is fulfilled

    There are 2 types of loops

    Pre-test loop or entry controlled loop

    Post-test loop or exit controlled loop

    In entry controlled loop test expression is evaluated before entering

    the loop.

    In a exit controlled loop test expression is evaluated before exitingfrom the loop

  • 7/31/2019 Operators and expressions,control structures in C

    95/134

    Testexpression

    Body of loop

    True

    false

    Pre-test loop

    Body of loop

    Testexpression

    True

    false

    Post-test loop

    In pretest loop ,loop body may not be executed where as in post-testloop loop body will be executed at least once

  • 7/31/2019 Operators and expressions,control structures in C

    96/134

    C having 3 looping statements

    For

    WhileDo while

    for and while are pretest/entry controlled loopsand do while is exit controlled/post test loops

    Parts of loop

  • 7/31/2019 Operators and expressions,control structures in C

    97/134

    Initialization expression(s)

    before entering the loop, loop control variables must be initialized.

    this initialization of control variable take place under initialization

    expression .

    This part of loop is the first to be executed.

    Initialization expression(s) are executed only once in the beginning of theloop

    Test expression

    Test expression is an expression whose truth value decides whether the

    loop-body will be executed or not .

    If test expression evaluates to true loop body gets executed,otherwise loop

    is terminated

  • 7/31/2019 Operators and expressions,control structures in C

    98/134

    Update expression(s)

    change value of loop control variable(s)

    Update expression are executed every time through the loop before

    test expression is tested

    Body- of- theloop

    The statements that are executed repeatedly form the body of the loop

    While Loop

  • 7/31/2019 Operators and expressions,control structures in C

    99/134

    pThe while statement is used to carry out looping operations, in which a

    group of statements is executed repeatedly, until some condition hasbeen satisfied.

    Is an entry controlled loop

    The general form of the while statement is

    while ( test expression)

    statement

    The statement will be executed repeatedly, as long as the expression

    is true

    Statements can be simple or compound,

    start

  • 7/31/2019 Operators and expressions,control structures in C

    100/134

    Initialization

    Testexpression

    Statement(s)

    Update

    expressions

    True

    false

    Flowchart of while loop

    In while loop,initialization of loop

    control variable donebefore the loop starts.Updating mustincluded in the body of

    the loop

  • 7/31/2019 Operators and expressions,control structures in C

    101/134

    Sample program//to print numbers 1 to 10 using while loop

    void main()

    {

    int i=1;while(i

  • 7/31/2019 Operators and expressions,control structures in C

    102/134

    For loopIt is a commonly used loop

    This loop is definite loop because programmer knows exactly how

    many times loop will be executed

    General format is

    For(initialization; test expression; update expression)

    statement;

    Statements can be simple or compound, which is the body of loop

    Fl h f f l

  • 7/31/2019 Operators and expressions,control structures in C

    103/134

    Initialization

    Testexpression

    statementsUpdateexpressions

    True

    false

    Flowchart of for loop

    All the four parts of while loop is also present in for loop. but all are comprised inone line

  • 7/31/2019 Operators and expressions,control structures in C

    104/134

    for loop can written as equivalent to while loop and vice versa

    For(initialization; test expression; update expression)

    statement;

    Is equivalent to while

    Initialization;

    while ( test expression)

    {

    statement ;

    Update expressions;

    }

  • 7/31/2019 Operators and expressions,control structures in C

    105/134

    Sample program using for loopvoid main()

    {

    int i;

    For(i=1;i

  • 7/31/2019 Operators and expressions,control structures in C

    106/134

    First feature is Multiple initialization and update expressions

    For loop may contain multiple initialization and/or update expressions

    Multiple expressions are separated by commas For(i=1,sum=0;i

  • 7/31/2019 Operators and expressions,control structures in C

    107/134

    Do while loop It is a post-test loop

    Test expression is evaluated after executed loop body at least once

    General syntax is

    do

    {

    statement

    }

    while (expression);

    Statements will be executed until expression become false.

  • 7/31/2019 Operators and expressions,control structures in C

    108/134

    Initialization

    Testexpression

    statements

    Updateexpressions

    True

    false

  • 7/31/2019 Operators and expressions,control structures in C

    109/134

    //to print numbers 1 to 10 using do-while loopvoid main(){

    int i=1;do{printf("%d\n",i);

    i++;}while(i

  • 7/31/2019 Operators and expressions,control structures in C

    110/134

    p

    Each loops having its own control variable or index

    Inner loop must terminate before outer loop

    for(i=1;i

  • 7/31/2019 Operators and expressions,control structures in C

    111/134

    Nesting of whileint n,i=1,j=1;while(i

  • 7/31/2019 Operators and expressions,control structures in C

    112/134

    Int i=1,j=1;

    do

    {

    j=1;

    do

    {printf("%d",j);

    j++;

    }while(j

  • 7/31/2019 Operators and expressions,control structures in C

    113/134

    The usage of multiple If else statement increases the complexity of

    the program since when the number of If else statements increase it

    affects the readability of the program and makes it difficult to follow the

    program.

    The switch statement removes these disadvantages by using asimple and straight forward approach.

    c has a built-in multiway decision statement known as a switch

    statement

  • 7/31/2019 Operators and expressions,control structures in C

    114/134

    General format of switch statement is

    Switch(expression)

    {

    Case constant 1:statementlist1;

    break;

    Case constant 2:statementlist2;

    break;

    ..

    Default :statementlist n}

    Expression is an integer or character expression. When the switch statement

    is executed the expression is evaluated first and the value is compared with the

  • 7/31/2019 Operators and expressions,control structures in C

    115/134

    case label values in the given order.

    If the case label matches with the value of the expression then the control is

    transferred directly to the group of statements which follow the label.

    If none of the statements matches then the statement against the default is

    executed.

    The default statement is optional in switch statement in case if any default

    statement is not given and if none of the condition matches then no action takes

    place in this case the control transfers to the next statement

  • 7/31/2019 Operators and expressions,control structures in C

    116/134

    Break statement at the end of each statement block indicates end of

    particular case and causes an exit from switch statement.

    Even if there are multiple statements to be executed in each casethere is no need to enclose them within a pair of braces

  • 7/31/2019 Operators and expressions,control structures in C

    117/134

    Sample codeswitch(choice)

  • 7/31/2019 Operators and expressions,control structures in C

    118/134

    switch(choice)

    {

    case 1: printf(you entered menu choice #1);break;

    case 2:printf(you entered menu choice #2);

    break;

    default:printf("Invalid Choice");break;

    }

    Once the statement list under a case is executed ,the flow of controlcontinues down executing all the following cases until the break is

  • 7/31/2019 Operators and expressions,control structures in C

    119/134

    continues down executing all the following cases until the break isreached

    Switch(number){Case 1:Case 3:Case 5:

    Case 7:case 9 : printf(%d is an odd number,number);

    break;Case 2:Case 4:

    Case 6:Case 8:printf(%d is an even number,number);

    break;Default:printf(%d is not between or including 1 and 9,number);

    break;}

  • 7/31/2019 Operators and expressions,control structures in C

    120/134

    Switch versus if-else Ladder

  • 7/31/2019 Operators and expressions,control structures in C

    121/134

    1.Switch can only test for equality where if can evaluate a relational or

    logical expression

    2.switch cannot handle floating point test. Where if can handle floating

    point test also apart from integer and character test

    3.Switch statement select its branches by testing value of a same

    variable against set of constants whereas if else use series of

    expression that involve unrelated variables and complex expression

    4.Switch case label value must be a constant

    if 2 or more variables are to be compared use if-else

  • 7/31/2019 Operators and expressions,control structures in C

    122/134

    breakThe break statement is used to terminate loops or to exit from a switch. It

    can be used within a for, while,do -while, or switch statement.

    The break statement is written simply as

    break;

    After a break is executed with in a loop or a case in switch execution

    proceeds to the statement that follows loop or switch

    When loops are nested break would only exit from the loop containing

    it.i.e break will exit only a single loop

  • 7/31/2019 Operators and expressions,control structures in C

    123/134

  • 7/31/2019 Operators and expressions,control structures in C

    124/134

    While(){

    .If(condition)break;

    }

    For(.){

    if(condition)Break;....}

    ..

    Exitfromloop

    Exitfromloop

    Do{

    .If(condition)Break;.}While(..);

    For(.){for(.)

    {if(condition)

    Break;.}..

    }

    Exitfromloop

    Exitfromloop

    Void main()

    {

  • 7/31/2019 Operators and expressions,control structures in C

    125/134

    {

    int c=1;

    While(c

  • 7/31/2019 Operators and expressions,control structures in C

    126/134

    Break in nested loop

    for(i=2;i

  • 7/31/2019 Operators and expressions,control structures in C

    127/134

    continueContinue statement does not terminate the loop .it forces the next

    iteration of the loop to take place, skipping any code in between.

    On execution of continue statement control will goes to test

    expression in while and do while statement and goes to the updating

    expression in a for statement

    While (test expr){

    Continue;. . }}

  • 7/31/2019 Operators and expressions,control structures in C

    128/134

    do{

    .continue;

    }while(testexpr);

    For(initialization;testexpr;updation){

    Continue;..}

    void main(){

  • 7/31/2019 Operators and expressions,control structures in C

    129/134

    {.

    for(i=1;i

  • 7/31/2019 Operators and expressions,control structures in C

    130/134

    continue

    break continue

    It helps to make an earlier exitfrom the block where it appears It helps in avoiding the remainingstatements in current iteration ofthe loop and continuing with thenext iteration

    It can be used in all control

    statements including switchconstruct

    It can be used only in loop

    constructs

    GOTO statement:

  • 7/31/2019 Operators and expressions,control structures in C

    131/134

    The goto statement is used to alter the normal sequence of program

    execution by transferring control to some other part of the program.

    In its general form, the goto statement is written as

    goto label;

    where label is an identifier that is used to label the target statementto which control will be transferred.

  • 7/31/2019 Operators and expressions,control structures in C

    132/134

  • 7/31/2019 Operators and expressions,control structures in C

    133/134

    Sample codevoid main()

    {

    float x,y;

    read:

    scanf(%f,&x);

    if(x

  • 7/31/2019 Operators and expressions,control structures in C

    134/134

    void main(){

    int n,i;long int fact=1;scanf(%d,&n);if(n