CP_UNIT_ 2_2011

download CP_UNIT_ 2_2011

of 68

Transcript of CP_UNIT_ 2_2011

  • 8/2/2019 CP_UNIT_ 2_2011

    1/68

    2.1 HISTORY OF C LANGUAGE

    ALGOL was the first computer language to use a block structure. In 1967, MartinRichards developed a language called BCPL (Basic Combined ProgrammingLanguage) at University of Cambridge primarily, for writing system software. In

    1970, Ken Thompson created a language using many features of BCPL andcalled it B. B was used to create early versions of UNIX operating system atBell Laboratories. Both BCPL and B were type less system programminglanguages.

    The major milestones in Cs development as a language are listed in Figure 2.1.

    Figure 2.1 Development of C Language

    C was developed by Dennis Ritchie at Bell Laboratories in 1972. It was evolvedfrom ALGOL, BCPL, and B. C uses many concepts of these languages and newfeatures like data types. UNIX operating system was coded almost entirely in C.

    To assure that the C language remains standard, in 1973, American NationalStandards Institute (ANSI) appointed a technical committee to define a standard

    for C. The committee approved a version of C in 1989 which is now known asANSI C. It was then approved by the International standards Organization (ISO)in 1990. The standard was updated in 1999.

    Prior to C, there are two broad types of languages:

    Applications languages: Basic and COBOL, which are portable butinefficient.

    Systems languages: Low Level and Assembly language, which are efficientbut non portable.

    2.1.1 CHARACTERISTICS OF C LANGUAGE

    The increasing popularity of C is due to its various features:

    C language is well suited for structured modular programming. Programdivided in to sub modules.

    C is a robust language with rich set of built-in functions and operators.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 1

  • 8/2/2019 CP_UNIT_ 2_2011

    2/68

    Programs written in C are efficient and fast. This is due to its variety ofdata types. It is many times faster than BASIC. For example, if a programto increment a variable from 0 to 1000 takes about one second in C whileit takes more than 30 seconds in BASIC.

    C is highly portable (code written in one machine can be moved to other).

    C is highly flexible. C allows access to the machine at bit level (using Lowlevel bitwise programming).

    C supports pointer implementation. Extensive use of pointers for memory,array, structures and functions.

    2.2 STRUCTURE OF A C PROGRAM

    A C program can be viewed as a group of building blocks, called functions. Afunction is a subroutine that includes one or more statements designed toperform a specific task. Figure 2.2 show the general structure of C program.

    Figure 2.2 General Structure of C program

    The preprocessor directives provide instructions to the preprocessor, to includefunctions from the system library, to define the symbolic constants and macro.The prototype of the user-defined functions (function declaration) is specifiedafter the preprocessor directives.

    The variables that are used in common by more than one function are calledGlobal Variables and are declared in global declaration section. This section canhave declarations for all the user-defined functions.

    Every C program must have one main() function. This function contains twoparts: declaration part and executable part. The declaration part declares all the

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 2

    Preprocessor directives

    User-defined functions prototype

    Global declaration section

    main(){

    // Local Declarations

    // Executable statements

    }

    User-defined functions

  • 8/2/2019 CP_UNIT_ 2_2011

    3/68

    Variables used in the executable part. These two parts must appear between theopening and the closing braces.

    The program execution begins at the opening brace and ends at the closingbraces. The closing brace of the main function is the logical end of the program.

    The executable portion of the main function will have three types of statements:Input, Output and Processing statements. All the statements in the declarationand Executable parts end with a semicolon.

    C program can have any number of user-defined functions and they aregenerally placed immediately after the main () function, although they mayappear in any order.

    All sections except the main () function may be absent when they are notrequired. C is a case sensitive language. Comments are enclosed within /* and*/. C program can be documented using these comment lines.

    Explanation to Example C Program

    #include

    It is a directive to C preprocessor. # (pound sign) line processed by preprocessorbefore the program is compiled tells preprocessor to include contents of stdio.hfile in the program. stdio.h standard input/output header file, Contains

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 3

    /************************************************

    * File Name: Hello.c *

    * Description: Simple C Program ** Author: B V Rajesh *

    * Date: 17/11/10 *************************************************/

    #include

    int main(){

    /* Display text on monitor */printf(" Hello World ");

    /* Return a success code to the Operating System */

    return 0;

    } /* End of Hello.c */

    OUTPUT

  • 8/2/2019 CP_UNIT_ 2_2011

    4/68

    information & declarations about functions. In this case, the printf library functionnot part of C programming language.

    /* comments */

    Ignored by the C compiler.

    int main(){return 0;}

    int is the return type of function

    return 0; Returns 0 to operating system. Indicates that program executedsuccessfully.

    main Every program consists of 1 or more functions. Must have a mainfunction.

    {} body of function = left & right brackets (block).

    2.3 CREATING AND RUNNING C PROGRAM

    There are four steps in the creation and running of C program:

    1. Writing and Editing Programs2. Compiling Programs3. Linking Programs4. Executing Programs

    Writing and Editing Programs

    The software used to write programs is known as a text editor. A text editor helpsus enter, change, and store data. Depending on the editor on our system, wecould use it to write letters, create reports, or write programs.

    After complete a program, we save our file to disk. This file will be input to thecompiler, it is known as a source file. Always source file should be created alongwith filename.c extension (Example Hello.c).

    Compiling Programs

    The C program (code) in a source file stored on the disk must be translated into

    machine language. This job is done by the compiler. It does two separateprograms: The preprocessorand translator.

    The preprocessor reads the source code and prepares it for the translator.While preparing the code, it scans for special instructions known as preprocessorcommands. These commands tell the preprocessor to look special code libraries,make substitutions in the code, and in other ways prepare the code for translationinto machine language.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 4

  • 8/2/2019 CP_UNIT_ 2_2011

    5/68

    Figure 2.3 Crating and running C Program

    After preprocessor has prepared the code for compilation, the translator does the

    actual work of converting the program into machine language. The translatorreads the translation unit and writes the resulting object module, contains code inmachine language (Hello.obj) to a file that can then be combined with otherprecompiled units to form the final program.

    Linking Programs

    If a source file contains library functions or functions defined in other source files,the linker combines these functions with main (), to create an executable file(Hello.exe).

    2.4 C FUNDAMENTALS

    Basic elements of C language constitute Character set, Identifiers, variables,keywords, and C tokens.

    2.4.1 CHARACTER SET

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 5

  • 8/2/2019 CP_UNIT_ 2_2011

    6/68

    Character set defines the characters that are used to form words, numbers andexpressions. The characters in C are grouped into the following categories:

    1. Letters2. Digits

    3. Special Characters4. White spaces

    Letters

    Digits

    0 1 2 3 4 5 6 7 8 9

    Special Characters

    " ( ) * + - / : = ! & $ ; < > % ? , . # @ { } [ ] \ |

    White Spaces

    Blank Space Horizontal tab carriage return new line Form Feed

    2.4.2 KEYWORDS

    Keywords are also known as reserve words, have standard and predefinedmeanings in C. These keywords can be used only for their intended purpose andthey cannot be used as programmer-defined identifiers. Keywords serve as basicbuilding blocks for program statements. All keywords must be written inlowercase. ANSI C supports 32 keywords. Table 2.1 shows the list of keywords.

    auto double int struct break else long switch

    case enum register typedef char extern return union

    const float short unsigned continue for signed void

    default goto sizeof volatile do if static while

    Table 2.1 ANSI C Keywords

    2.4.3 IDENTIFIERS

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 6

  • 8/2/2019 CP_UNIT_ 2_2011

    7/68

    Identifiers are names given to various programming elements such as variables,constants, and functions. It should start with an alphabet, followed by thecombinations of alphabets and digits. No special character is allowed exceptunderscore (_). An Identifier can be of arbitrarily long. Some implementation of Crecognizes only the first 8 characters and some other recognize first 32

    Characters.

    The following are the rules for writing identifiers in C:

    1. First character must be alphabetic character or underscore.2. Must consist only of alphabetic characters, digits, or underscore.3. Should not contain any special character, or white spaces.4. Should not be C keywords.5. Case matters (that is, upper and lowercase letters). Thus, the names

    count and Count refer to two different identifiers.

    Table 2.2 shows examples of legal and illegal C identifiers.

    Identifier Legality

    Percent Legal

    y2x5__fg7h Legal

    annual profit Illegal: Contains White space

    _1990_tax Legal but not advised

    savings#account Illegal: Contains the illegal character #

    double Illegal: Is a C keyword

    9winter Illegal: First character is a digit

    2.2 Examples of legal and illegal C identifiers

    2.4.4 C TOKENS

    In a passage of text, individual words and punctuation marks are called tokens.The compiler splits the program into individual units, are known as C tokens. Chas six types of tokens as shown in Figure 2.4. C programs are written using

    these tokens and the syntax of C language.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 7

  • 8/2/2019 CP_UNIT_ 2_2011

    8/68

    Figure 2.4 C tokens and examples

    For our first program (Hello.c), the tokens are shown in the Figure 2.5.

    main

    ( ) { printf ( "Hello World" ) ; }

    Figure 2.5 C tokens for Hello.c program

    2.4.5 VARIABLES

    When you want to process some information, you can save the valuestemporarily in variables. A variable is a data name that may be used to store adata value. The value represented by the identifier may be changed during theexecution of the program.

    Variable names must be chosen in such a way that it should be a valid identifiersatisfying all the basic conditions. Variable names are case sensitive (ex: variableEMPNAME is different from variable empname). The variable name can bechosen by the programmer in a meaningful way so as to reflect its function ornature in the program.

    Rules for writing variable names are same as identifier naming rules.

    Examples:

    Valid: sum student_sal tot_sec marks1

    Invalid: 1area temp% emp name

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 8

  • 8/2/2019 CP_UNIT_ 2_2011

    9/68

    2.5 DATA TYPES

    Data types are used to indicate the type of value represented or stored in avariable, the number of bytes to be reserved in memory, the range of values thatcan be represented in memory, and the type of operation that can be performed

    on a particular data value.

    ANSI C supports 3 categories of data types:

    1. User Defined data types2. Built-in data types3. Derived data types

    Figure 2.6 shows different categories of data types.

    Figure 2.6 Different Categories of Data types

    Built-in Data types

    Built-in data types are also known as primary or Fundamental or Basic orPrimitive data types. C uses the following basic data types

    int integer quantitychar character (stores a single character)float single precision real (floating point) numberdouble double precision real (floating point) number

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 9

  • 8/2/2019 CP_UNIT_ 2_2011

    10/68

    Integer Data Type

    Integers are whole numbers with a range of values supported by aparticular machine.

    The keyword int is used to specify an integer variable.

    Generally integer occupy one word of storage, and since the word sizes ifmachine vary(typically, 16 or 32 bits) the size of an integer that can bestored depends on the computer.

    16-bit integer can have values in the range of - 32768 to 32767 (-2^15 to2^15-1). One bit is used for sign.

    For 32-bit integer can have values in the range of -2147483648 to2147483647.

    Character Data Type

    The shortest data type is character.

    The keyword char is used to declare a variable of a character type. It is stored in 1 byte in memory.

    Corresponding integer values for all characters are defined in ASCII code(American Standard Code for Information Interchange).

    For example, character constant a has an int value 97, b - 98, A - 65etc.

    Character can have values in the range of -128 to 127.

    The floating Point Data Type

    The data type float represents a floating point number (also called a realnumber).

    The keyword float is used to declare a variable of the type float.

    The float type variable is usually stored in 32 bits, with 6 digits of precision.

    float can have values in the range of 3.4E-38 to 3.4 E+38.

    The double Data Type

    A floating point number can also be represented by the double data type.

    The data type double is stored on most machines in 8 bytes which is about15 decimal places of accuracy.

    To declare a variable of the type double, use the keyword double. double can have values in the range of 1.7E-308 to +1.7E+308.

    Void Data type

    Defines an empty data type which can then be associated with some datatypes. It is useful with pointers.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 10

  • 8/2/2019 CP_UNIT_ 2_2011

    11/68

    Big and small numbers

    Scientific notation is often used to write a big or small numbers.

    A number is written as the combination of the mantissa, which is followedby the prefix e or E, and the exponent.

    For example,87000000 = 8.7e7- 550 = -5.5e20.00000000031 = 3.1e-10.

    Note: float and double data types are used to store fractional values. Thedifference between float and double is in terms of the precision.

    Type Modifiers

    The basic data types may have various modifiers (or qualifiers) preceding

    them, except type void. A modifier is used to alter the meaning of the base data type to fit the

    needs of various situations more precisely.

    The list of modifier is given below.

    The modifiers signed, unsigned, long short may be applied to integer basetypes.

    We can apply unsigned and signed to characters. Long may also beapplied to double.

    The difference between signed and unsigned integers is in the way high-order bit (sign bit) of the integer is interpreted.

    If sign bit is 0, then the number is positive; if it is 1, then the number isnegative.

    Table 2.3 shows the different data types, number of bytes occupied by then andthe range.

    Data Type MeaningSize

    (in Bytes) Range

    unsignedchar

    unsignedcharacter(positive) 1

    0 to 255

    signed char represents singlecharacter 1

    -128 to 127

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 11

  • 8/2/2019 CP_UNIT_ 2_2011

    12/68

    Data Type MeaningSize

    (in Bytes)Range

    unsigned int

    unsignedshort int

    represents positive

    integer numbers

    2 0 to 65,535

    shortsigned shortshort intsigned shortintint

    represents both positiveand negative integerquantity

    2 -32,768 to 32,767

    unsigned

    long

    represents positive long

    integer

    4 0 to 4,294,967,395

    longsigned longlong intsigned longint

    represents both positiveand negative longnumbers

    4 -2,147,483,648 to2,147,483,647

    float floating point number 4 3.4*(10-38) to3.4*(10+38)double A more accurate floating

    point number than float8 1.7*(10-308)

    to1.7*(10+308)long double increases the size of

    double10 3.4*(10-4932)

    to3.4*(10+4932)

    void defines an empty datatype.

    Table 2.3 Data types with Size and Range

    Derived Data Types and User Defined data types are the combination of primitivedata types. They are used to represent a collection of data. They are:

    Arrays

    Structures

    Unions

    Enumerated

    Pointers

    Note: Number of bytes and range given to each data type is platform dependent.

    2.6 VARIABLE DECLARATIONS

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 12

  • 8/2/2019 CP_UNIT_ 2_2011

    13/68

  • 8/2/2019 CP_UNIT_ 2_2011

    14/68

    tot =0; // tot is assigned with a value 0bonus=100; // bonus is assigned with a value 100

    Note: Assigning values using input functions will be discussed later.

    2.7 CONSTANTS

    A constant in C refers to the fixed values that do not change during the executionof a program. Like variables constants have a data type.

    2.7.1 CONSTANT REPRESENTATION

    C supports several representations (or types) of constants as shown in Figure2.7.

    Figure 2.7 Basic types of Constants with examples

    Integer Constants

    An integer constant refers to a sequence of digits. If we code the number as aseries of digits, its type is signed integer, or long integer if the number is large.We can override this default by specifying unsigned (u or U), and long (l or L),after the number. There is no way to specify a short int constant. Table 2.4 showsseveral examples of integer constants.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 14

  • 8/2/2019 CP_UNIT_ 2_2011

    15/68

    Embedded spaces, commas, and non-digit characters are not permitted betweendigits. For example,

    12 345 10,000 $1000

    Are illegal integers.

    Representation Value Type

    +123 123 int

    -378 -378 int

    -32271L -32,271 long int

    76542LU 76,542 unsigned long unit

    Table 2.4 Examples of Integer Constants

    Real Constants

    The default form for real constants is double. If we want the resulting data type tobe float or long double, we must use a code to specify the desired data types. torepresent float value we can use f or F , l and L are used to represent longdouble. Table 2.5 shows several examples of real constants.

    Representation Value Type

    0. 0.0 double

    .0 0.0 double

    2.0 2.0 double3.1416 3.1416 double

    -2.of -2.0 float

    3.1415926536L 3.1415926536 long double

    Table 2.5 Examples of Real ConstantsSingle Character Constants

    A single character constant (or character constant) contains a single characterenclosed between two single quote marks. Character constants have integer

    values known as ASCII values.

    Examples of character constants are:

    a 5 S

    Note that the character constant 9 is not the same as the number 9.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 15

  • 8/2/2019 CP_UNIT_ 2_2011

    16/68

    String Constants

    A string constant is a sequence of characters enclosed in double quotes. Thecharacters may be letters, numbers, special characters and blank space.Examples are:

    April 1984 David A

    Note that a character constant x is not equals to the string X.

    Escape Characters

    If a character precedes with a \ (backslash) it is called escape character (orbackslashed characters or control characters). It conveys a special meaning tothe printf () function other than the normal character it represents. A list of escapecharacters is given in table 2.6.

    Escape Sequence Description

    \b Back Space

    \t (Horizontal) Tab

    \n New line feed (LF)

    \v Vertical Tab

    \f Form Feed

    \r Carriage Return (CR)

    \\ Back Slash (Solidus)

    \ Single quote (grave accent)\ Double quote

    \o null (C string terminator)

    null (Empty) string

    \c continuation (UNIX)

    \a Alert (beep sound)

    Table 2.6 Escape characters in C

    2.7.2 CODING CONSTANTSThere are three different ways we can code (or use) constants in our programs:literal constants, defined constants, and memory constants.

    Literal Constants

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 16

  • 8/2/2019 CP_UNIT_ 2_2011

    17/68

    A literal is an unnamed constant used to specify data. If we know that the datacannot change, then we can simply code the data value itself in a statement. Forexample 10 is used in the following statement.

    Sum=a+10;

    Defined constants

    Another way to use a constant is to use the preprocessor command define. Likeall preprocessor commands, it is prefaced with the pound sign (#). The definedconstant contains the following form:#define identifier value

    Examples,#define pi 3.14 // defines pi with 3.14#define max 10 // defines max with 10

    Memory Constants

    The third way to use constant is with memory constants. Memory constants use aC const keyword, to indicate that the data cannot be changed. The general form:

    const data_type identifier=value;

    Here the value of the identifier cannot be changed in the program.

    Examples,

    const int max=10;const float pi=3.14;

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 17

    /***************************************************** Name: Const.c ** Author: B V Rajesh *

    * Date: 18/11/10 ** Description: a program demonstrating constants usage *

    ****************************************************/

    #include

    #define PI 3.14

    void main()

    {/* Variable Declaration */

    const float val=3.14;

    /* Display Values */printf("\n Literal Constant = %f",3.14);

    printf("\n Defined constant = %f", PI*3.14);

    printf("\n Memory Constant = %f",3.14*PI*val);

    /* keep console screen until a key stroke */

    getch();}

  • 8/2/2019 CP_UNIT_ 2_2011

    18/68

    2.8 INPUT/OUTPUT STATEMENTS

    Reading, processing, and printing of data are the three essential functions of acomputer program. Most programs take some data as input and display theprocessed data, often known as information or results/ So far we have seen twomethods of providing data to the program variables. One method is to assignvalues to variables through the assignment statements such as n=10; a=5; andso on. Another method is to use the input functions.

    All the input/output operatios are carried out through functions defined instandard input output library (stdio.h).

    There are two types of Input and Output (I/O) statements: Unformatted I/Ostatements and Formatted I/O statements. We will discuss later Unformatted I/O.

    Formatted I/O Statements

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 18

    OUTPUT

  • 8/2/2019 CP_UNIT_ 2_2011

    19/68

    Formatted input/output refers to an input data that has been arranged in aparticular format.

    2.8.1 FORMATTED INPUT FUNCTION

    scanf() function is used to read formatted data values. For example consider thefollowing data:

    56.78 123 c

    This line contains three pieces of data, arranged in a particular form. Such datahas to be read conforming to the format of its appearance. For example, the firstpart of the data should be read into a variable float, the second into int, the thirdpart into char. This is possible by using scanf function.

    General Form:

    scanf (format control string, &var1, &var2&varn);

    The format Control string is a listing of the data types of the variables tobe input and the & in front of each variable name tells the system Whereto store the value that is input.

    Format control string and variables are separated by comma.

    Format control string, also known as control string contains fieldspecifications (or format specifier), which directs the interpretation of input

    data. It consist of the following form:

    %code (type-specifier)

    The percent sign (%) indicates that a conversion specification follows,code specifies data type.

    By default, the delimiter while reading the values is space. Delimiter canbe user-defined.

    Format specifications contained in the format control string, must matchthe variable list in order.

    Input data values must be separated by spaces and must match thevariables receiving the input in the same order.

    To read a string using %s, & need not be used.

    The format specifers for different data types shown in Table 2.7.

    2.8.2 FORMATTED OUTPUT FUNCTION

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 19

  • 8/2/2019 CP_UNIT_ 2_2011

    20/68

    printf() function is used to output the values. This function returns the number ofcharacters printed.

    General Form:

    printf (format control string, var1,var2varn);

    Format Control String Consist of three types of things:

    1. Characters that will be printed on the screen as they appear.2. Format specifications that define the output format for display of each

    value.3. Escape sequence characters such as \n,\t..,

    The format control string indicates how many arguments follow and what theirtypes are. var1, var2varn are the variables whose values are formatted andprinted according to the specifications of the control string. The arguments shouldmatch in number, order and type with the format specifications.

    Format Conversion Specifiers

    Table 2.7 shows Format Specifiers for different data types in C.

    Data Type Format Specifier Meaning

    charsigned charunsigned char

    %c displays a single character

    intsigned int

    %d , %i a decimal (base 10) integer

    unsigned int %u unsigned decimal integer short %h short integer short intsigned short int

    %hd , %hi short integer

    unsigned shortint

    %hu unsigned decimal integer

    long intsigned long int %ld , %li long integer

    unsigned longint

    %lu unsigned long decimal integer

    Data Type Format Specifier Meaning

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 20

  • 8/2/2019 CP_UNIT_ 2_2011

    21/68

    float %e a floating point value in exponentialnotation

    %f a floating point value

    %g a number in either "e" or "f" format

    Double %lf, %le, %lg double precision valuelong double %Lf, %Le, %Lg long double precision value

    %s displays a string of characters

    %x a hexadecimal integer %o an octal integer

    Table 2.7 Format Specifiers for different data types

    Examples,

    printf (char=%c, int=%d, floating point=%f ,ch, i, x);printf (sum = %f, sum);

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 21

    /* Read Values */

    printf("\n Enter a character : ");scanf("%c",&c);

    printf("\n Enter a integer : ");

    scanf("%d",&i);printf("\n Enter a float : ");

    scanf("%f",&f);

    /* Display values */

    printf("\n The Given character is %c",c);printf("\n The value of i= %d",i);

    printf("\n The value of f= %f",f);

    /* keep console screen until a key stroke */

    getch();

    }

    OUTPUT

    /******************************************************

    * Filename : Demo.c ** Author : B V Rajesh *

    * Date : 30/11/10 ** Description : program demonstrates Reading Data *

    * *

    ******************************************************/

    #include

    void main()

    {

    /* variable declaration */

    char c;int i;float f;

  • 8/2/2019 CP_UNIT_ 2_2011

    22/68

    printf (name = %c, name);

    2.9 OPERATORS

    C supports a rich set of operators. An operator is a symbol that tells the computerto perform mathematical or logical operations. Operators are used in C to operateon data and variables.

    C operators can be classified into a number of categories. They include:

    1. Arithmetic Operators2. Relational Operators3. Logical Operators4. Assignment Operators5. Increment & decrement Operators6. Conditional Operators7. Bitwise Operators8. Special Operators

    2.9.1 ARITHMETIC OPERATORS

    C provides all basic arithmetic operators which are work in the same way as theydo in other languages. It can operator any built in data type allowed in C. Table2.8 shows different types of arithmetic operators in C.

    C Operation Binary Operator C Expression

    Addition + a + b

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 22

  • 8/2/2019 CP_UNIT_ 2_2011

    23/68

    Subtraction - a - b

    Multiplication * a * b

    Division(second operand must benonzero)

    / a / b

    Modulus (Remainder bothoperands must be integer andsecond operand must be nonzero)

    % a % b

    Table 2.8 Arithmetic OperatorsInteger arithmetic:

    When both operands in a single arithmetic expression such as a+b areinteger the expression is called integer expression.

    The integer arithmetic always yields an integer value. Integer divisiontruncates any fractional part.

    Let a=14,b=4 Then

    a+b = 14+4 = 18a-b = 14-4 = 10a*b = 14* 4 = 56a/b = 14/4 = 3 (truncates fraction part)a%b = 14%4 = 3 (remainder after division)

    Floating point arithmetic

    When an arithmetic operation is preformed on two real numbers or fractionnumbers such an operation is called floating point arithmetic.

    The floating point results can be truncated according to the propertiesrequirement.

    The remainder operator is not applicable for floating point arithmeticoperands.

    Let x = 14.0 and y = 4.0 then

    x + y = 18.0

    x y = 10.0x * y = 56.0x / y = 3.50

    Mixed mode arithmetic

    When one of the operand is real and other is an integer and if thearithmetic operation is carried out on these 2 operands then it is called asmixed mode arithmetic.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 23

  • 8/2/2019 CP_UNIT_ 2_2011

    24/68

    If anyone operand is of real type then the result will always be real thus15/10.0 = 1.5.

    2.9.2 RELATIONAL OPERATORS

    We often compare two quantities and depending on their relation takecertain decision. Comparing the age of two people, price of two items.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 24

    /*********************************************************** Filename : Arithmetic.c *

    * Author : B V Rajesh ** Date : 20/11/10 *

    * Description : a program demonstrates C arithmetic operators *

    ***********************************************************/#include

    void main(){

    /* Variable declaration & initializations */

    int x = 10, y = 20 ,remainder = 0;

    /* display values of x and y */printf("x = %d\n y=%d",x,y);

    /* demonstrate = operator + */y = y + x;

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

    /* demonstrate - operator */

    y = y - 2;printf("y = y - 2; y = %d\n",y);

    /* demonstrate * operator */y = y * 5;printf("y = y * 5; y = %d\n",y);

    /* demonstrate / operator */y = y / 5;

    printf("y = y / 5; y = %d\n",y);

    /* demonstrate modulus operator % */

    remainder = y %3;

    printf("remainder = y %% 3; remainder = %d\n",remainder);/* keep console screen until a key stroke */ getch(); }

    OUTPUT

  • 8/2/2019 CP_UNIT_ 2_2011

    25/68

    An expression containing relational operator termed as relationalexpression. A simple relational expression contains only one relationaloperator and takes the following form:

    exp1 relational_operator exp2

    Where exp1 and exp2 are expressions, which may be simple constants,variables or combination of them.

    The value of relational expression is either 1 or 0. If It is 1 the specifiedrelational is true and 0 If the specified relation is false.

    Given below is a list of examples of relational expressions and evaluatedvalues.

    6.5 0 FALSE10 < 7 + 5 TRUE

    Relational expressions are used in decision making statements of Clanguage such as if, while and for statements to decide the course ofaction of a running program.

    Different types of Relational Operators and equality operators are listed inTable 2.9 and 2.10.

    C operation Relational Operator C expression

    greater than > x > y

    less than < x < y

    greater than or equal to >= x >= y

    less than or equal to j);

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

    printf("i

  • 8/2/2019 CP_UNIT_ 2_2011

    26/68

    2.9.3 LOGICAL OPERATORS

    Used to combine more than one relational test into a compound relationaltest.

    The logical operators are used if we want to test more than one conditionand make decision.

    The first two (&&, ||) never appear by themselves (always go betweenrelational tests).

    Truth Tables show you how to achieve results from an if statement that

    uses these operators. Table 2.11 shows different categories of logical operators.

    Operator Meaning

    && Logical AND(true only if both the operands are true)

    || Logical OR(true if either one operand is true)

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 26

    OUTPUT

  • 8/2/2019 CP_UNIT_ 2_2011

    27/68

    ! Logical NOT(negate the operand)

    Table 2.11 logical operators

    Logical AND (&&)

    This operator is used to evaluate 2 conditions or expressions withrelational operators simultaneously.

    If both the expressions to the left and to the right of the logical operator istrue then the whole compound expression is true (1), otherwise false (0).Table 2.12 shows the truth table of Logical And (&&).

    A B A&&BA||B

    0 0 00

    0 1 0 1

    1 0 0 1

    1 1 1 1

    Table 2.12 Truth table for Logical And, Logical OR

    Logical OR (||)

    The logical OR is used to combine 2 expressions or the conditionevaluates to true if any one of the 2 expressions is true. Table 2.12 showsthe truth table of Logical OR(||).

    Logical NOT (!)

    The logical not operator takes single expression and evaluates to true ifthe expression is false and evaluates to false if the expression is true. Inother words it just reverses the value of the expression.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 27

    A ! A

    0 1

    1 0

    /*****************************************************

    * Filename : Logical.c * Author : B V Rajesh

    * Date : 20/11/10 * Description : a program demonstrates C Logical operators

    * *****************************************************/

    #include

    void main()

    {/* Variable Declaration */

    int a, b;

    /* Read the values of a and b */

    printf("Enter a: ");scanf("%d", &a);

    printf("Enter b: ");scanf("%d", &b);

    /* logical operations */

    printf("a && b %d\n", a && b);

    printf("a || b %d\n", a || b);printf("!a !b %d %d\n", !a, !b);

    getch(); /* keep console screen until a key stroke */}

  • 8/2/2019 CP_UNIT_ 2_2011

    28/68

    2.9.4 ASSIGNMENT OPERATORS

    Assignment Operators are used to assign the result of an expression to avariable. Assignment operator can be used in three ways.

    Single assignment consists of the form a = 4;

    Multiple assignment used for variable initialization a=b=c=d=0;

    Compound assignment: Assignment operators are used to combine the= operator with one of the binary arithmetic operators. Table 2.13 showsexamples of compound assignment.

    Example,salary = salary + 1000;salary += 1000; //is the same as above

    Operator Example Equivalent Statement

    += c += 7 c = c + 7

    -= c -= 8 c = c - 8

    *= c *= 10 c = c * 10

    /= c /= 5 c = c / 5

    %= c %= 5 c = c % 5

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 28

    OUTPUT

  • 8/2/2019 CP_UNIT_ 2_2011

    29/68

    Table 2.13 Compound Assignment in C

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 29

    /* demonstrate /= operator */

    y /=2;printf("y /=2;y = %d\n",y);

    /* keep console screen until a key stroke */

    getch();

    }

    OUTPUT

    /******************************************************

    * Filename : Assignment.c *

    * Author : B V Rajesh ** Date : 20/11/10 ** Description: a program demonstrates C Assignment operator *

    * *

    *******************************************************/

    #include

    void main()

    {/* Variable declaration */

    int x = 10;

    /* demonstrate = operator */

    int y = x;printf("y = %d\n",y);

    /* demonstrate += operator */

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

    /* demonstrate -= operator */y -=5;

    printf("y -=5;y = %d\n",y);

    /* demonstrate *= operator */

    y *=4;printf("y *=4;y = %d\n",y);

  • 8/2/2019 CP_UNIT_ 2_2011

    30/68

    2.9.5 THE INCREMENT AND DECREMENT OPERATORS

    We can add or subtract 1 to or from variables by using increment (++) and

    decrement (--) operators. Te operator ++ adds 1 to the operand and the operator subtracts 1.

    They can go on either side of the modified variable. They can apply in twoways postfix and prefix.

    Prefix form: variable is changed before expression is evaluated

    Postfix form: variable is changed after expression is evaluated.

    We can use increment and decrement operators in loops.

    Table 2.14 shows the working of increment and decrement operator.

    Operator Example Meaning Equivalent Statements

    ++ i++ postfix i=i+1; i+=1;

    ++ ++i prefix i=i+1; i+=1;

    -- i-- postfix i=i-1; i -=1;

    -- --i prefix i=i-1; i-=1;

    Table 2.14 Working of Increment and Decrement Operators

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 30

    /********************************************************

    * Filename : Increment.c *

    * Author : B V Rajesh ** Date : 20/11/10 ** Description: demonstrates increment and Decrement operators *

    * *

    ********************************************************/

    #include

    void main ()

    {

    /* Variable Declaration */int a=4, b=5, result;

    /* Increment operator */printf("Postfix increment %d\n", a++);

    printf("Now a is %d\n", a);

    printf("Prefix increment %d\n", ++a);printf("Now a is %d\n", a);

    /* Decrement Operator */

    printf("Postfix decrement %d\n", b--);printf("Now b is %d\n", b);

    printf("Prefix decrement %d\n", --b);

    printf("Now b is %d\n", b);

    /* keep console screen until a key stroke */

    getch();}

  • 8/2/2019 CP_UNIT_ 2_2011

    31/68

    2.9.6 THE CONDITIONAL OPERATOR

    Cs only conditional (or ternary) operator requires three operands (asopposed to the unarys single and the binarys double operandrequirement).

    A ternary operator pair ? in C used to construct conditional expression.

    Syntax :conditional_expression? expression1: expression2;

    The conditional_expression is any expression that results in a True(nonzero) or false (zero) answer.

    If True expression1 executes, otherwise expression2 executes.

    Example:sales > 1000)? Bonus = 500: Bonus = 0;(a > b)? (ans = 10): (ans = 25);ans = (a > b)? (10): (25);

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 31

    /*******************************************************

    * Filename : Ternary.c ** Author : B V Rajesh *

    * Date : 20/11/10 ** Description: a program demonstrates C conditional operator *

    *******************************************************/

    #include

    void main()

    {/* Variable Declaration */

    int a,b,max;

    /* Read the values of a and b */

    printf(" Enter the values of a: ");

    scanf("%d",&a);printf(" Enter the values of b: ");

    scanf("%d",&b);

    max=(a>b) ? a : b ;

    printf("\n Max=%d", max);

    /* keep console screen until a key stroke */

    getch();

    }

    OUTPUT

  • 8/2/2019 CP_UNIT_ 2_2011

    32/68

    2.9.7 BITWISE OPERATORS

    C has a special operator known as Bitwise operator for manipulation of data at bitlevel. These operators are used for testing the bits or shifting them right or left.Bitwise operator may not be applied for float and double. Table 2.15 showsdifferent categories of Bitwise Operators.

    Table 2.15 Different Categories of Bitwise Operators

    Bitwise and Operator (&)

    It is a binary operator it requires two integral operands. It does a bit-by-bitcomparison between the operands. The result of the comparison is 1 only whenboth bits are 1. It is 0 otherwise. Truth Table is shown in table 2.16.

    Let us consider two variables a and b whose values are 10 and 20, then a & b bitby bit comparisons are shown below:

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 32

    Operator Meaning

    & Bitwise AND

    | Bitwise OR

    ^ Bitwise exclusive OR

    > Shift right

    ~ ones complement

  • 8/2/2019 CP_UNIT_ 2_2011

    33/68

    a&b results in decimal value 0.

    A B A&B A|B A^B

    0 0 0 0 0

    0 1 0 1 1

    1 0 0 1 1

    1 1 1 1 0

    Table 2.16 Truth Tables for Bitwise And, Inclusive OR, Exclusive OR

    Bitwise Inclusive OR Operator (|)

    It is a binary operator it requires two integral operands. It does a bit-by-bit

    comparison between the operands. The result of the comparison is 0 when bothbits are 0.it is 1 otherwise. Truth Table is shown in table 2.16.

    Let us consider two variables a and b whose values are 10 and 20, then a | b bitby bit comparisons are shown below:

    a|b results in decimal number 30.

    Bitwise Exclusive or Operator (^)

    It is a binary operator it requires two integral operands. It does a bit-by-bitcomparison between the operands. The result of the comparison is 1 when onlyone operand is 1.it is 0 other wise. Truth Table is shown in table 2.16.

    Let us consider two variables a and b whose values are 10 and 20, the a ^ b bit

    by bit comparisons are shown below:

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 33

  • 8/2/2019 CP_UNIT_ 2_2011

    34/68

    a^ b results in decimal number 30.

    Ones Complement Operator (~)

    It is a unary operator applied to integral values. It complements the bits in theoperand, which is reverse bit value. Check sum used when detecting receivingbits are valid or not.

    Truth Table is shown below.

    A ! A

    0 1

    1 0

    Shift Operators

    The shift operators move bits to the right or left, for this purpose we have twocategories: Bitwise Shift-Right Operator (>>), Bitwise Shift-Left Operator ()

    It is a binary Operator that requires two integral operands. the first one is value tobe shifted. the second one specifies number of bits to be shifted. The generalform is as follows:

    Variable >> expression;

    When bits are shifted right, the bits at the rightmost end are deleted. The shiftright operation is shown in Figure 2.8.

    Example,a=8;b=a>>1; // assigns 4 after shift right operation

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 34

  • 8/2/2019 CP_UNIT_ 2_2011

    35/68

    Figure 2.8 Shift-right Operation

    Shift right operator divides by a power of 2. I.e a>>n results in a/2n. where n isnumber of bits to be shifted.

    Bitwise shift Left Operator (

  • 8/2/2019 CP_UNIT_ 2_2011

    36/68

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 36

    /***************************************************************** Filename : Bits.c *

    * Author : B V Rajesh *

    * Date : 20/11/10 ** Description: program a demonstration of C bitwise operators *

    * *****************************************************************/

    #include

    void main(){

    /* Variable Declaration */

    int d1 = 10; /* 01010 */int d2 = 20; /* 10100 */

    int d3;

    /* Display values of d1 and d2 */

    printf("\nd1=%d",d1);printf("\nd2=%d",d2);

    d3 = d1 & d2; /* 01010 & 10100 = 00000 */

    printf("\n Bitwise AND d1 & d2 = %d",d3);

    d3 = d1 | d2; /* 01010 | 10100 = 11110 */

    printf("\n Bitwise OR d1 | d2 = %d",d3);

    d3 = d1 ^ d2;/* 01010 ^ 10100 = 11110 (=30) */

    printf("\n Bitwise XOR d1 ^ d2 = %d",d3);

    d3 = ~d1; /* ones complement of 1010 is 1111 0101 (-11) */printf("\n Ones complement of d1 = %d",d3);

    d3 = d12; /* 0000 0101 right shift by 2 bits is 0000 0010 (2) */

    printf("\n Right shift by 2 bits d1 >> 2 = %d",d3);

    /* keep console screen until a key stroke */

    getch();

    }

    OUTPUT

  • 8/2/2019 CP_UNIT_ 2_2011

    37/68

    2.9.8 SPECIAL OPERATORS

    C supports the following special category of operators.

    & Address operator

    * Indirection operator, Comma operator sizeof() Size of operator

    . And Member selection Operators

    comma Operator

    It doesnt operate on data but allows more than one expression to appearon the same line, e.g.

    int i = 10, j = 20;

    Is used to separate arguments in Input/output function calls, e.g.

    printf (%d %.2f %c, an integer, a float, a char);

    The comma allows some interesting statements. Example,

    i = 10; //i is assigned the value 10j = (i = 12, i + 8); //i is assigned 12 added to 8 produces 20

    Comma operator is used in Functions arguments separating.

    The size of Operator

    Is a unary operator (operates on a single value). Produces a result that represent the size in bytes or the data specified

    format size of data.

    Example:int a = 5;sizeof a; //produces 2

    Directly applied to data type name also, syntax as follows:

    sizeof(data type)

    example,sizeof(char); // produces 1sizeof(int); // produces 2

    2.10 EXPRESSIONS

    An expression is a sequence of operands and operators that reduces to a singlevalue. Figure 2.10 shows different categories of expressions in C.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 37

  • 8/2/2019 CP_UNIT_ 2_2011

    38/68

    Figure 2.10 Different Categories of Expressions

    Primary Expressions

    The most elementary type of expression is a primary expression. It consists ofonly one operand with no operator. In C, the operand in the primary expression

    can be a name, a constant, or a parenthesized expression.

    Name is any identifier for a variable, a function, or any other object in thelanguage. The following are examples of some used as primary expressions:

    a price sum max

    Literal Constants is a piece of data whose value cant change during theexecution of the program. The following are examples of literal constants used inprimary expression:

    A 56 98 12.34

    Any value enclosed in parentheses must be reduced in a single value is called asprimary expression. The following are example of parentheses expression:

    (a*x + b) (a-b*c) (x+90)

    Postfix Expression

    The postfix expression consists of one operand followed by one operator. Thegeneral syntax as follows:

    operand (variable) operator

    The postfix Increment and decrement will increase or decrease the value ofvariable by 1. The value of postfix increment expression is determined before thevariable is increased. Figure 2.11 illustrates the working of postfix increment.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 38

  • 8/2/2019 CP_UNIT_ 2_2011

    39/68

    Figure 2.11 Working of Postfix Expression

    Prefix Expression

    In prefix expression, the operator comes before the operand. The general syntax

    as follows:

    operator operand (variable)

    The prefix Increment and decrement will increase or decrease the value ofvariable by 1. The value of variable is increased before prefix incrementexpression is determined. Figure 2.12 illustrates the working of prefix increment.

    Figure 2.12 Working of Postfix Expression

    Unary Expression

    A unary expression, like a prefix expression, consists of one operator and oneoperand. The operator comes before the operand. A Unary operator comes intwo forms: Unary plus (+), Unary Minus (-). Some of the examples of unaryexpressions are shown in Table 2.17.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 39

  • 8/2/2019 CP_UNIT_ 2_2011

    40/68

    Table: 2.17 Examples of Unary Expression

    Binary Expression

    Binary expressions are formed by an operator operand combination. They areperhaps the comst common expression category. Any two numbers added,subtracted etc..,. It takes of the form:

    Examples:a + b a*b + c a - b

    Assignment Statement

    Assignment statement is used to assign a value to a variable. In C, theassignment operator is =.

    The left side of the = is always a variable, whose address specifieswhere to store the data on the right side.

    For example, the statement x = y + z; computes the value of y+z and store

    the result in the variable x. However, x + 3 = y; is not legal because x + 3 is an arithmetic expression

    (i.e.) not a storage location.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 40

  • 8/2/2019 CP_UNIT_ 2_2011

    41/68

    2.11 OPERATOR PRECEDENCE AND ASSOCIATIVITY

    Operator Precedence

    Defines the order in which operators are applied.

    The order is not defined explicitly by the language, Inferred from thesyntax definition.

    Precedence is applied before Associativity to determine the order in whichexpressions are evaluated. Associativity is then applied, if necessary.

    Parentheses have highest precedence. The order of evaluation can bechanged by introducing parentheses into an expression.

    Table 2.18 shows the precedence level of different operators.

    Operator Associativity

    Associativity is used to determine the order in which operators with same

    precedence are evaluated in an expression. Associativity can be left-to-right or right-to-left.

    Left-to-right Associativity evaluates the expression by proceeding from theLeft to Right as shown in Figure 2.13.

    Right-to-left evaluates the expression by proceeding from the right to leftas shown in Figure 2.14.

    Unary and assignment operators are right-to-left associative.

    All other operators are left-to-right associative.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 41

  • 8/2/2019 CP_UNIT_ 2_2011

    42/68

    Table 2.18 Precedence and Associativity of Operators in C

    2.12 TYPE CASTING IN C

    C provides a mechanism for allowing the programmer to change the default datatype of a given expression. This is called Typecasting. Typecasting allows avariable to behave like a variable of another type.

    C provides two types of type conversions: Implicit and Explicit type conversions.Implicit type conversion

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 42

  • 8/2/2019 CP_UNIT_ 2_2011

    43/68

    In implicit type conversion, if the operands of an expression are of different types,the lower data type is automatically converted to the higher data type before theoperation evaluation. The result of the expression will be of higher data type. Thefinal result of an expression is converted to the type of the variable on the LHS of

    the assignment statement, before assigning the value to it.

    Examples,

    char c = 'a';int i;i = c; /* i is assigned by the ascii of a */

    int i = 5 , j = 1;float x = 1.0, y;y = x / i; /* y = 1.0 / 5.0 */

    y = j / i; /* y = 1 / 5 so y = 0 */

    The C compiler uses the following rules to promote the types if two operands donot agree in expressions.

    Figure 2.15 C Promotion Rules

    Explicit type conversion

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 43

  • 8/2/2019 CP_UNIT_ 2_2011

    44/68

    In explicit type conversion, the user has to enforce the compiler to convert onedata type to another data type by using typecasting operator. This method oftypecasting is done by prefixing the variable name with the data type enclosedwithin parenthesis. The original value of the variable is not altered.

    General form:

    (data_type) expression

    (data_type) can be any valid C data type and expression is any variable, constantor a combination of both.

    Example,

    float sum;sum = (int) (1.5 * 3.8);

    The typecast (int) tells the C compiler to interpret the result of (1.5 * 3.8) as theinteger 5, instead of 5.7. Then, 5.0 will be stored in sum, because the variablesum is of type float.

    Note: Type casting is allowed in expressions only.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 44

    /***************************************************************** Filename : Bits.c *

    * Author : B V Rajesh *

    * Date : 30/11/10 ** Description: a demonstration of C bitwise operators ** *

    ****************************************************************/

    #include

    void main()

    {

    /* Variable Declaration & Initialization */char c='z';

    int a=100, b=45;double x=100.0, y=45.0;

    double z;

    /* Display given values */printf("\n c=%c",c);

    printf("\n a=%d b=%d", a, b);printf("\n x=%g y=%g", x, y);

    /* illustrating implicit type conversion */printf("\n\n %d", c*a);

    printf("\n %lf", a*x);

    /* illustrates explicit type conversion */

    z=(double)(a/b);

    printf("\n\n (double)(a/b)=%f", z);

    z=(double)a/b;

    printf("\n (double)(a/b)=%f", z);

    c=(char)(x/y);

    printf("\n (char)(x/y)=%d", c);

    /* keep console screen until a key stroke */getch();

    }

    OUTPUT

  • 8/2/2019 CP_UNIT_ 2_2011

    45/68

    2.13 STATEMENTS

    A statement causes an action to be performed by the program. It translates

    directly into one or more executable computer instructions. You may havenoticed that we have used a semicolon at the end of the statements in ourprograms. Most statements need a semicolon at the end; some do not. Differenttypes of statements in C are shown in Figure 2.16.

    An expression terminated by a semicolon (;) is termed to be a simple statement(or expression statement).

    Compound statements are used to group the statements into a single executableunit. It consists of one or more individual statements enclosed within the braces{ }.

    Return statement returns 0 to operating system on successful execution of theprogram.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 45

  • 8/2/2019 CP_UNIT_ 2_2011

    46/68

    Figure 2.16 Types of Statements in C

    2.14 CONTROL STRUCTURES IN C

    Control Structures control the flow of execution in a program or function. Thebasic programming control structures are sequence, selection, and iteration(looping).

    In a sequence structure, the instructions are executed in the same order in whichthey appear in the program. A program, which consists of declaration statements,input-output statements, and one or more simple expression statements, is

    executed in a sequential manner.

    In a selection structure, the control flow can be altered by evaluating conditions.

    In an iterative structure, a group of instructions is executed repeatedly, until somecondition is satisfied.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 46

  • 8/2/2019 CP_UNIT_ 2_2011

    47/68

    Selection Statements

    Selection (or Decision making) statements are used to alter the normalsequential flow of control. It provides the ability to decide the order of execution.The following are the selection statements available in C:

    1. if statement2. Conditional / Ternary operator statement (? :)3. switch statement

    2.15 IF STATEMENT

    The if statement, allows us to establish decision-making in the programs.Programs may require certain logical tests condition) to be carried out at someparticular points. Depending on the result of the expression the statements areexecuted.

    Condition

    Condition is an expression that is either false (represented by 0) or true(represented by 1). Conditions may contain relational or equality operators, andhave the following forms.

    Variable relational-operator variable (or constant)Variable equality-operator variable (or constant)

    The if statement has four basic forms:

    Simple if statement

    if.else statement

    Nested if else statement

    else if ladder

    2.15.1 SIMPLE IF STATEMENT

    The general form of a simple if statement is

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 47

    if (condition)

    {statement-block;

    }

  • 8/2/2019 CP_UNIT_ 2_2011

    48/68

    Figure 2.17 Flowchart of simple if statement

    Following are the properties of an if statement:

    1. If the condition is true then the statement block will be executed.

    2. If the condition is false it does not do anything.

    3. The condition is given in parentheses and must be evaluated as true

    (nonzero value) or false (zero value).

    4. If a compound statement is provided, it must be enclosed in opening

    and closing braces.

    Consider the following segment of a program that is written for swapping thecontents of two numbers.

    int num1=20,temp;int num2=40;

    if(num1>num2){

    temp=num1;num1=num2;

    num2=temp;

    } printf(\n Hello );

    The program test the condition num1>num2. If num1 greater than num2 theswapping occurs. For otherwise, proceed next statement printing hello onmonitor.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 48

  • 8/2/2019 CP_UNIT_ 2_2011

    49/68

    2.15.2 THE IF ELSE STATEMENT

    An else clause can be added to an if statement to make an if-else statement. Thegeneral form is

    Figure 2.18 Flowchart of ifelse statement

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 49

    /

    *************************************************************

    **** Name: Div.c ** Author: B V Rajesh *

    * Date: 22/11/10 ** Description: a program demonstrating simple if statement *

    ***********************************************************/#includevoid main()

    {/* Variable declaration */

    float a, b, c;

    /* Read the values of a and b */printf("\n Enter the value of a and b: ");

    scanf("%f%f", &a, &b);

    if(b!=0)

    {c=a/b;

    printf(\n c=%f, c);}

    printf("\n hi ");/* keep console screen until a key stroke */

    getch();

    OUTPUT1

    OUTPUT2

    if(condition){

    statements1;

    }

    else{

    statements2;}

  • 8/2/2019 CP_UNIT_ 2_2011

    50/68

    Following are the properties of an ifelse statement:

    1. If the condition is true then the true statement block will be executed.

    2. If the condition is false then false statement block got executed.

    3. The condition is given in parentheses and must be evaluated as true

    (nonzero value) or false (zero value).

    4. If a compound statement is provided, it must be enclosed in opening

    and closing braces.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 50

    /

    *****************************************************************

    Name: Even.c * *Author: B V Rajesh * *

    Date: 22/11/10 * *Description: a program demonstrating simple if else statement *

    ****************************************************************/#include

    void main(){

    /* Variable declaration */

    int num;

    /* Read number */printf("\n Enter a number : ");scanf("%d", &num);

    if(num%2==0){

    printf("\n The Given number %d is Even",num);}

    else

    {

    printf("\n The Given number %d is Odd",num);}

    /* keep console screen until a key stroke */

    getch();

    }

    OUTPUT1

    OUTPUT2

  • 8/2/2019 CP_UNIT_ 2_2011

    51/68

    2.15.3 NESTING OF IF ELSE STATEMENTS

    When a series of decisions are involved, we may have to use more than one ifelse statement in the nested form as follows:

    Figure 2.19 Flowchart on nested if else statements

    Nested if / else structures test for multiple cases by placing if / else structuresinside other if / else structures.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 51

    /

    ************************************************************Name: Even.c * *

    Author: B V Rajesh ** Date: 22/11/10 *

    * Description: a program demonstrating simple if else statement *

    ***********************************************************/#include

    void main()

    {

    /* Variable declaration */

    int i,j,k;

    /* Read values */

    printf("\n Enter the values of a,b and c : ");"

  • 8/2/2019 CP_UNIT_ 2_2011

    52/68

    2.15.4 THE ELSE IF LADDER

    There is another way of putting ifs together when multiple decisions are involved.A multipath decision is a chain of ifs in which the statement associated with eachelse is an if. It takes the following general form:

    The conditions are evaluated from the top (of the ladder), downwards. As soonas a true condition is found, the statement associated with it is executed and thecontrol is transferred to the statementx) skipping the rest of the ladder). When alln conditions become false, final else containing default_statement will beexecuted. Figure 2.20 shows the flowchart of else if ladder.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 52

    if(i > j)

    {if (i > k)

    printf(\nmax=%d, i);

    else

    printf(\nmax =%d, k);}

    else{

    if(j>k)printf(\nmax =%d,j);

    else

    printf(\nmax =%d,k);

    }

    /* keep console screen until a key stroke */getch();

    }

    OUTPUT

    Enter the values of a, b and c :

    20 49 10

    max=49

    if (condition1)statements1;

    else if (condition2)statements2;

    else if(conditionn)statementsn;

    elsedefault_statement;statement x;

  • 8/2/2019 CP_UNIT_ 2_2011

    53/68

    Figure 2.20 Flowchart of else if ladder

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 53

    /***********************************************************

    * Filename : Arithmetic.c *

    * Author : B V Rajesh ** Date : 20/11/10 ** Description : a program demonstrates working of else if ladder *

    * ** **********************************************************/#includevoid main(){

    /* variable declaration */int a, b, c;int D;

    /* read values */printf("\n Enter the values of a,b and c: ");

    scanf("%d%d%d",&a,&b,&c);/* find descriminiten */D=b*b-4*a*c;

    printf("\n The Nature of roots of a quadratic equation");

  • 8/2/2019 CP_UNIT_ 2_2011

    54/68

    2.16 THE SWITCH STATEMENT

    This is a conditional control statement that allows some particular group ofstatements to be chosen from several available groups. It is a multi-wayconditional statement generalizing the if else statement. A switch statementallows a single variable to be compared with several possible case labels, whichare represented by constant values. If the variable matches with one of theconstants, then an execution jump is made to that point. A case label cannotappear more than once and there can only be one default expression.

    The switch statement takes this form:

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 54

    if(D==0){printf("\n\n\n roots are real and equal ");}

    else if(D>0)

    { printf("\n\n\n roots are real and not equal ");}else{printf("\n\n\n roots are imaginary ");}

    /* keep console screen until a key stroke */getch();

    }

    OUTPUT

  • 8/2/2019 CP_UNIT_ 2_2011

    55/68

    Note that this statement does not allow less than, greater than, etc. ONLY theequality operator (==) is used with a switch statement. The control variable mustbe integral (int or char) only.

    When the switch statement is encountered, the control variable is evaluated.

    Then, if that evaluated value is equal to any of the values specified in a caseclause, the statements immediately following the colon (:) begin to run. Defaultcase is optional and if specified, default statements will be executed, if there is nomatch for the case labels.

    Once the program flow enters a case label, the statements associated with onecase have been executed, the program flow continues with the statement for thenext case. In other words, once the program enters through a closed switch, itexecutes the code for all of the following cases until end.

    Lets consider a program segment

    It consists of the following outputs

    The results are possible, depending on the value of printFlag. If printFlag is 1,then all three printf statements are executed. If printFlag is 2, then the first print

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 55

  • 8/2/2019 CP_UNIT_ 2_2011

    56/68

    statement is skipped and the last two are executed. Finally, if printFlag is neither1 nor 2, then only the statement defined by the default is executed.

    But occasionally we need this flexibility; it is not always we want. If we wantexecute only one case-label, C provides break statement. It causes the program

    to jump out of the switch statement, that is go to the closing braces (}) andcontinues the remaining code of the program.

    If we add break to the last statement of the case, the general form of switch caseis as follows:

    After adding the break statement to each case label the switch case executesonly one printf . The results are shown below.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 56

  • 8/2/2019 CP_UNIT_ 2_2011

    57/68

    Difference between Switch and else if ladder

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 57

  • 8/2/2019 CP_UNIT_ 2_2011

    58/68

    The switch statement only works on integer. Whereas else if ladder works

    for any type of value.

    In switch case only equality operation is performed. In else if any operator

    can be used in the condition.

    If the number of test cases are more in terms of readability and

    understabality switch case is better than else if ladder.

    switch works faster than else if ladder.

    2.17 LOOPS IN C

    The real power of computers is in their ability to repeat an operation or a series ofoperations many times. This repetition, called looping or iteration. Each loop musthave an expression (condition) that determines if the loop is done. If it is notdone, the loop repeats one more time; if it is done, the loop terminates.

    We need to test for the end of a loop; we can have either a pre- or a post-testterminating condition.

    In a pretest loop, in each iteration, the control expression is tested first. If it istrue, the loop continues; otherwise, the loop is terminated.

    In a post-test loop, in each iteration (repetition), the loop action(s) are executed.Then the control expression is tested. If it is true, a new iteration is started;otherwise, the loop terminates.

    In a pre tested loop if the condition is false in the first test itself then no actionsare taken place. Where as in the case op post test at least once the body of theloop is going to execute.

    A looping process, in general, would include the following four steps,

    Before a loop start, the loop control variable must be initialized; this should

    be done before the first execution of loop body. Test for the specified condition for execution of the loop, known as loop

    control expression.

    Executing the body of the loop, known as actions.

    Updating the loop control variable for performing next condition checking.

    Table 2.19 shows the difference between a pre tested loop and post tested loopin terms of iterations test conditions etc..,

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 58

  • 8/2/2019 CP_UNIT_ 2_2011

    59/68

    Table 2.19 Pretest loop and post test loop

    Figure 2.21 Flow chart for pretest loop and post test loop

    C language provides three loop control structures for performing repetition. Theyare shown in Figure 2.22.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 59

  • 8/2/2019 CP_UNIT_ 2_2011

    60/68

    Figure 2.22 Different types of loops in C

    2.17.1 THE WHILE STATEMENT

    The "while" loop is a generalized looping structure that employs a variable or

    expression for testing the ending condition. Is a repetition statement that allowsan action to be repeated while some conditions remain true. Variables used inthe loop control testing must be initialized testing for the termination condition isdone at the top of the while () loop. The body of WHILE statement can be asingle statement or compound statements.

    Syntax:

    In the above syntax while is the reserve word, condition should be specifies inbetween braces, a valid c expression. The statement (or block) will executerepeatedly until condition becomes false.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 60

    Form 1: Simple Statement

    while (condition)

    statement;

    Form 2: Compound Statements

    while (condition)

    {s1; s2; s3; ..

    }

  • 8/2/2019 CP_UNIT_ 2_2011

    61/68

    Figure 2. 23 Flow chart for while loop

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 61

    /********************************************************** Name: Rev.c *

    * Author: B V Rajesh ** Date: 24/11/10 *

    * Description: a program to revese a positive number *

    *********************************************************/

    #include

    void main(){ /* Variable Declaration */

    /* Display Values */

    int n,rem,rev=0;

    printf("\n Enter a positive number: ");scanf("%d",&n);

    while(n!=0){

    rem=n%10;rev=rev*10+rem;n=n/10;

    }

    printf("The reverese of %d is %d",n,rev);

    /* keep console screen until a key stroke */

    getch();}

  • 8/2/2019 CP_UNIT_ 2_2011

    62/68

    2.17.2 DO WHILE STATEMENT

    Statements in the loop are executed first (at least once, and condition is testedlast. Loop is controlled by a condition. The general form is :

    do{

    statement;

    statement;

    } while (condition);

    statement;On reaching do statement, the program proceeds to evaluate the body of theloop first. At the end of the loop, condition statement is evaluated. If the conditionis true, it evaluates the body of the loop once again. This process continues up tothe condition becomes false.

    In menu-driven application do-while statement is used. In do while statement, the

    while statement must ebd with semi colon.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 62

    OUTPUT

    Enter a positive number: 1234

    The reverse of 1234 is 4321

    Example

    #include

    void main(){

    int i = 1, n=5;

    do{

    printf( %d * %d = %d , n, i, n*i);i = i + 1;

    } while ( i

  • 8/2/2019 CP_UNIT_ 2_2011

    63/68

    2.17.3 THE FOR LOOP

    When the number of passes through a loop is known in advance, a for statementis often used. The general form of the for loop is

    for( initialization; test-condition; increment)

    { Body of the loop}

    The execution of the for statement is as follows:

    Initialization of the control variables is done first, using assignmentstatements such as i=1 count=0. The variables I and count are known asloop-counter variables.

    The value of the control variable is tested using the test-condition. The

    test-condition is a relational expression, such as i

  • 8/2/2019 CP_UNIT_ 2_2011

    64/68

    This for loop executes 10 times and prints the digits 0 to 9 in one line. The threesections enclosed within parentheses must be separated by semi colon.

    We can write the for loop in the following ways

    Option 1

    for (k= 1; k< = 10 ;){

    printf(%d, K);K = k + 1;

    }

    Here the increment is done within the body of the for loop and not in the forstatement. Note that the semicolon after the condition is necessary.

    Option 2

    Int k = 1;for (; k< = 10; k++);{

    printf(, k);}

    Here the initialization is done in the declaration statement itself, but still thesemicolon before the condition is necessary.

    The infinite loop

    One of the most interesting uses of the for loop is the creation of the infinite loop.Since none of the three expressions that form the for loop are required, it ispossible to make an endless loop by leaving the conditional expression empty.

    For example:

    for (; ;)Printf(The loop will run forever\n);

    Actually the for (; ;) construct does not necessarily create an infinite loopbecause Cs break statement, when encountered anywhere inside the body of aloop, causes immediate termination of the loop. Program control then picks upthe code following the loop, as shown here:

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 64

  • 8/2/2019 CP_UNIT_ 2_2011

    65/68

    For (; ;)

    {

    Ch = getchar( ); /* get a character */

    If (ch = = A)Break ;

    }

    Printf (you typed an A);

    This loop will run until A is typed at the keyboard.

    For loop with no bodies

    A statement, as defined by the C syntax, may be empty. This means that thebody of the for may also be empty. This fact can be used to improve theefficiency of certain algorithms as well as to create time delay loops.

    The following statement shows how to create a time delay loop using a for loop:

    for (t = o; t < SOME _VALUE; T++);

    One final C operator is the comma ,, which most often finds use in the forstatement. A pair of expressions separated by a comma is evaluated left to right,and the type and value of the result are the type and value of the right operand.Thus, in a for statement, it is possible to place multiple expressions in the variousparts.

    break statement

    When a break statement is enclosed inside a block or loop, the loop isimmediately exited and program continues with the next statement immediatelyfollowing the loop.

    When loop are nested break only exit from the inner loop containing it.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 65

  • 8/2/2019 CP_UNIT_ 2_2011

    66/68

    Figure 2.24 working of break in different looping statements

    continue statement

    C supports a statement continue to skip a part of the loop. It causes the loop tobe continued with the next iteration after skipping any statements between. Thecontinue statement tells the compiler, skip the following statements and continuewith the next iteration. The format of the continue statement is:

    Figure 2.24 working of continue in different looping statements

    Nested Loops

    These loops are the loops which contain another looping statement in a singleloop. These types of loops are used to create matrix. Any loop can contain anumber of loop statements in itself. If we are using loop within loop that is callednested loop. ANSI C support nesting up to 15 levels.

    B.V.RAJESH, ASSISTANT PROFESSOR, DEPARTMENT OF IT, SNIST PNO: 66

  • 8/2/2019 CP_UNIT_ 2_2011

    67/68

    In this the outer loop is used for counting rows and the internal loop is used forcounting columns

    SYNTAX:-

    for (initializing ; test condition ; increment / decrement){statement;for (initializing ; test condition ; increment / decrement){

    body of inner loop;}statement;

    }

    Consider the following segment of program

    for (j=1; j

  • 8/2/2019 CP_UNIT_ 2_2011

    68/68

    (b) Write about space requirements for variables of different data types.

    3. (a) Define the following with examples:(i) C tokens (ii) Identifiers (iii) Keyword (iv) constant

    (b) Differentiate Constants and Variables.

    4. (a) What is the standard Input / Output header file in C? How it is used?(b) What are the commonly used Input / Output functions used in C? How

    they are accessed? Explain.

    5. (a) What is an operator? What are the different categories of operators?Explain with examples?(b) What is precedence and Associativity? Give the Precedence andAssociativity of different operators.

    6. (a) What is an Expression? What are the different categories of expression?

    Explain with examples.(b) Explain Switch statement. How does this statement differ from the otherconditional statements?

    7. (a) Explain about different forms of IF statement and draw the flowchart foreach one.

    (b) Describe in detail the execution of While statement with example.8. (a) What is the purpose of for statement? How does it differ from the while

    statement and the do-while statement?(b) How many times will a for loop be executed? What is the purpose of the

    index in a for statement.(c) Can any of the three initial expression in the for statement be omitted? If

    so, what are the consequences of each omission?

    9. (a) What is the purpose of break and continue statements? Write thedifference between them.(b) Suppose a break or continue statements are included within the

    innermost of several nested control statements. What happens when breakor continue statement is executed?(c) Summarize the syntactic rules associated with the do-while statement.

    Compare it with the while statement.