C&DS Unit-I

Embed Size (px)

Citation preview

  • 8/14/2019 C&DS Unit-I

    1/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:1

    Program:

    A computer program is a set of instructions which are executed in a sequential order. In a

    C program, the instructions (statements) execute in the order in which they appear until unless

    the order is not specifically changed by control structures in C.

    History of C:

    C is originally developed by Dennis Ritchie at AT and Ts Bell Laboratories in 1972. C

    was evolved from ALGOL, BCPL and B and uses many concepts from these languages and

    added the concept of data types and other powerful features. One of the most popular operating

    systems, UNIX is developed in C.

    Many version of C were proposed and to assure that the C language remains standard,

    ANSI (American National Standards Institute) appointed a technical committee in 1983 to define

    a standard for C. The committee approved a version in 1989 and is referred to ANSI C. It is later

    approved by ISO (International Standards Organization).

    Features of C:

    The increasing popularity of C is due to its many desirable qualities:

    It is a highlyportable language and can be easily implemented in differentoperating systems.

    It is robustlanguage; with its rich set of built in functions and operators we canwrite any complex programs easily.

    Programs written in C are efficient and fastthan other languages like BASIC C language is well suited forstructured programming, in which the programmer

    thinks of a problem in terms of function modules or blocks. A proper collection of

    these modules (blocks) make a complete program. That is why a C program can

    termed as a collection of different functions. One of those functions is compulsory

    and is it the main() function. C compiler starts execution of the program by

    making a call to main function.

    C has ability to extend itself; we can continuously as add our own functions to theC Library.

    Executing a C program:

    The following are series of steps involved:

    Creating the program (using a editor) Compiling the program Linking the program with functions that are needed from the C library; Executing the program

    We can use any text editor to create a C program.

    C Compiler is the software tool (or component) that is responsible for converting the high level

    C program into machine understandable code (machine level language). This code is called

  • 8/14/2019 C&DS Unit-I

    2/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:2

    object code and is stored in file with the extension .obj. The Linker is used to link the various

    functions called in program. If the functions are user defined, the definition of the function

    should be in the range of the program. The operating system handles the execution of the

    programs and all input and output operations are channeled through the operating system.

    Commenting in C:

    Comments are generally written to explain the logic of the program, sometimes to specify

    the problem statement and sometimes to specify the details of the author of the program. These

    comments are purely for better understandability of the user (programmer) and do not make any

    sense to the C compiler. The compiler ignore the comments while generating the object code.

    Therefore the file with extension.objdoesnt contain the conversions for these comments.

    Commenting in C can be done in 2 ways:

    Multi-Line Commenting (/*..*/) the text placed between /* and */ will be commented

    (ignored by compiler) and it also supports multiple lines of the commented text.

    Single Line Commenting (//) when a sequence of two forward slashes appears in the program,the entire text following it in the same line will be commented. \\ can comment only a single

    line of text.

    Algorithm and Flow Chart:

    Since we will be solving lot of logical problems while writing C programs, it is necessary

    to understand the components (namely Algorithm/ Pseudo code and Flow Chart) that can be used

    to represent solutions for complex problems.

    Algorithm/ Pseudo code:

    An algorithm is a method of representing the step-by-step procedure for solving aproblem. An algorithm is very useful for finding the right solution for a problem by breaking the

    problem into simple cases. An algorithm is also called Pseudo code. For example a simple

    algorithm for finding a large among three numbers can be written like this.

    Begin

    1. Read 3 numbers x,y,z from the user.2. ifx>y and x>z3. then x is the largest4. else ify>z and y>z5. then y is the largest among the 3 numbers6. else7. Z is the largest of the three.8. End-ifEnd.

  • 8/14/2019 C&DS Unit-I

    3/26

  • 8/14/2019 C&DS Unit-I

    4/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:4

    Flow chart for the above algorithm will be as follows:

    Getting started with C:

    Learning C language is similar to learning the English language. The classical method oflearning English to learn the set of alphabets (character set in C), words (tokens) and sentences(sentences) and paragraphs (program). It is just that they are termed differently in C.

    Character Set:

    The character set of C language contains the following:Alphabets A, B, C, .X, Y Z

    a, b, c.. x, y, zDigits 0, 1, 2, 3.9Special symbols: ~ ` ! @ # % $ & * ( ) _ - + = | \ { } [ ] : ; < > , . ? /

    No

    No

    Start

    x>y &

    x>z

    Read values for x,y,z

    X is largest.

    Output x

    Yes

    y>x &

    y>z

    y is largest.

    Output yYes

    z is largest.

    Output z

    End

  • 8/14/2019 C&DS Unit-I

    5/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:5

    C Tokens:

    In a C program, the basic element recognized by the compiler is the "token." A token issource-program text that the compiler does not break down into component elements. Token areformed with the combinations of characters in character set of C. The keywords, identifiers,

    constants, string literals, and operators are examples of tokens. Punctuation characters such asbrackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens.

    Constants:

    A constant is a quantity that doesnt change during the execution of the program.Constants are also called literals. C supports various kinds of constants (different kind ofconstants for different data types).

    Illustration:

    Integer Constants:Integer constant refers to a sequence of digits. Decimal integer consists of a set of digits,

    0 through 9. Integer can negative or positive. Negative integers are indicated by using the unaryoperator minus (-).

    Eg: 867 -124

  • 8/14/2019 C&DS Unit-I

    6/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:6

    Real Constants: are also called floating point constants. These can be represented in 2 formsfractional form or exponential form.In fraction form a decimal point is used.Eg: 23.456 768.45 -945.45

    The exponential form is usually used for when the value of real constant is either too small or toolarge. The real constant is represented in 2 parts namely mantissa and exponent. Mantissaappears before e and exponent appears after e. Range of real constants expressed inexponential form is -3.4e38 to 3.4e38.Eg: 3.2e-5 4.1e8 +467e31

    Note: ANSI C supports unary plus (+) which was not supported earlier.

    Character Constants:

    A character constant is either a single alphabet or a single digit or a single special symbol

    enclosed within single inverted commas (apostrophes).Eg: A g 9 *

    Each character has an integer value known as ASCII (American Standard Codes for InformationInterchange) code. For example the ASCII code associated with a is 97. To print the ASCIIcode of a character we can use the format specifier %d instead of %c while in the printfstatement.

    String Constants:

    A string Constant is a sequence of characters enclosed in a pair of double quotes. The charactermay be alphabets, digits, special characters and blank spaces.Eg: INDIA Indian Engineer What a pleasant day! ?_)-?

    Backslash Character Constants (Escape Sequences):C supports special kind of characters which are formed by combining the normal characters withthe escape character (\). These characters have special meaning. Each represents a singlecharacter although it has 2 characters.Some of Escape Sequences:

    \b blank space \ single quote\f form feed \ Double Quote\n new line \? Question Mark\r carriage return \\ back slash\t horizontal tab \0 Null\v vertical tab \a audible alert

    Keyword and IdentifiersKeywords are the word in C which has fixed meaning and these meanings cannot be

    changed. They serve as the building blocks of the program. The following is the list of 32keywords in C.

  • 8/14/2019 C&DS Unit-I

    7/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:7

    auto double int struct break else long switchcase enum register typedef char extern return unionconst float short unsigned continue for signed voiddefault goto sizeof volatile do if static while

    Identifiers are user defined names formed with different combinations of alphabets,digits and underscore in character set with certain rules. Identifiers are used to name thevariables, functions, arrays, etc.Rules to forming identifiers (user defined name):

    Identifiers must start with an alphabet or underscore. Identifiers cannot contain special character other than underscore. Maximum length should be 31 characters. Should not be a keyword

    Variables:

    Variable is data name that may be used to store the data value. Unlike constants (literals)variables may have different value during the execution of program. In general a meaningfulname is chosen for a variable depending upon the context on the program. Variable names arecase sensitive and therefore variableAMOUNTis different from variable amount. Since thevariable name is identifier, the above mentioned rules need to be followed.

    Eg: x, sum, Avg, Root1, Nearest_Number.

    Declaring of variables:

    Before using the variables in a program, they should be declared. Declaration tells thecompiler what the variable name is and what type of data it can store. Undefined usage ofvariables results in error during compilation.

    Syntax: ;Separate statements need to be used to declare variables of different kinds. Multiple

    variables of same kind can be defined in a single statement by separating them with commas(separate statements are also allowed).

    Eg: int a,b,c;float x;char str;

    Initializing and assigning value to Variables: To initialize or assign a value to a variable we usethe assignment operator =. The variable can be initialized during declaration or can beassigned a value anytime later.

    Eg: int a=3; int sum=0; int x; x=45;If a variable is not initialized; unpredicted values will be stored, until any value is assigned.

    Data Types:Data Types are used to specify what type of data can be stored, exchanged or returned by a

    variable or a function. C supports a variety of data types which can be classified into two groups:o Primary (Fundamental or Primitive) Data Types

  • 8/14/2019 C&DS Unit-I

    8/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:8

    o User Defined Data Types (Derived Data Types)Primary Data Types:

    C compiler supports 5 fundamental data types namely int, float, double, char and void.Many compilers also support extended data types such as long int, long double, unsigned int,

    short int, unsigned long int, unsigned short int, unsigned char, etc.

    Integer types (int):Integers are the natural numbers (1, 2, 3.) including 0 and their negatives (-1, -2, -3,

    .). int is the keyword used to declare variable or functions of type integer. On a 16 bitcomputer when an integer is declared it is allocated 2 bytes of memory.Eg: int x;

    The range of integers that can be stored depends on the word length of the computer. Ifwe use a 16 bit word length, the size of the integer is limited to the range -32768 to -32767(i.e -215 to 215-1). A signed integer uses the first bit for sign and 15 bit for the magnitude of the integer. If thefirst bit is 1 then it indicated negative numbers. If it is Zero then it is positive number. A 32 bit wordlength computer can store integers ranging from -2147483648 to 2147483647. The range of the integerscan be restricted or increased by qualifying int with the proper combination keywords short, long andunsigned. short decreases the range where as long and unsigned increases the range. The use ofqualifier signed is optional because by default integers are signed integers.

    Note:To distinguish long integer literals from regular literals they are appended by a qualifier L (or l).Similarly U (or u) is appended for unsigned integers. For L and U any case can be used.Eg: 56789U (unsigned int) 987654321ul (unsigned long integer)

    987.34567784787L (long double)Floating Point Data Type:

    Floating point numbers are real numbers which can have fractional values (decimal point).Floating Point numbers are stored with 6 digits of precision and uses 32 bits (4 bytes) of memory. The

    keyword used isfloat. double can be used to increase the range real numbers and also to increase theaccuracy with higher precision. Double (double precision numbers) uses 64 bits of memory (8 bytes)giving a 14 digit precision. To increase the precision even more we can use long double which uses 80bits.

    Eg: float avg; double discriminant; long double acc_value;

    Character Type:A single character type can be declared using the key word char. Character uses 8 bits (1 byte)

    of memory for storage. While storing the chars the corresponding ASCII value is stored in binary format.The qualifiers signed and unsigned can be used to change the range of chars. By default charis signedchar whose range is -128 to 127, where as the range ofunsigned charis 0 to 255.

    Void Types:The voidhas no values. It is generally used to specify the type of the function and a function is

    said to be void when it does not return any value. There will not be any void variables.

    The size and range of different data types on a 16 bit computer are listed here:

  • 8/14/2019 C&DS Unit-I

    9/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:9

    User-defined Data Types (Derived Data Types):

    These data types are created by the user (programmer), which are either derived from

    primitive data types or formed by different combination of the primitive data types. Derived data

    type can be a structure, union, enum, pointer or it can be type defined using typedef keyword.

    typedefusage:

    C allows the programmer to define a new data type and give it a user friendly name

    which originally represents the existing data type. In other words the we can rename a existing

    data type using typedef.

    Syntax: typedef ;

    Where, type can be any of the fundamental data type or a derived data type (such as structure)

    which is available before execution of this statement.

    Eg: typedef int units;

    Once the above statement is executed, a new data type units is available whose behavior

    exactly same as int. So we can now create variable, functions, etc of type units.

    units a,b;

    units u=9;

    Other user defined data types will be discussed later.

    Constant Variables:

    A variable can be made constant throughout the execution of the program by declaring it

    using the key word const.

  • 8/14/2019 C&DS Unit-I

    10/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:10

    Eg: const int size=100;

    In the above case, the value of the variable size is always 100. It variable size can be used

    anywhere in the program but the value cannot be altered. Constant variable must compulsorily be

    initiated while they are declared. They cannot be initialized in a separate statement as we can do

    in case of normal variables.

    Reading and Displaying Data:

    As we have seen earlier, variables can be assigned values with the help of the assignment

    operator. Another way of assigning a value to variable is by using scanffunction.

    The general format of scanf is: scanf(control string, &variable1,&variable2,);

    The control string can be a format specifier or a collection of format specifiers which specify the

    type of the values that can be read into the variables (variable1, variable2,..etc).

    The ampersand symbol (&) before each variable is a pointer operator; which indicates theaddress of the variable. This means that the values read are stored in the address of the variable.

    More on this will be understood when we learn pointers.

    Eg: scanf(%d, &var1);

    %d is the format specifier which specifies that a integer value must be read from the user console

    (or terminal).

    To display any text (or string) or the value of any variables, we can use the printf

    function. General format:

    printf(Simple String);

    printf(Simple String + Control String, variable1, variable2,);printf(Control String, variable1, variable2,);

    Control string specifies the type of the value that is displayed from the variables.

    Eg: printf(Hello World);

    printf(Value of the variable x is %d, x);

    printf(%f, avg);

    The following are the various format specifier that we can used in scanf and printf functions

    Format

    specifier

    Used to Represent Comment

    %d signed decimal integer used in both scanf and printf

    %i signed decimal integer (same used in both scanf and printf

  • 8/14/2019 C&DS Unit-I

    11/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:11

    as above)

    %c character

    %s string (character array) In scanf multi word strings cannot be read.

    %f Floating Point Number By default displays the 6 precision digits when

    used in printf

    %0.2f Limits the number of number

    of digits after decimal point

    to 2 (can be any value less

    than 6)

    Used in printf to to define the accuracy

    needed. For example while dealing with cost

    of any items, we need only two digits (that

    represent paise) after decimal point.

    %u Unsigned int

    %% Used to display the percent

    symbol

    used only in printf not in scanf

    Operators:

    C supports a huge variety of operators. An operator is use to ask the computer to perform

    certain mathematical or logical manipulations. Operators are used to manipulate data and

    variables.

    Following are the categories of operators in C:

    Arithmetic Operators Relational Operators

    Logical Operators Assignment Operator Increment and Decrement Operators Conditional Operators Bitwise Operators Special Operators

    Arithmetic Operators:

    These operators are used to perform the basic Arithmetic operations such as addition,

    subtraction, multiplication and division.

    Unary minus operator in effect multiplies its single operand by -1 there by changing thesign of the operand.

    Integer Division truncates (does not round off) any fractional part The modulo division operator gives the reminder after performing the integer division. Modulo Division cannot be performed on floating point.

  • 8/14/2019 C&DS Unit-I

    12/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:12

    Operator Description Cardinality

    + This is used to perform addition on integers or real

    numbers. This can also be used as unary plus (optional)

    Binary/Unary (2

    or 1)

    - This used to perform subtraction on integers or realnumbers. This is also used as unary minus

    Binary/Unary (2or 1)

    * This is called asterisk and is used to perform

    multiplication.

    Binary (2)

    / Forward slash operator is used to perform division Binary (2)

    % Modulo Division. Can be used only for integers and

    produces reminder of integer division

    Binary (2)

    If both operands of an arithmetic operation are integers then it is called integer expression and

    the result of the integer expression will be an integer.

    Eg: 2+3 the result is 5

    5/2 the result is 2 and not 2.5 (decimal part is truncated in integer division)

    5%2 the result is 1 (% returns the reminder of integer division of 5 by 2)

    If an expression has both real operands (float or double) then it is called real expression and

    result will be a real number.

    5.0/2.0 the result is 2.5

    4.3/8.45 0.508876

    An expression involving one integer operand and one real operand can be called as mixed modeoperation and the result of mixed mode operation is a real number.

    5.0/2 2.5 (even if 2 is integer 5.0 is real and so result is real).

    Relational Operators:

    These operators are used to compare two quantities to determine the relation between

    those quantities.

    An expression that contains relational operators is called relational expression. The result of the

    relational expression is eitherone orzero (true orfalse in advanced languages). Zero

    corresponds to false and one corresponds to true.

    Eg: a

  • 8/14/2019 C&DS Unit-I

    13/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:13

    used to check if the left hand operand is greater than right

    hand operand

    Binary

    >= greater than or equal to Binary

    == This is used to check if the value of left hand operator is equal

    to right hand operator.Note that this is different from

    assignment operator (=)

    Binary

    != not equal to Binary

    Relational operations can be performed on multiple arithmetic expressions. In such cases the

    arithmetic expression are evaluated first and then the results are compared.

    Eg: (a+2) < (b-c);Relational expressions are used to form conditions in the decision statements (will be explained

    later).

    Logical Operators:

    Logical Operators are used to perform logical AND, logical OR and NOT. Logical

    operators are used to check more than one condition.

    && -- Logical AND

    || -- Logical OR

    ! -- Logical NOT

    && and || are binary operations and ! is a unary operator.

    An expression which combines 2 or more relational expressions by using logical operations is

    called a compound relational expression.

    Eg: a>b && x==10 d=e !(d!=f)

    Truth Table

    Op1 Op2 Value of the Expression

    Op1 && Op2 Op1 || Op2

    Non-Zero (1) Non-Zero (1) 1 1

    Non-Zero (1) 0 0 1

    0 Non-Zero (1) 0 1

    0 0 0 0

  • 8/14/2019 C&DS Unit-I

    14/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:14

    NOT (!) has only operand and can represented as !Op1. If Op1 is a Non-Zero value then the

    result of !Op1 is zero. If the value of Op1 is zero then the result of !Op1 is 1.

    Assignment Operators:

    Assignment operators are used to assign the result of an expression to a variable. The

    operator = is used for assignment.

    Eg: v1= 20; v2= v1+v3;

    C also supports shorthand assignment operators of the form

    v op= exp;

    where v is a variable, exp is an expression and op is a binary arithmetic operation. The operator

    op= is known as the shorthand assignment operator.

    The statement v op= exp is equivalent to v = v op exp. The operation op can be +, -, %, / or *.

    Eg: a *=b (a= a*b) x += 2 (x= x+2) a /= n+2 [a= a/(n+2)]

    Shorthand assignment makes the statement more concise and easy to read and makes it moreefficient.

    Increment and Decrement Operators:

    Both the operators are unary and operate on only one operand. Increment operator is ++

    and increases the value of the operand by 1. Decrement operator is and subtracts 1 from the

    operand.

    Based the place the operator is placed w.r.t operand there can post increment and pre decrement.

    Similarly post decrement and pre decrement also exists.

    If the operator is placed before the operand then it is pre (increment or decrement) else if it

    placed after the operand then it called post (increment or decrement).Eg: i++ ++i --j j--

    i++ and ++i are equivalent to i=i+1 and --j and j-- are equivalent to j=j-1.

    ++iand i++ mean the same when they are independent statements. But when used in a

    expression they behave differently. In an expression when ++iis used, the value of i is

    incremented before it is used in the evaluation of the expression, where as when i++ is used, the

    previous value iis first used for evaluating the expression and later incremented.

    Sample code for illustration:

    int a=5,b,c;

    a++; //increment value of a by 1 so a value is 6

    --a; //decrements the value of a by one and so value of a will be 5

    b=a++; //since post increment is used, the value of a (5) is assigned to b and later

    //incremented. Therefore b will be 5 and a will be 6

    c=++a; //since pre-increment is used, the value of a is incremented before assigning it to c

    // Therefore value of c will be 7 and value of a will be 7

  • 8/14/2019 C&DS Unit-I

    15/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:15

    printf(%d %d %d,a,b,c);

    Output: 7 5 7

    Conditional Operator:

    The conditional operator ?: is used to form conditional expressions of the form

    exp1 ? exp2 : exp3;

    where exp1, exp2 and exp3 are expressions.

    exp1 is evaluated first and if it is nonzero (true), then the expression exp2 is evaluated and

    becomes the value of the expression. If exp1 is zero (false) then exp3 is evaluated and it becomes

    the value of the expression (can be assigned to any variable).

    Eg: q = (f>g)?f:g

    The above statement makes the variables to be assigned with greatest of both f and g. If f=5 and

    g=6 then f>g condition returns false and so q=g i.e. q=6.

    Logically this is equivalent to using if else block.

    if(f>g)q=f;

    else

    q=g;

    Bitwise Operators:

    These operators are used to manipulate the data at bit level. They can be used for testing

    the bits, shifting them right or left. Bitwise operators may not be applied tofloatordouble.

    Bitwise AND &is used to perform AND operation on individual bits of the operands. It is a

    binary operation and needs two operations.

    Eg: c=2 & 3;First the two operands are converted into binary bits and then AND operation is

    applied on individual bits. If assume the word length of a computer as 16bit we will have 16

    digits in the binary conversion.

    2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

    3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1

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

    2 & 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 2 (result)

    Bitwise OR |(single pipeline) is used to perform OR operation on individual bits of the

    operands. This is again a binary operations and it needs 2 operands.

    Eg: j= 5 | 9;

    First 5 and 9 are converted into binary system and later on OR operation is performed

    on each bit of the numbers.

  • 8/14/2019 C&DS Unit-I

    16/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:16

    5 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1

    9 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1

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

    5 | 9 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 13 (result)

    Bitwise exclusive OR ^ this is similar to the operations except that it performs exclusive OR

    operation on

    Shift left or left shift

  • 8/14/2019 C&DS Unit-I

    17/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:17

    Note: Right shifting a number by one position will half the value (in above case result of 4>>1 is

    2). Therefore x=x>>1 will simply reduce the value of x to half. Similarly x=x>>2 will make it

    reduced to 1/4th.

    Ones Complement ~(can also be referred to as bitwise NOT) is a unary operation that

    applies on a single operand and performs logical NOT operation on individual bits of the binary

    conversion of the operand.

    Eg: c= ~a;

    where a is the operand on which ones complement is applied and the value is assigned to c.

    Let value of a be 6.

    6 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0

    ~6 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1

    Special Operators:

    C supports some special operators such as comma (,) operator, sizeof operator, pointeroperator (& and *) and member selection operators (, and ->).

    Comma Operator ,is used to link the related expressions together. A comma-linked

    expression is evaluated left to right. The value of the right most expression is the value of the

    combined expression.

    Eg: x = (a = 34, b = 4, a+b);

    In the above statement first the value 34 is assigned to a and then 4 us assigned to b and the

    addition (a+b) is performed and the result of a+b is stored in x.

    Since comma operator has lowest precedence use of parenthesis is compulsory. Some

    applications of comma operator are as follows

    for( i=0, j=10; i

  • 8/14/2019 C&DS Unit-I

    18/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:18

    Operator Precedence and Associativity:

    In general expressions can involve many operators and when multiple operators are used,

    the order in which operations are performed should be defined. The precedence and associativity

    of operators are used to determine how an expression involving multiple operators should be

    evaluated. There are different levels of precedence and the operation involving highest

    precedence operator will be evaluated first. The operators of same precedence are evaluated

    either from left to rightorright to leftdepending on the associativity property of the operator.

    Most of the operator will have left to right associativity where some of them have right to

    left associativity. Here is a table:

  • 8/14/2019 C&DS Unit-I

    19/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:19

    Decision Making Statements:

    Simple if statement:

    The ifstatement is a powerful decision making statement and is used to control the flow

    of execution of statements. The general form of a simple if is:

    if (test expression)

    {

    Statement-block;

    }

    Statement-x;

    Thestatement blockcan be a single statement or a group of statements. If the test-expression is

    true, the statement block is executed and the control continues to statement-x. If the test-

    expression is false then statement block inside the if is skipped and the execution continues

    with statement-x. Therefore when the test-expression is true both statement block and statement-x are executed where as in other case only statement-x is executed. The flow of simple can be

    represented in the following way:

    Eg: Program to check if a number is even or not.

    #include

    void main(){

    int num;

    printf(Enter the number: );

    scanf(%d, &num);

    if(num%2==0)

    printf(The entered number %d is a even number, num);

  • 8/14/2019 C&DS Unit-I

    20/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:20

    if(num%2==1)

    printf(The entered number %d is a odd number, num);

    }

    De Morgans Rule: when applying logical NOT on complex relational expressions we have to

    keep in mind that the expressions will be evaluated using De-Morgans rule.

    Eg: !(a||b && !(p>q)) will be equivalent to !x && !b || !p < !q

    !(a && b) !a || !b

    if..else statement:

    This is the extension of simple ifstatement and the general form is

    if(test-expression)

    {

    Statement-block-x; //true block

    }

    else{

    Statement-block-y //false block

    }

    Statement-block-z;

    If the test-expression is true, then the Statement-block-x (true block) is executed; if the test-

    expression is false, then the Statement-block-y is executed. In both the cases the control is passed

    to Statement-block-z. The flow of the if..else statement can be show in the following way:

  • 8/14/2019 C&DS Unit-I

    21/26

  • 8/14/2019 C&DS Unit-I

    22/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:22

    The sequence of execution of the statements can be described using the following table:

    Lets represent condition as c-1,c-2, etc and statement as s-a, s-b, etc.

    c-1 c-2 c-3 s-a (executed Y/N) s-b s-c s-d s-e s-f

    True True True Y Y N Y N Y

    True True False Y Y N N N Y

    True False False Y N Y N N Y

    True False True Y N Y Y N Y

    False True/False True/False N N N N Y Y

    Flow Chart:

    C-1

    C-3

    C-2

    Statement-a

    Statement-c

    Statement-b

    Statement-f

    true

    false

    true

    false

    false Statement-dtrueStatement-e

    Entry

  • 8/14/2019 C&DS Unit-I

    23/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:23

    if-else ladder:

    The if-else ladder is another way of using multiple if. This is used when choice has to be made

    among multiple blocks of statements based on various test conditions. The general form of if-

    else ladder is:

    if(condition 1)

    statement-1;

    else if(condition-2)

    statement-2;

    else if(condition-n)

    statement-n;

    else

    statement-default;

    statement-x;

    In the above illustration when condition-1 is true only statement-1 is executed and when

    condition-2 is true only statement-2 is executed and in general when condition-n is true

    statement-n is executed. Therefore statement 1 through n are executed mutually exclusive (if one

    is executed rest all are skipped). When all n conditions are false, then the statement-default in the

    last else is executed. In an if-else ladder each else block is paired with the if statement

    immediately above it. The flow chart for the above general form is as follows:

  • 8/14/2019 C&DS Unit-I

    24/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:24

    Switch Statement:

    A switch control structure or statement is an alternative to if..else ladder. It is also knownas multiple branch selection statement. In order to use switch control statement, four keywordsare required. They are: switch, case and break. The general form follows:

    switch (expression)

    {

    case value-1:

    statement block-1;

    break;

    case value-2:

    statement block-2;

    break;

    default:

    default-block;

    break;

    }

    statement-x;

    The expression is an integer expression or a character. Cannot be a real or otherexpression.

    The value-, value-2, are the constants or constant expressions and are known as caselabels. These labels are the possible values of the expression given in switch. Case labels

    end with : which are followed by statement blocks.

    There cannot be two case labels with same value. When a switch is executed, the value ofexpression is compared with case labels and the

    statement block defined in that case is executed.

    The breakstatement at the end of each block causes the exit from the switch statement,there by achieving the exclusivity among the multiple statement blocks. In other words;

    when expression evaluates to value-1, only statement-block1 is executed; if it is value-2

    only statement-block-2 is executed and so on.

    The defaultexecuted when the value of expression matches none of the case labels. Thedefault section is generally defined at the end of switch and it is optional. When it is used

    as last section, usage of break statement is also optional.

    When default is not defined and none of the case labels match the expression value, theexecution continues to statement-x without executing any block in the switch.

  • 8/14/2019 C&DS Unit-I

    25/26

    C & DS for I MCA Unit-1 VVIT

    Staff: Janaki Ram N. Dept of IT Page:25

    Absence ofbreakin any of the case block makes the execution to continue with the nextcase statements as well until breakis reached or end of switch is reached. (Eg: Lab Ex-10)

    Flow Chart illustrating the selection of statements in switch:

    Ex: printf(Enter day value);

    scanf(%d,&day);

    switch(day)

    {

    case 1:

    printf(Sunday);break;

    case 2:

    printf(monday);break;

    case 3:

    printf(tueday);break;

    case 4:

    printf(wednesday);break;

    case 5:

    printf(thursday);break;

    case 6:

    printf(friday);break;case 7:

    printf(Saturday);break;

    default:

    printf(Illegal choice);}

  • 8/14/2019 C&DS Unit-I

    26/26

    C & DS for I MCA Unit-1 VVIT

    The goto statement:

    C supportsgoto statement to support unconditional branching from one point to anotherpoint of program. In other wordsgoto statement makes the flow of control to jump to alocation in the program unconditionally.

    goto requires a labelto identify the place where the control has to be jumped. Label canbe any valid name followed by a colon :. The labelis place just above the statementswhere the control has to be transferred.

    Depending on place of the label in the program goto will result in either forward jump orbackward jump. Below is a illustration:

    Eg:main(){

    int x,y;read:

    scanf(%d, &x);if(x