unit 1for civil

Upload: prasanna-don

Post on 07-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 UNIT 1for Civil

    1/56

    0 #55

    C FUNDAMENTALSPrepared by

    S.Gunasekaran B.E,7/1/2011

    This unit is explained about the fundamentals of C language such as C character set-Identifiers and

    keywords-Data types-Constants-Variables-Declaration-Expressions-Statements-Symbolic constants-

    Operators-Data input and output-control statements-Unconditional statements, nested loop.

  • 8/3/2019 UNIT 1for Civil

    2/56

    1 # 55

    HISTORY OF C LANGUAGE

    C is one of the most popular programming languages. It was developed by Dennis

    Ritchie at AT & Ts Bell Laboratories at USA in the early 1970s. It is an upgraded version of

    two earlier languages, called Basic Combined Programming Language (BCPL) and B, which

    were also developed at Bell laboratories. The following table illustrates the history of C

    language.

    Language Year Founder

    ALGOL 1960 International group

    BCPL 1967 Martin Richards

    B 1970 Ken Thompson

    C 1972 Dennis Ritche

    K&RC 1978 Kernighan and Ritche

    ANSI C 1989 ANSI Committee

    ANSI/ISO C 1990 ISO Committee

    C IS A MIDDLE LEVEL LANGUAGE

    a)

    Low level language: Low level language is in terms of 0s and 1s (bits). Clanguage has the certain features of Low-level Language, that allow the

    programmer to carry out operations on bits that are normally available in Assembly

    language or Machine language.

    b) High level language: High level language looks like normal English, whoseinstruction set is more compatible with human languages. These languages are easily

    understandable and designed to provide a better program efficiency. These are

    machine independent. Examples are FORTAN, PASCAL, COBOL, BASIC, C++

    etc.

    c) Middle level language: C lies in between these two categories it is neither a lowlevel language nor a high level language, it is a middle level language. i.e., performs

    the task of Low level language as well as high level language. We can write the code

    for Operating System, Application Programs, and Assembly language programs in

    C language. Unix Operating System is written in C language.

  • 8/3/2019 UNIT 1for Civil

    3/56

    2 # 55

    STRUCTURE OF A C PROGRAM

    There are some sections in C program given below:

    i) Documentation SectionIt consists of set of comment lines used to specify the name of program,

    author and other details etc.,

    Comments: It is helpful in identifying the program features and

    underlying logic of the program. The line begins with /* and ending with */.

    These are not executable, the compiler is ignored anything between /* and */.The

    new style is //

    ii) Preprocessor Section

    Definition sectionIt is used to link system library files, for defining the macros and

    for defining the conditional inclusion.

    Eg: #include, #define A 10, #if def, #endif etc.

    iii) Global Declaration SectionThe variables that are used in more than one function throughout the

    program are called global variables and declared outside of all the function i.e.,

    before main(). It has two parts:

    Declaration part to declare all the variables used in the program

    Execution part Contains at least one valid C statement. It begins with

    opening braces {and ends with closing braces }. The

    closing brace of main function is the logical end of theprogram.

    iv) Sub Program Section It contains the function definitions included.

    The following tables are explained the programming structure.

  • 8/3/2019 UNIT 1for Civil

    4/56

    3 # 55

    STRUCTURE SAMPLE

    documentation section

    preprocessor section

    definition section

    global declaration section

    main()

    {

    declaration part;

    execution part;

    }

    sub program section

    {

    Body of the subprogram;

    }

    /* finding area of circle */

    #include

    #define PI 3.14

    main()

    {

    int r=5;

    float area;

    area = PI * r * r;

    printf(Area of circle: %f, area);

    }

    OUTPUT:

    Area of circle: 78.5

    CHARACTER SET

    Character set is the fundamental raw material of any language and they are used to

    represent information. C language consists of two character set namely,

    a) Source character setb) Execution character set

    Source Character Set

    These are useful to construct the statements in the source program Alphabets Upper

    case AZ,Lower case az ,Digits 0,19 ,Special character , + - * / $ _ { [ ] < > \ |

    ~ @ # % ^ & : ; ?

    Execution Character Set

    These are employed at the time of execution. This set of characters are also called as non

    graphic characters because, these characters are invisible and cannot be printed or displayed

    directly. This will be effect when program is being executed. Execution characters set are always

    represented by a backslash (\) followed by a character. We simply call it as escape sequences.

  • 8/3/2019 UNIT 1for Civil

    5/56

    4 # 55

    CHARACTER ESCAPE SEQUENCE

    Bell (alert) \a

    Backspace \b

    Horizontal tab \t

    Vertical tab \v

    Newline (Line feed) \n

    Form feed \f

    Carriage return \r

    Quotation Mark \

    Apostrophe \

    Question Mark \?

    Back Slash \\

    Null \0 (indicate end of string)

    C TOKENS

    The individual units of C programming language are called C tokens. It is usually

    referred as individual text and punctuation in a passage of text and has the following types

    C Tokens

    Identifiers Keywords Constants Strings OperatorsSpecial

    Symbols

    Total,

    Age

    int,

    double,

    39,

    39.77

    Guna

    Vikram

    +, -, *, / #, $, %

  • 8/3/2019 UNIT 1for Civil

    6/56

    5 # 55

    IDENTIFIERS

    Identifiers are referring to the names of variable, functions and arrays.

    RULE FOR NAMING AN IDENTIFIERS

    First character must be an alphabet Must consist of only letters, digits or underscore Only first 31 characters are significant Must not contain white space

    The following are valid

    Salary, aug99_sales, I, index

    The following are not valid

    2001_sales, aug99+sales, my age, printf

    KEYWORDS

    There are certain reserved words called keywords that have standard and predefinedmeaning in C language, which cant be changed.

    All keywords are fixed meanings and these meanings are cant be changed Keywords serve as basic building blocks for program statementsExample:

    Auto, double, int, struct, break, else, case, char, float, for

    DATA TYPES

    Data type is the type of the data, which are going to access within the program. C

    supports different data types. Each data type may have predefined memory requirement and

    storage representations in program.

  • 8/3/2019 UNIT 1for Civil

    7/56

    6 # 55They are four data types:

    Primary C

    Data TypeUser defined Derived Empty

    Charint

    float

    double

    typedefenum

    arrayspointers

    structures

    union

    void

    Basic data types:

    Type Keyword

    Character char

    Integer int

    Floating point float

    Doublefloating point

    double

    Valueless void

    Several of the basic types can be modified using one or more of these type modifiers:

    signed

    unsigned

    short

    long

    The type modifiers precede the type name that they modify. The basic arithmetic types,

    including modifiers, allowed by C are shown in the following table along with their guaranteed

    minimum ranges. Most compilers will exceed the minimums for one or more types. Also, if your

    computer uses twos complement arithmetic (as most do), then the smallest negative value that

    can be stored by a signed integer will be one more than the minimums shown. For example, the

    range of an int for most computers is 32,768 to 32,767. Whether type char is signed or

    unsigned is implementation dependent.

  • 8/3/2019 UNIT 1for Civil

    8/56

    7 # 55

    Type Byte Minimum Range

    CHARACTER TYPE

    char 127 to 127 or 0 to 255

    unsigned char 1 bytes 0 to 255

    signed char 127 to 127

    INTEGER TYPE

    Int 2 bytes 32,767 to 32,767

    unsigned int 2 bytes 0 to 65,535

    signed int 2 bytes same as int

    short int 1 bytes same as int

    unsigned short

    int

    1 bytes 0 to 65,535

    signed short int 1 bytes same as short int

    long int 4 bytes 2,147,483,647 to 2,147,483,647

    signed long int 4 bytes same as long int

    unsigned longint

    4 bytes 0 to 4,294,967,295

    FLOAT TYPE

    float 4 bytes 3.4E-38 to 3.4E+38 (6 digits of precision)

    double 8 bytes 1.7E-308 to 1.7E+308 (10 digits ofprecision)

    long double 10 bytes 3.4E-4932 to 1.1E+4932 (10 digits of

    precision)

    EMPTY DATA TYPE

    void

    When a type modifier is used by itself, int is assumed. For example, you can specify an unsigned

    integer by simply using the keyword unsigned. Thus, these declarations are equivalent.

    unsigned int i; // here, int is specified

    unsigned i; // here, int is implied

    VARIABLES

    A variable is an identifier that is used to represent some type of information within a

    designated portion of the program.

    Example

    int a,b,c;

    Here a,b,c is a variable

  • 8/3/2019 UNIT 1for Civil

    9/56

    8 # 55

    RULES FOR NAMING THE VARIABLE:

    Variable name can be any combination of 1 to 18 alphabets, digits or underscore First character must be an alphabet Length of the variable cant exceed upto 8 characters long, and some C compilers

    can be recognizing upto 31 characters long.

    No commas or blank spaces are allowed within a variable name. No special symbol, an underscore can be used in a variable name.

    Syntax:

    datatype v1, v2, v3,., vn;

    Where

    datatype is the type of the datav1, v2, v3... vn are the list of variables

    Example:

    main()

    {

    int i,j; //These 3 lines declare 4 variable

    char c;

    float x;

    //rest of program follows

    }

    USER DEFINED VARIABLES:

    a) Type declaration: C Language provides a feature to declare a variable of the typeof user defined type declaration, which allows users to define an identifier that would

    represents an existing data type and this can be used to declare variables.

    Syntax:

    Where

    typedef user defined type declaration

    datatype existing data type

    typedef datatype identifier;

  • 8/3/2019 UNIT 1for Civil

    10/56

    9 # 55

    identifier refers to the new name given to the data

    type

    Eg: typedef int marks;

    marks m1, m2, m3;

    b) Enumerated data type: C language provides another user defined data type iscalled enumerated data type.

    Syntax:

    where

    enum

    user defined enumerated data type.identifier refers to the new name given to the datatype

    value1, value2, , value nenumeration constants

    Eg:

    enum day {mon, tue, wed,,sun};

    enum day w_st, w_end;

    w_st = mon;

    w_end=sun;

    CONSTANTS

    The items whose values cant be changed during the execution of program are called

    constants. C constants can be classified as follows:

    enum identifier {value 1, value2, ., value n};

  • 8/3/2019 UNIT 1for Civil

    11/56

    10 # 55

    INTEGER CONSTANTS

    An integer constant formed with the sequence of digits. There are three types of integer

    constants which are different number system.

    Decimal number 0 to 9

    Octal number 0 to 7

    Hexadecimal 0 to 9, A, B, C, D, E, F

    Eg:

    marks = 90;

    per = 75;

    discount = 15;

    These are basically three types of integer namely,

    Decimal Eg: 10, 153, -342, 089, etc.Octal Eg: 037, 0,0567, etc.Hexadecimal Eg: 0x4, 0x8F, 0xBCF etc.

    Constants

    Numeric

    Integer Real

    Character

    Character String

  • 8/3/2019 UNIT 1for Civil

    12/56

    11 # 55

    REAL CONSTANTS

    It is made up of a sequence of numeric digits with presence of decimal point.

    Eg:

    weight = 56.8;

    height = 5.6;speed = 3.11;

    CHARACTER CONSTANTS

    The character constant contains is a character with enclosed quotes

    Eg: p N 4 +

    STRING CONSTANTS

    A string constant is a sequence of characters enclosed in double quotes ( ), the

    characters may be letters, numbers, special characters and blank spaces etc. At the end of

    string \0 is automatically placed.

    Eg: String, HI39.56,

    22

    i) Declaring a variable as constant:When the value of some of the variables may remain constantly during the

    execution of the program, in such a situation, this can be done by using the

    keyword const.

    Syntax:

    Where

    const keyword to declare constant

    variable name of the variable

    datatype type of the data

    constant constant

    Eg:

    const int rate = 397;

    const datatype variable =

  • 8/3/2019 UNIT 1for Civil

    13/56

    12 # 55

    STRING:

    String is a collection of character

    Eg:India, Tamilnadu

    OPERATORS:

    An operator is a symbol that tells the computer to perform the certain mathematical or

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

    1. ARITHMETIC OPERATOR

    C provides the entire basic arithmetic operator+ Addition operator

    - Subtraction operator

    / Division operator

    % modulo division

    Modulo operator cant used to floating point data

    Operators

    Arithmetic operator

    Relational operator

    Logical operator

    Assignment operator

    Increment and decrement operator

    Conditional operator

    Bitwise operator

    Special operator

  • 8/3/2019 UNIT 1for Civil

    14/56

    13 # 55

    Example:

    a=10, b=5

    a+b=15

    a-b=5

    a/b=2

    a%b=2

    2. RELATIONAL OPERATOR

    Relational operator which is used to compare two quantities and depending on their

    relation take certain decisions

    Relational expressions are used in decision statements such as if and while

    They operator are

    < less than

    > greater than

    = greater than or equal to

    == is equal to

    != not equal to

    Example:

    a=10, b=5

    ab true

    a=b true

    a==b false

    a!=b true

    3. LOGICAL OPERATOR

    Logical operator which is used to test more than one condition and make decisions

  • 8/3/2019 UNIT 1for Civil

    15/56

    14 # 55They operator are

    && ->Logical AND

    ||->Logical OR

    !->Logical NOT

    Example:

    if((ad))

    {

    printf( This is true);

    }

    The variable a must be less than b and, at the same time, c must be greater than d .if both

    condition is true then if block statement execute, either one or false statement not execute

    If((ad))

    {

    printf( This is true);

    }

    The variable a must be less than b and, at the same time, c must be greater than d .if both

    condition either one or true or both true then if statement block execute

    If(!(aassignment operator

    Example:

    Variable operator = expression

    a=10, b=5

    a=a+b ->a=15 is equal to a+=b ->a=15

    5. INCREMENT AND DECREMENT OPERATOR

    The operator ++ add 1 to operand while subtract 1.

    Increment and decrement statements in for and while loops extensively

  • 8/3/2019 UNIT 1for Civil

    16/56

    15 # 55Two types

    Prefix:A prefix operator first adds 1 or subtract to the operand and then the result is assigned to

    the variable on left

    Example:

    Assume a=5;

    b=++a;

    a=6,b=6

    b=--a;

    a=5,b=5;

    Postfix: A postfix operator first operator first assigns the value to the variable on left and then

    increment or decrement the operand

    Example:

    Assume a=5;

    b=a++

    b=5,a=6

    b=a- -

    b=5,a=4

    6. CONDITIONAL OPERATOR

    Conditional operator also called as ternary operator. This conditional operator is used to

    replace ifelse logic in some situation

    The conditional operators are

    Conditional exp? expression1: expression 2;

    If the condition exp is true is expression 1 is execute .if the condition exp is false then

    expression 2 is execute

    a>b?(ans=10);(ans=25);

    is equal to

    if(a>b)

    {

    ans=10;

    }

    else

  • 8/3/2019 UNIT 1for Civil

    17/56

    16 # 55{

    ans=25;

    }

    7. BITWISE OPERATOR

    Bitwise operator for manipulation of data at bit level. These operator are used for testing

    the bits or shifting them right or left .bitwise operator not be applied to float or double

    The bitwise operators are

    & Bitwise AND

    | Bitwise OR

    ^ Bitwise Exclusive OR

    > Shift right

    Eg:

    24 >> 2 is 6

    24 0001 1000

    After shifting right by 2 position,

    0000 0110 6

    8. SPECIAL OPERATOR

    Comma operator:

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

    linked list of expressions are evaluated left to right and the value of right most expression is the

    value combined

    Example:

    Value=(x=10,y=5,x+y);

    Sizeof() operator:

    The sizeof is compile time operator and when used with an operand it returns the number

    of bytes the operand occupies. The operand may be variable, a constant or a data type qualifier

    a=sizeof(sum);

    b=sizeof(long int);

    c=sizeof(234);

  • 8/3/2019 UNIT 1for Civil

    18/56

    17 # 55

    SPECIAL SYMBOLS:

    These are the symbols, which has some syntactic meaning and has got significance.

    These will not specify any operation. In C language call it as Delimiters as given below:

    SYMBOLS NAME MEANING

    # Hash Pre-Processor directive

    , comma Variable delimiters to separatelist of variables

    : Colon Label Delimiters

    ; Semicolon Statement Delimiters

    () Paranthesis Used in expressions or infunctions

    { } Curly braces using for blocking Cstructure

    [] Square braces used along with arrays

    EXPRESSIONS

    An expression consists of a sequence of constants, identifiers, and operators that the

    program evaluates by performing the operations indicated. The expression's purpose in the

    program may be to obtain the resulting value, or to produce side effects of the evaluation, or

    both.

    Single constant, a string literal, or the identifier of an object or function is in itself an

    expression. Such a simple expression, or a more complex expression enclosed in parentheses, is

    called a primary expression.

    Every expression has a type. An expression's type is the type of the value that results

    when the expression is evaluated. If the expression yields no value, it has the type void. Some

    simple examples of expressions are listed below:

    Variable = Expression;

    Eg:

    y = (a/b) +c;

    k = ((2 * x * x)/b) c;

  • 8/3/2019 UNIT 1for Civil

    19/56

    18 # 55

    OPERATOR PRECEDENCE AND ASSOCIATIVITY

    An expression may contain several operators. In this case, the precedence of the

    operators determines which part of the expression is treated as the operand of each operator. For

    example, in keeping with the customary rules of arithmetic, the operators *, /, and % have higher

    precedence in an expression than the operators + and -. For example, the following expression:

    a - b * c

    is equivalent to a - (b * c). If you intend the operands to be grouped differently, you must use

    parentheses, thus:

    (a - b) * c

    If two operators in an expression have the same precedence, then their associativity

    determines whether they are grouped with operands in order from left to right, or from right to

    left. For example, arithmetic operators are associated with operands from left to right, and

    assignment operators from right to left, as shown below lists the precedence and associativity of

    all the C operators.

    OPERATOR GROUPING

    EXPRESSION ASSOCIATIVITY EFFECTIVE GROUPING

    a / b % c Left to right (a / b) % c

    a = b = c Right to left a = (b = c)

    OPERATOR PRECEDENCE AND ASSOCIATIVITY

    PRECEDENCE OPERATORS ASSOCIATIVITY

    1. Postfix operators :

    [ ] ( ) . -> ++ --

    (type name){list}

    Left to right

    2. Unary operators:

    ++ --

    ! ~ + - * & sizeof

    Right to left

    3. The cast operator: (type name) Right to left

    4. Multiplicative operators: * / % Left to right

    5. Additive operators: + - Left to right

    6. Shift operators: > Left to right

  • 8/3/2019 UNIT 1for Civil

    20/56

    19 # 55

    OPERATOR PRECEDENCE AND ASSOCIATIVITY

    PRECEDENCE OPERATORS ASSOCIATIVITY

    7. Relational operators: < >= Left to right

    8. Equality operators: == != Left to right

    9. Bitwise AND: & Left to right

    10. Bitwise exclusive OR: ^ Left to right

    11. Bitwise OR: | Left to right

    12. Logical AND: && Left to right

    13. Logical OR: || Left to right

    14. The conditional operator: ? : Right to left

    15. Assignment operators:

    = += -= *= /= %= &= ^= |= =

    Right to left

    16. The comma operator: , Left to right

    DATA INPUT AND OUTPUT

    Standard devices

    C always assumes that input comes from stdin or the standard input device .this is

    usually the keyboard. C assumes that all output goes to stdout or the standard output device

    Standard I/O devise in C

    I/O DEVICE C NAME

    Screen Stdout

    Keyboard Stdin

    Printer Stdprn

    Serial port Stdaux

    Error messages Stderr

    Disk files None

  • 8/3/2019 UNIT 1for Civil

    21/56

    20 # 55

    SIMPLE INPUT AND OUTPUT STATEMENT

    scanf

    The scanf () functions is used to read the formatted data items from the keyboard the

    format is user defined data items .it can be read or written as defined by a programmer

    The general format

    scanf(control string ,argument list);

    The control string is a specified format code to read from the keyboard and the

    argument list is a user defined variable list .usually, the argument list of the user defined

    variables must include the address operator(&) as a prefix to the variable

    For example

    int x,y;

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

    char c,i;

    scanf(%f%f,&c,&i);

    The complete format code used in the scanf() function for the various data variables shown

    below

    Code Meaning

    %c Read a single character

    %d Read a decimal integer

    %i Read a decimal integer

    %e Read a floating point number

    %f Read a floating point number

    %h Read a short integer

    %o Read a octal number

    %s Read a string

    %x Read a hexadecimal number

    All the variables used to receive values through scanf() must be passed by their addresses .this

    means that all arguments must be pointed to the variables used as arguments

  • 8/3/2019 UNIT 1for Civil

    22/56

    21 # 55printf()

    The printf() function is one of the most important and useful function to display the

    formatted output data items on the standard output device normally the video screen

    The general form ofprintf() function is as

    printf(control strings,argument list);

    Where the control strings are user defined format code and the argument list is a set of data itemsto be displayed in a proper format as defined by the control stings

    The complete format code used in the printf() function for the various data variables shown

    below

    Code Meaning

    %c Read a single character

    %d Read a decimal integer

    %i Read a decimal integer

    %e Read a floating point number

    %f Read a floating point number

    %h Read a short integer

    %o Read a octal number

    %s Read a string

    %x Read a hexadecimal number

    %% Print a percent sign

    THE get() AND putc() FUNCTIONS

    The most fundamental character I/O functions are getc() and putc().

    getc()

    The getc() function inputs a single character form the standard input device which is

    keyboard ,unless you redirect it

    The format for getc( ) follows

    intvar=getc(device);

  • 8/3/2019 UNIT 1for Civil

    23/56

    22 # 55Dont let the integer intvar confuse you. Even though getc() is a character function, you use a

    integer variable to store the getc() input value. getc() returns a 1 when an end-of-file condition

    occurs. If you are using getc() to read information from a disk file, the 1 is read when the end of

    the file is reached

    The getc() device can be any c standard input device .if you are getting character input from the

    keyboard ,use stdin as the device

    putc()

    The putc() functions writes a single character to the standard output device ,which is the

    screen, unless you redirect it from your operating system.

    The format ofputc() follows:

    putc(intval,device);

    The intval can be integer variable, expression, or constant. You output character data with

    putc().the device can be any standard output c device.to write a character to your printer, use

    stdprn for the device.

    Example program

    /*Introduces getc() and putc()*/

    #include

    #include

    void main()

    {

    int inchar; //Holds incomming initial

    char first,last; //Holds converted first and last intial

    clrscr();

    printf("what is your first name initial?");

    inchar=getc(stdin); //Wait for first initial

    first=inchar;

    inchar=getc(stdin); // ignore newline

    printf("what is your last name initial?");

    inchar=getc(stdin); //Wait for last initial

    last=inchar;

    inchar=getc(stdin); // ignore newline

  • 8/3/2019 UNIT 1for Civil

    24/56

    23 # 55printf("\nHere they are!!!\n");

    putc(first,stdout);

    putc('\n',stdout); // A newline is output

    putc(last,stdout);

    getch();

    }

    OUTPUT

    The getchar() and putchar() functions

    When you perform character I/O ,the getchar() functions are easier to use than getc() and

    putc(). The getchar() and putchar() functions are identical to getc() and putc(),except you do

    not specify a because they assume that the standard input and output devices are stdin andstdout (typically ,the screen and the keybord).in the following

    inchar=getc(stdin);

    Is identical to

    inchar=getchar();

    And

  • 8/3/2019 UNIT 1for Civil

    25/56

    24 # 55putc(var.stdout);

    is identical to

    putchar(var);

    The getchar() and the getc() functions are both buffered input functions. That is as you

    type characters, the data goes to a buffer rather than immediately to your program. The buffer is

    a section of memory managed by C

    When your program gets to a getc() or a getchar(),the program temporarily waits as you type the

    input. The program does not seethe characters because they are going to the buffer in memory

    there is no limit to the size of the buffer; it keeps filling up with you press enter. Pressing the

    enter key signals the computer to release the buffer to your program

    /*Illustrates simple getchar() and putchar()*/

    #include

    #include

    void main()

    {

    int mychar; // Must be integer

    clrscr();

    mychar=getchar(); // Get the character

    printf("You Typed This!!!\n");

    putchar(mychar);

    getch();

    }

  • 8/3/2019 UNIT 1for Civil

    26/56

    25 # 55

    OUTPUT

    getch() and putch() funtoins

    The getch() and putch() functions are slightly different than the previous character I/O

    functions. Their formats are similar to getchar() and putchar() ; they both assume that stdin and

    stdout are the standard input and output devices, and you cant specify other devices(unless you

    redirect them with your operating system)

    The format ofgetch()

    intvar=getch();

    The format ofputch()

    putch(intvar);

    The getch() and putch() functions are not ANSI C standard functions, but they are

    available on a large number of compilers and well worth mentioning, getch() and putch() are

    non-buffered functions

    Both getch() and putch() assume that stdin and stdout are the standard input and output devices.When you want your program to respond immediately to keyboard input use getch().some

    programmers want to make users press enter after answering a prompt or selecting from a menu.

    They feel that buffered input gives users more time to decide if they really want to give that

    answer: users can press Backspace and correct the input before pressing Enter

    Example program

    /*uses getch() and putch() input and output */

    #include

    #include

  • 8/3/2019 UNIT 1for Civil

    27/56

    26 # 55void main()

    {

    int ctr; // The for loop counter

    char letters[5]; // Holds five input characters

    clrscr();

    printf("Please Type Five Letters....\n");

    for(ctr=0;ctr

  • 8/3/2019 UNIT 1for Civil

    28/56

    27 # 55

    OUTPUT

    STRING I/O FUNCTIONS

    The input and output functions are listed fellow

    gets(s):stores input from stdin(usually directed to the keyboard)into the string named s

    puts(s):output the s string to stdout(usually directed to the screen by the operating system)

    Therefore when you enter stings with gets(), C places a string-terminating character in

    the string at the point where you press Enter. This creates the input sting. (Without the null zero,

    the input would not be a string).when you output a string, the null zero at the end of the sting

    becomes a newline character. This is good because you typically prefer a newline at the end of a

    line of output (to put the cursor on the next line)

    Example Program

    /*using gets() and puts()*/

    #include

    #include

    void main()

    {

    char book[30]; // Holds the string

    clrscr();

    printf("What is the Book Tittle?\n");

  • 8/3/2019 UNIT 1for Civil

    29/56

    28 # 55gets(book); // Get an input String

    printf("You Typed the Book Tittles are!\n");

    puts(book); // Display the String

    printf("Thanks for the Book!!!\n");

    getch();

    }

    OUTPUT

  • 8/3/2019 UNIT 1for Civil

    30/56

    29 # 55

    DECISION MAKING AND BRANCH STATEMENTS

    Simple if statements:

    Syntax:

    if(test expression)

    {

    Statementblock one or more;

    }

    Statement x;

    If the test expression is true then the statement is executes otherwise it goes to out of branch

    Decision Makingand Branching

    Statements

    Simple ifstatements

    The if elsestatements

    Nesting of if elsestatements

    The else if Ladder

    Condition

    True Statements

    False

    True

  • 8/3/2019 UNIT 1for Civil

    31/56

    30 # 55Example:

    //simple if program

    #include

    #include

    void main()

    {

    int age=21; //declare and assign age as 21

    clrscr();

    printf(\n What is student age? );

    scanf(%d,&age);

    if(age

  • 8/3/2019 UNIT 1for Civil

    32/56

    31 # 55Simple if else statements:

    Syntax:

    if(condition)

    {

    Block of one or more statements

    }

    else

    {

    Block of one or more statements

    }

    The if condition is true then execute entire if block statement other wise else statement is execute

    Condition

    True Statements False Statements

    FalseTrue

  • 8/3/2019 UNIT 1for Civil

    33/56

    32 # 55Example:

    //simple if else program

    #include

    #include

    void main()

    {

    int num;

    clrscr();

    printf("What is your number?");

    scanf("%d",&num);

    if(num>=10)

    {

    printf("More than 10\n");

    }

    else

    {

    printf("Less or equal to 10\n");

    }

    getch();

    }

  • 8/3/2019 UNIT 1for Civil

    34/56

    33 # 55

    OUTPUT

    Nested if else statements:

    When a series of decisions are involved. We may have to use more than one if.else

    statements

    Syntax:

    if(test condition-1)

    {

    if(test condition-2)

    {

    Statements -1;

    }

    else

    {

    statements -2;

    }

    }

    else

  • 8/3/2019 UNIT 1for Civil

    35/56

    34 # 55{

    Statements-3;

    }

    Statementsx;

    If the condition-1 is false, the statement-3 will be executed, otherwise to perform the

    second test. if the condition -2 is true, the statement-1 will be evaluated, otherwise the statement-

    2 will be evaluated and then the control is transferred to the statement-x

  • 8/3/2019 UNIT 1for Civil

    36/56

    35 # 55

    Example:

    //nested if else program

    #include

    #include

    void main()

    {

    int a,b,c;

    clrscr();

    printf("\nEnter the three valus:");

    scanf("%d%d%d",&a,&b,&c);

    prtinf(\n***OUTPUT***\n);

    printf("The Largest values are:");

    if(a>b)

    {

    if(a>c)

    {

    printf("%d",a);

    }

    else

    {

    printf("%d",c);

    }

    }

    else

    {

    if(c>b)

    {

    printf("%d",c);

    }

    else

    {

  • 8/3/2019 UNIT 1for Civil

    37/56

    36 # 55printf("%d",b);

    }

    }

    getch();

    }

    OUTPUT

    The else if ladder statements:

    A multiple decision is a chain of if is which statement associated with each else is an if

    Syntax:

    If(condition)

    Statement -1;

    else if (condition 2)

    statement-2;

    else if(condition-3)

    statement-3;

    else if(conditionn)

    statementn;

    else

    default statements;

  • 8/3/2019 UNIT 1for Civil

    38/56

    37 # 55statementx;

    The conditions are evaluated from the top to downwards. As soon as a true condition is

    found, the statement associated with it is executed and the control is transferred to the statement-

    x. When all the condition is false then the final else containing the default statement will be

    executed

    Example:

    //else if ladder

    #include

    #include

    void main()

    {

    int num;

    clrscr();

    printf("Enter the Number(1-5)");

    scanf("%d",&num);

    printf(\n***OUTPUT***\n);

    if(num==1)

    printf("color=RED");

    else if(num==2)

    printf("color=GREEN");

    else if(num==3)

    printf("color=WHITE");

    else if(num==4)

    printf("color=YELLOW");

    else if(num==5)

    printf("color=BLUE");

    else

    printf("color=BLOCK");

    getch();

    }

  • 8/3/2019 UNIT 1for Civil

    39/56

    38 # 55

    OUTPUT

    switch case statement:

    The switch statement is sometimes called the multiple choice statement

    Syntax:

    switch (expression)

    {

    case value1:

    block-1;

    break;

    case value2:

    block-2;

    break;

    .

    .

    .

    default:

    default-block;

    break;

    case 2

    Statements

    case 1

    Statements

    default

    Statements

    switch

  • 8/3/2019 UNIT 1for Civil

    40/56

    39 # 55

    The expression can be an integer expression, a character, a constant or a variable. The sub

    expression (value1, value 2 and so on)

    If the expression matches value1 the statement execute and so on. None of the value is

    not match then default statement is executes

    Example:

    //simple switch program

    #include

    #include

    void main()

    {

    int num;

    clrscr();

    printf("Enter the number(1-7)");

    scanf("%d",&num);

    switch(num)

    {

    case 1:

    {

    printf("This is Sunday");

    break;

    }

    case 2:

    {

    printf("This is Monday");

    break;

    }

    case 3:

    {

    printf("This is Tuesday");

    break;

    }

  • 8/3/2019 UNIT 1for Civil

    41/56

    40 # 55case 4:

    {

    printf("This is Wendsday");

    break;

    }

    case 5:

    {

    printf("This is Thursday");

    break;

    }

    case 6:

    {

    printf("This is Friday");

    break;

    }

    case 7:

    {

    printf("This is Saturday");

    break;

    }

    default:

    printf("You Enter the Wrong Number try again");

    }

    getch();

    }

  • 8/3/2019 UNIT 1for Civil

    42/56

    41 # 55

    OUTPUT

    UNCONDITIONAL STATEMENTS

    break

    The for loop was designed to execute for a specified number of times, sometimes, though

    rarely the for loop should quit before the counting variable has reached its final value, as withwhile loops, you use the break statements to quite a for loop early.

    The break statement goes in the body of the for loop. Programmers rarely put break on a line byitself, and it almost comes after an if test.if the break were on a line by itself the loop would

    always quit early defeating the purpose of the for loop

    The format of break is

    break;

    Example

    for(ctr=0;ctr

  • 8/3/2019 UNIT 1for Civil

    43/56

    42 # 55Example

    /*a for loop running at the user's request*/

    #include

    #include

    void main()

    {

    int num,ans; // loop counter variable

    clrscr();

    printf(" Here are the numbers from 1 to 20\n");

    for(num=1;num

  • 8/3/2019 UNIT 1for Civil

    44/56

  • 8/3/2019 UNIT 1for Civil

    45/56

    44 # 55continue; // Causes body to end early

    printf("C Programming\n");

    }

    getch();

    }

    OUTPUT

    GOTO STATEMENT:

    C supports the goto statement to branch unconditionally from one point to another in the

    program. The goto requires a label to identify the place where the branch is to be made. A label

    is any valid variable name, must be followed by a colon. The label is placed immediately before

    the statement where the control is to be transferred.

    General forms:

    Forward jump Backward jump

    Syntax:

    goto begin;

    goto label;

    ..

    ..

    label:

    statement;

    label:

    statement;

    ..

    ..

    goto label;

  • 8/3/2019 UNIT 1for Civil

    46/56

    45 # 55goto breaks the normal sequential execution of the program. If the label: is before the

    statement goto label; a loop will be formed and some statements will be executed repeatedly.

    such a jump is called backward jump. If the label: is placed after the goto label; some statements

    will be skipped and the jump is known as forward jump. A goto is used at the end of a program

    to direct the control to go to the input statement, to read further data.

    Example

    /* This is Program demonstrates the overuse of goto */

    #include

    #include

    void main()

    {

    clrscr();

    goto Here;

    First:printf("A\n");

    goto Final;

    There:

    printf("B\n");

    goto First;

    Here:

    printf("C\n");

    goto There;

    Final:

    getch();

    }

  • 8/3/2019 UNIT 1for Civil

    47/56

    46 # 55OUTPUT

    DECISION MAKING AND LOOP STATEMENTS

    while

    The while statement is one of several C construct statement. Looping statements cause

    parts of a program to execute repeatedly as long as a certain condition is being met. While is an

    entry-controlled loop statement.

    Syntax:

    while(test-condition)

    {

    Body of the loop

    }

    The test condition is evaluated and if the condition is true(non zero),the block of one or

    more C statements execute repeatedly until the test condition becomes false(evaluates to zero)

    DECISIONMAKING AND

    LOOPSTATEMENTS

    while do-while for

  • 8/3/2019 UNIT 1for Civil

    48/56

    47 # 55

    Example:

    //simple while program

    #include

    #include

    void main()

    {

    char name[15];

    int count=0;

    clrscr();

    printf("What is Your First Name?");

    scanf("%s",name);

    while(name[count])

    {

    count++;

    }

    printf(\n***OUTPUT***\n);

    printf("Your Name has %d Characters",count);

    getch();

    }

    Condition

    Body of the loop

    False

    True

  • 8/3/2019 UNIT 1for Civil

    49/56

  • 8/3/2019 UNIT 1for Civil

    50/56

  • 8/3/2019 UNIT 1for Civil

    51/56

    50 # 55

    Example:

    //simple for program

    #include

    #include

    void main()

    {

    int total,ctr;

    total=0;

    clrscr();

    for(ctr=100;ctr

  • 8/3/2019 UNIT 1for Civil

    52/56

    51 # 55

    OUTPUT

    NESTED LOOPS:

    One for loop statement within another for loop statement called nested for loop.

    Syntax:

    for ()

    {

    .

    for (..)

    {

    .

    }

    }

    Example:

    #include

    #include

    void main()

    {

    int i,j;

    clrscr();for(i=1;i

  • 8/3/2019 UNIT 1for Civil

    53/56

    52 # 55{

    for(j=1;j

  • 8/3/2019 UNIT 1for Civil

    54/56

    53 # 55

    Example:

    a) while () b) do{ {

    if (condition) .

    break; .

    Exit if (condition

    From Exit break;

    loop } from }while (.);

    loop

    c) for () d) for ()

    { {

    . .

    . for (..)

    if (error) {

    break; ..

    Exit .. if (condition)

    from .. break;

    loop Exit from .

    } Inner loop }

    .............. .

    }

    Skipping a part of loop:During the loop operations, to skip a body of loop under some conditions we may

    use continue statement. It tells the compile to skip the following statement and then continues

    with the next iteration.

  • 8/3/2019 UNIT 1for Civil

    55/56

    54 # 55Example:

    a) while (test-condition) b) do{ {

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

    if (-----------) if (-----------)

    continue; continue;

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

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

    } }while(test-condition);

    c) for (initialization; test condition; increment/decrement operator)

    {

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

    if -----------)

    continue;

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

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

    }

    THE STANDARD HEADERS

    Each standard library function is declared in one or more of the standard headers. These

    headers also contain all the macro and type definitions that the C standard provides. This chapter

    describes the contents and use of the standard headers.

    Each of the standard headers contains a set of related function declarations, macros, and type

    definitions. The standard headers are also called header files, as the contents of each header are

    Usually stored in a file. Strictly speaking, however, the standard does not require the headers to

    be organized in files.

  • 8/3/2019 UNIT 1for Civil

    56/56