fundamentals of programmingc class1

Upload: umal8282

Post on 07-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    1/114

    C Programming

    Class I

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    2/114

    Introduction to C

    Generation of C Language1. In 1967, Martin Richards developed a language called BCPL

    (Basic Combined Programming Language)

    2. In 1970, Ken Thompson created a language using manyfeatures of BCPL and called it simply B.

    3. In 1972, C is Introduced by Dennis Ritchie at Belllaboratories and in the UNIX operating system.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    3/114

    TYPES OF C COMPILER

    1. Borland C Compiler

    2. Turbo C Compiler

    3. Microsoft C Compiler

    4. ANSI C Compiler

    Why are using C It is a Structured Programming Language

    High Level Language

    Machine Independent Language It allows software developers to develop programs

    without worrying about the hardware platforms wherethey will be implemented

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    4/114

    Steps in Learning C

    Character set

    Constants, variableAnd Data types

    Control statements

    Functions

    Files

    Structures andUnions

    Pointers

    Arrays

    Data Structures

    Algorithms

    Programs

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    5/114

    CS Program StructureDocumentation section

    Preprocessor section

    Definition section

    Global declaration section

    main(){Declaration part;Executable part;

    }

    Sub program section{

    Body of the subprogram}

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    6/114

    Cs Character set

    C Character set

    Source Characterset

    ExecutionCharacter set

    AlphabetsA to Z & a to z

    Escape Sequences\a,\b,\t,\n

    Digits0 to 9

    Special Characters

    +,-,,@,&,$,#,!

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    7/114

    C TOKENS

    C TOKENS

    Keywords

    Identifiers

    Strings

    Special Symbols

    Constants

    Operators

    -15.5

    100

    Grant_total

    Amount

    a1

    float

    while

    ABC

    YEAR

    + - * /

    [ ]

    { }

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    8/114

    Cs keyword Basic Building Block of the Program

    This are the Reserved words

    This words cant be changed

    C keywords

    autobreakcase

    charconstcontinuedefaultdo

    doubleelseenum

    externfloatforgotoif

    intlongregister

    returnshortsignedsizeofstatic

    structswitchtypedef

    unionunsignedvoidvolatilewhile

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    9/114

    Cs Variables

    A variable is a data name as well as identifier that may beused to store a data value.

    Rules for Naming the Variablesa) A variable can be of any combination of alphabets, digits and

    underscore.

    b) The first character of the variable cant be digits.

    c) The length of the variable cant be exceeded by 8.(ANSI C 32Character)

    d) No commas, blanks or special symbol are allowed within a

    variable name.e) Uppercase and lowercase are significant. That is, the variable

    Total is not the same as total or TOTAL.

    f) It should not be a keyword.

    g) White space is not allowed.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    10/114

    Cs Variables cont.

    Variable Declaration

    It tells the computer what the variable name and type of the data

    Syntax data_type a1,a2,a3..an;

    Description data_type is the type of the data.a1,a2,a3an are the list of variables

    Example int number;char alpha;

    float price;

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    11/114

    Cs Variables cont.Initializing Variables

    Initialization of variables can be done using assignment operator(=)

    Syntax

    a1 = c1 ;(or)

    data_type a1 = c1;

    Description a1 is the variablec1 is the constant

    data_type is the type of the data

    Example int a1 = 29;float f1 = 34.45;

    char c1 = d

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    12/114

    Cs constant

    C constant

    Numeric constant

    Character constant

    Integer constanteg: roll_number = 12345;

    Real constanteg: pi = 3.14;

    Single Character constant

    eg: ch = c; ch = 3;

    String constant

    eg: name = palani

    The item whose values cant be changed during execution of program are called consta

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    13/114

    Cs constant Conti

    Integer constanteg: roll_number = 12345;

    Hexadecimal constantEg. 0x23

    Octal constantEg. 043

    Decimal ConstantEg. 35

    Real Constanteg: pi = 3.14;

    Double Precision ConstantSingle Precision Constant

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    14/114

    Data Types This are the type of the data that are going to access

    within the program.

    Cs Data Type

    Primary User defined Derived Empty

    Char

    Int

    Float

    Double

    typedef

    Arrays

    Pointers

    Structures

    Union

    Void

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    15/114

    Cs Data types cont.

    Integer

    Signed

    Unsigned

    Int (%d)2 bytes,-32768 to 32767

    Short int (%d)1 bytes, -128 to 127

    Long int (%ld)4 bytes,

    -2,147,483,648 to 2,147,483,647

    Unsigned Int (%d)2 bytes, 0 TO 65, 535

    Unsigned short int (%d)1 bytes, 0 TO 255

    Unsigned Long int (%ld)4 bytes,

    The primary data types are further classified as below.

    Integers are the whole numbers, both positive and negative.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    16/114

    Cs Data types cont.

    Float Type

    Float (%f )4 bytes, 3.4E -38 to 3.4E +38

    Double (%lf)8 bytes, 1.7E -308 to 1.7E +308

    Long Double (%lf)10 bytes, 3.4E -4932 to 1.1E+4932

    Float are the numbers which contain fractional parts, bothPositive and Negative.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    17/114

    Cs Data types cont.

    Character Type

    Char (%c)1 byte, -128 to 127

    Signed Char (%c)

    1 byte, -128 to 127

    Unsigned Char (%c)1 byte, 0 to 255

    Charare the characters which contain alpha-numeric character.Characters are usually stored in 8 bits (one byte) of internal storage

    The void is the Null Data type.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    18/114

    C Delimiters

    Symbol Name Meaning

    # Hash Pre-processor directive

    , comma Variable delimiters (to separate list ofvariables)

    : colon Label delimiters

    ; Semi colon Statement delimiters

    () parenthesis Used in expressions or in functions

    {} Curly braces Used in blocking C structure

    [] Square braces Used along with arrays

    Delimiters are the symbols, which has some syntactic meaning and hasgot significance.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    19/114

    C Statements

    Statements

    Expression Statement Compound Statement Control Statement

    Statement can be defined as set of declarations (or) sequence of actioAll statements in C ends with semicolon(;) except condition and

    control statement

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    20/114

    Expression Statement

    1. An Expression is a combination of constant, variables, operators, and function calls written inany form as per the syntax of the C language.

    2. The values evaluated in these expressions can be stored in variables and used as a part forevaluating larger expressions.

    3. They are evaluated using an assignment statement of the form.

    variable = expression;

    4. For Example,age = 21;

    result = pow(2,2);

    simple_interest = (p * n * r) / 100;

    Algebraic Expression Equivalent C Expression

    (mnp + qr at) (m*n* p+q*r-s*t)

    (a+b+c) (x+y+z) (a+b+c)*(x+y+z)

    abc / x+y (a*b*c) / (x+y)

    8a3 + 3a2 + 2a 8*a*a*a+3*a*a+2*a

    (a-b)+(x-y) / mn ((a-b)+(x-y)) / (m*n)

    8.8(a+b-c) + c / pq 8.8 * (a+b-c) + (c / (p*q))

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    21/114

    CompoundStatements

    1. A group of valid C expression statements placed within an opening flower brace {and closing flower brace } is referred as a CompoundStatements.2. For Example,

    {X = (A + (B * 3) C);

    Y = A + B * 3;Z = A * (B * 3 C);

    }

    1. This statement normally executed sequentially as they appear in the program.

    2. In some situations where we may have to change the order of execution of statementsuntil some specified conditions are met.

    3. The control statement alter the execution of statements depending upon the

    conditions specified inside the parenthesis.4. For Example,

    if (a == b) if ((x < y) && (y > z))

    { {

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

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

    } }

    Control Statements

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    22/114

    OperatorsAn operator is a symbol that specifies an operation to beperformed on the operands

    Some operator needs two operands (binary)

    Eg: a+b;

    + is an operator and a and b are the operands

    Some operator needs one operand (unary)

    Eg: ++a;

    ++ is an operator and a is the operand

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    23/114

    Types of Operatorsoperators

    Arithmetic operator

    Relational operators

    Logical operator

    Assignment operator

    Increment and Decrement Operator (Unary Op.)

    Conditional operator (Ternary operator)

    Bitwise operator

    Special operator

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    24/114

    Arithmetic Operators

    Operator Meaning Examples

    + Addition 1+2 = 3

    - Subtraction 3 -2 = 1

    * Multiplication 2*2 = 4/ Division 2/2 = 1

    % Modulo division 10/3= 1

    This operators help us to carryout basic arithmetic operationssuch addition, subtraction, multiplication, division

    Operation Result Examples

    Int/int int 2/2 = 1

    Real/int real 7.0/2 = 3.5

    Int/real real 7/2.0 = 3.5

    Real/real real 7.0/2.0 = 3.5

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    25/114

    Relational Operator This are used to compare two or more operands.

    Operands can be variables, constants or expression.

    eg: comparison of two marks or two values.

    Operator Meaning Example Returnvalue

    < is less than 5= is greater than or equal to 7>=5 0

    == equal to 6==6 1

    != not equal to 5!=5 0

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    26/114

    Logical Operator

    Operator Meaning Example Return value

    && Logical And (9>2) && (6>4) 1

    || Logical OR (9>2) || (3.4) 1

    ! Logical Not 4 ! 4 0

    AND truth tableTrue True True

    True False False

    False True False

    False False False

    OR truth tableTrue True True

    True False True

    False True True

    False False False

    This operators are used to combine the results of two or moreconditions.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    27/114

    Assignment Operator

    This are used to assign a value or an expression or a variable to another variable eg: a = 10; n1 = 20;

    Syntax:

    identifier = expression;

    a) Compound AssignmentThis operator are used to assign a value to a variable in order to assign a new

    value to a variable after performing a specified operation.eg: a+=10,n1-=20;

    b) Nested Assignment (Multiple)

    This operator are used to assign a single value to multiple variableseg: a=b=c=d=e=10;

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    28/114

    List ofShorthand or Compound AssignmentOperator

    Operator Meaning+= Assign Sum

    -= Assign Difference

    *= Assign Product

    /= Assign Quotient

    %= Assign Remainder

    ~= Assign Ones Complement

    = Assign Right Shift

    &= Assign Bitwise AND

    != Assign Bitwise OR

    ^= Assign Bitwise X - OR

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    29/114

    Increment and Decrement operator

    C provide two operator for incrementing a value ordecrementing a value

    a) ++ Increment operator (adds one to the variable)

    b) -- Decrement operator (Minus one to the variable)

    eg: a++ (if a= 10 then the output would be 11)

    Operator Meaning

    ++X Pre increment

    X++ Post increment

    --X Pre decrement

    X-- Post decrement

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    30/114

    Increment and Decrement operator Conti

    Expression Result

    + + X 4

    X + + 3

    - - X 2

    X - - 3

    If the value of the operand x is 3 then the various expressions and their results

    are

    The pre increment operation (++X) increments x by 1 and then assign

    the value to x. The post increment operation (X++) assigns the value to x andthen increments 1. The pre-decrement operation ( --X) decrements 1 and then

    assigns to x. The post decrement operation (x--) assigns the value to x and

    then decrements 1. These operators are usually very efficient, but causes

    confusion ifyour try to use too many evaluations in a single statement.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    31/114

    Conditional Operator

    It is used check the condition and execute the statementdepending upon the condition

    Syntax Condition?exp1:exp2

    Description The ? operator act as ternaryoperator, it first evaluate thecondition, if it is true then exp1is evaluated if the condition is

    false then exp2 is evaluatedExample a= 2; b=3

    ans = a>b?a:b;

    printf (ans);

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    32/114

    Bitwise Operator This are used to manipulate the data at bit level

    It operates only on integers

    Operator Meaning

    & Bitwise AND

    | Bitwise OR

    ^ Bitwise XOR

    > Shift right

    ~ Ones complement

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    33/114

    Bitwise Operator cont.

    Bitwise AND (both the operand

    should be high for 1)

    0 0 0

    1 1 1

    Bitwise XOR (the two operands

    should be different for 1)

    0 0 1

    1 1 0

    The truth table for Bitwise AND,OR and XOR

    Bitwise OR (either of the operand

    should be high for 1)

    0 0 0

    1 1 1

    Eg: x = 3 = 0000 0011

    y = 4 = 0000 0100

    x&y = 0000 0000

    Eg: x = 3 = 0000 0011

    y = 4 = 0000 0100

    x|y = 0000 0111

    Eg: x = 3 = 0000 0011

    y = 4 = 0000 0100

    x ^ y = 0000 0111

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    34/114

    Bitwise Operator cont.

    Bitwise Ones ComplementThe ones complement operator (~) is a unary operator, which causes the bits of the

    operand to be inverted (i.e., ones becomes zeros and zeros become ones)

    For Example, if x = 7

    i.e 8 bit binary digit is 0 0 0 0 0 1 1 1

    The Ones Complement is 1 1 1 1 1 0 0 0

    Bitwise Left Shift Operator

    The Left shift operator (

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    35/114

    Bitwise Operator cont.

    Bitwise Right Shift OperatorThe Right shift operator (>>) shifts each bit of the operand to its Right. The general

    form or the syntax of Right shift operator is

    variable >> no. of bits positions

    if x = 7 (i.e., 0 0 0 0 0 1 1 1) the value ofy in the expression

    y = x >> 1 is 3

    0 0 0 0 0 0 1 1 = 3 since it shifts the bit position to its right by one bit. The value stored

    in x is divided by 2N (where n is the no of bit positions) to get the required value. For example, if x

    = 7 the result of the expression y = x

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    36/114

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    37/114

    1. Each operator in C has a precedence associated with it.

    2. This precedence is used to determine how an expression involving more than one operator isevaluated.

    3. These are distinct levels of precedence and an operator may belong to one of these levels.4. The operators at the higher level of precedence are evaluated first.

    5. The operators of the same precedence are evaluated either from left to right or from right toleft, depending on the level.

    6. That is known as the associativity property of an operator.

    What is Precedence Rule and Associative Rule

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    38/114

    Arithmetic operators precedence

    The precedence of an operator gives the orderin whichoperators are applied in expressions: the highest precedence

    operator is applied first, followed by the next highest, and so on.

    eg: Arithmetic operator precedence

    Precedence operator

    High *,/,%

    Low +,-

    The arithmetic expression evaluation is carried out using twophases from left to right through the expressions

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    39/114

    Example:if (x == 10 +15 && y

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    40/114

    Precedence and Associativity Table

    The following table lists all the operators, in order ofprecedence, with their associativity

    Operators Operations Associativity priority

    () Function call Left to Right 1

    [] Square brackets

    -> Structure operator

    . Dot operator

    + Unary plus Right to Left 2

    - Unary minus

    ++ Increment

    -- Decrement

    ! Not

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    41/114

    Precedence and Associativity Tablecont.

    Operators Operations Associativity priority

    ~ Complement Right to Left 2

    * Pointer operation

    & Address operator

    Sizeof Size of operator

    type Type cast

    * Multiplication Left to Right 3

    / Division

    % Modulo

    + Addition Left to Right 4

    - Subtraction

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    42/114

    Precedence and Associativity Tablecont.

    Operators Operations Associativity priority

    > Right shift

    < is less than is greater than

    >= is greater than or equal to

    == equal to

    != not equal to

    & Bitwise AND Left to Right 7

    | Bitwise OR

    ^ Bitwise XOR

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    43/114

    Precedence and Associativity Tablecont.

    Operators Operations Associativity priority

    && Logical And Left to Right 8

    || Logical OR

    ?= Conditional Right to Left 9=,*=,-=,&=,+=,^=,!=,=

    Assignment Right to Left 10

    , comma Left to Right 11

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    44/114

    Sample Expression

    Exp = a - 2 * a * b + b / 4

    Let us have a=10,b=20

    exp = 10 - 2 * 10 * 20 + 20 / 4

    Phase I exp = 2*10*20 , 20/4 will be evaluated.

    phase II exp = 10-400+5 will be evaluated.

    Result exp = -395.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    45/114

    Expression Evaluation

    Let us see some examples for evaluating expression.

    Let a = 5, b = 8, c = 2.

    x = b / c + a * c

    410

    14

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    46/114

    Let us see some examples for evaluating expression.

    Let a = 5, b = 8, c = 2.

    y = a + (b * 3) - c

    29

    27

    24

    Expression Evaluation

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    47/114

    TYPE CONVERSION

    OR

    TYPE CASTING

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    48/114

    What is Type Conversion or Type Casting

    Type Casting means One data type converted into another data type. This is called Type

    conversion or Type casting.

    Example:

    1. Integer into floating point number

    2. Character into integer

    3. Floating point number into Integer Number

    Type conversion is classified into two types.

    1. Implicit Type Conversion (Automatic Type Conversion)2. Explicit Type Conversion (Manual Type Conversion)

    Type Conversion

    Implicit

    Conversion

    Explicit

    Conversion

    Automatic

    Conversion

    Casting

    Operation

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    49/114

    Type Conversion Hierarchy

    short char

    int

    unsigned int

    long int

    unsigned long int

    float

    double

    long double

    Implicit

    Type

    Conversion

    Explicit

    Type

    Conversion

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    50/114

    Implicit Type Conversion

    1. The Implicit Type Conversion is known as Automatic Type Conversion.

    2. C automatically converts any intermediate values to the proper type so that the expression can be

    evaluated without loosing any significance.

    3. Implicit type Conversion also known as Converted Lower order data type into Higher order data type.

    4. Implicit Type Conversion also known asWidening.

    Example:

    int a, b;

    float c;c = a + b;

    Print c;

    float a,b;

    int c;

    c = a + b; // This is Wrong

    Print c;

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    51/114

    Explicit Type Conversion

    1. The Explicit Type Conversion is, there are instances when we want to force a type conversion in a way

    that is different from the automatic conversion.

    2. The Explicit Type Conversion is Converted Higher order data type into Lower order data type.

    3. The Explicit type Conversion is also known as borrowing.

    4. The Explicit type conversion forces by a casting operator.

    Disadvantage of Explicit Type Conversion

    1. float to int causes truncation of the fractional part.

    2. double to float causes rounding of digits.

    3. Long int to int causes dropping of the excess higher order bits.

    The general form of the casting is

    (type_name) expression;

    Where type_name is one of the standard C data type.

    The expression may be a constant, variables or an expression.

    For Example:

    float a, b;

    int c;

    c = (int) a + (int) b;

    Print c;

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    52/114

    Use of Casts

    Example Action

    x = (int) 7.5 7.5 is converted to integer by truncation.

    a = (int) 21.3 / (int) 4.5 Evaluated as 21 / 4 and the result would be 5.

    b = (double) sum / n Division is done in floating point mode.

    y = (int) (a + b) The result of a + b is converted to integer.

    z = (int) a + b a is converted to integer and then added to b.

    p = cos ((double) x) Converts x to double before using it.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    53/114

    Input And Output Functions

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    54/114

    Ip / Op Statements

    We have two methods for providing data to the program.

    a) Assigning the data to the variables in a program.

    b) By using the input/output statements.

    c language supports two types of Ip / Op statements

    This operations are carried out through function calls.

    Those function are collectively known as standard I / O library

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    55/114

    Ip / Op Statements cont.

    Ip / Op Functions

    Unformatted Ip / Op statementsInput Outputgetc() putc()getch() putch()Gets() puts()

    Formatted Ip / Op statements

    Input OutputScanf() printf()fscanf() fprintf()

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    56/114

    Unformatted Ip / Op statements

    getch() function

    Syntax char variable = getch();

    Description

    char is the datatype of the variable;

    getch() is thefunction

    Example char x = getch();

    putch (x);

    These statements are used to input / output a single / group of charactersfrom / to the input / output device.

    Single character Input/output function

    putch() function

    Syntax putch (character variable);

    Description char variable is the validc variable of the type ofchar data type.

    Example char x ;

    putch (x);

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    57/114

    Unformatted Ip / Op statements

    cont.

    gets() function

    Syntax gets (char type of arrayvariable);

    Descriptio

    n

    valid c variable declared

    as one dimensional array.

    Example char s[10];

    gets (s);

    Group of character Input / output function.

    Gets() and puts are used to read / display the string from / tothe standard input / output device.

    puts() function

    Syntax puts (char type of arrayvariable)

    Description valid c variable

    declared as onedimensional array.

    Example char s[10];

    gets (s);

    puts (s);

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    58/114

    Unformatted Ip / Op statements

    cont.

    getc() function

    Syntax getc(char type ofvariable, file pointer);

    Descriptio

    n

    The getc function returns

    the next character fromthe input stream pointed

    to by stream

    Example int getc(FILE *stream );

    Single character Input / output function with files.

    Gets() and puts are used to read / display the string from / tothe standard input / output device.

    putc() function

    Syntax putc (char type ofvariable, file pointer)

    Description The putc function

    returns the character

    written .

    Example int putc(int c , FILE

    *stream );

    S l P

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    59/114

    Sample Program#include

    Void main(){charname[10];charaddress[20];

    Puts(Enter the name : );gets(name);puts(Enter the address : );gets(address);

    puts(Name = )puts(name);puts(Address = );puts(address);

    }

    Formatted Ip / Op statements

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    60/114

    Formatted Ip / Op statements It refers to Input / Output that has been arranged in a particular format.

    Using this statements, the user must specify the type of data, that is

    going to be accessed.

    scanf() (This function is used to enterany combination ofinput).

    Syntax scanf (control strings,var1,var2..var n);

    Description control strings is the type of data that user going toaccess via the input statements.

    var1,var2 are the variables in which the datas are

    stored.

    Example int n;

    scanf (%d, &n);

    Formatted Ip / Op statements

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    61/114

    Formatted Ip / Op statements Control strings

    i) It is the type of data that user is going to access via the input statement

    ii) These can be formatted . iii) Always preceded with a % symbol.Formatcode

    Variable type Display

    %c Char Single character

    %d Int Decimal integer -32768 to 32768

    %s Array of char Print a Strings

    %f Float or double Float point value without exponent

    %ld Long int Long integer -65536 to 65535

    %u Int Unsigned decimal integer

    %e Float or double Float point values in exponent form

    %h int Short integer

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    62/114

    Printf()

    printf() (This function is used to display the result or the outputdata on to screen)

    Syntax printf (control strings,var1,var2..var n);

    Description Control strings can be anyone of the following

    a) Format code character code

    b) Execution character set

    c) Character/strings to be displayed

    Var1,var2 are the variables in which the datas arestored.

    Example printf (this is computer fundamental class);

    printf (\n Total is %d and average is %f,sum,avg);

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    63/114

    Control Statements(Decision Making)

    Control Statements

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    64/114

    Control Statements

    Control statements

    Selection Statements Iteration statements

    The if else statement

    The switch statements

    The while loop &Do while loop

    The for loop

    The break statement

    Continue statement

    Goto statement

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    65/114

    Types of Selection Statement

    1. Simple if Selection statement2. if else Selection statement

    3. Nested if else Selection statement

    4. else if ladder Selection statement

    Simple if Selection statement

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    66/114

    Simple ifSelection statement

    It is used to control the flow of execution of the statements andalso to

    test logically whether the condition is true or false.

    if the condition is true then the statement following the if isexecuted if

    it is false then the statement is skipped.

    Syntax:

    if ( condition )

    {

    statement ;

    }

    Test Condition

    Executable X - Statement

    True

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    67/114

    //Biggest of Two Numbers

    #include

    void main(){

    int a, b;

    clrscr();

    printf(Enter the A and B Value:\n);scanf(%d, &a);

    if (a > b)

    {

    printf(A is Big);

    }

    getch();

    }

    The if else statement

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    68/114

    The if else statement

    It is used to execute some statements when the condition is true and execute some

    other statements when the condition is false depending on the logical test.

    Syntax:if ( condition )

    {

    statement 1 ; (if the condition is true this statement will be executed)}

    else

    {statement 2 ; (if the condition is false this statement will be executed)

    }

    Test Condition

    Executable X - Statement

    True

    Executable Y - Statement

    False

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    69/114

    // Biggest of Two Numbers

    #include

    void main()

    {

    int a, b;

    clrscr();

    printf(Enter the A and B Value:\n);

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

    if (a > b)

    {

    printf(A is Big);

    }

    else

    {

    printf(B is Big);}

    getch();

    }

    // Given Number is ODD or EVEN Number

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    70/114

    // Given Number is ODD or EVEN Number

    #include

    void main()

    { int n;

    clrscr();

    printf(Enter the Number:\n);

    scanf(%d, &n);

    if (n % 2 == 0)

    {

    printf(Given Number is Even Number);

    }

    else

    {

    printf(Given Number is Odd Number);}

    getch();

    }

    N t d if l t t t

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    71/114

    Nested if.. else statement

    Syntax:

    if ( condition 1)

    {

    if ( condition 2)

    statement 1 ;else

    statement 2 ;

    }

    else

    {

    if (condition 3)statement 3;

    else

    statement 4;

    }

    when a series of ifelse statements are occurred in a program, we can write an entireifelse statement in another ifelse statement called nesting

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    72/114

    l if L dd M lti l if l St t t

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    73/114

    else if Ladder or Multiple if else Statements

    Syntax:

    if (condition_1)

    executed statement_1;else if (condition_2)executed statement_2;

    else if (condition_3)executed statement_3;

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

    ----------------------else if (condition_n)

    executed statement_n;else

    executed statement_x;

    When a series of decisions are involved we have to use more than one if elsestatement called as multiple ifs. Multiple if else statements are much faster than a

    series of if else statements, since theif structure is exited when any one of the conditionis satisfied.

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    74/114

    Test Condition_1

    Test Condition_2

    Exec. Stat_1

    Test Condition_3

    TRUE

    Test Condition_n

    Exec. Stat_2

    Exec. Stat_3

    Exec. Stat_nExec. Stat_X

    TRUE

    TRUE

    TRUE

    FALSE

    FALSE

    FALSE

    FALSE

    else if Ladder

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    75/114

    else if Ladder

    if (result >= 75)printf ( Passed: Grade A\n ) ;

    else if (result >= 60)

    printf ( Passed: Grade B\n ) ;

    else if (result >= 45)printf ( Passed: Grade C\n ) ;

    else

    printf ( Failed\n ) ;

    THE SWITCH STATEMENT

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    76/114

    THE SWITCH STATEMENT

    The control statements which allow us to make a decision from the

    number of choices is called switch (or) Switch-case statement. It is a multi way decision statement, it test the given variable (or)

    expression against a list of case value.

    switch (expression)

    { case constant 1:

    simple statement (or)

    compound statement;

    case constant 2:

    simple statement (or)

    compound statement;

    case constant 3:

    simple statement (or)

    compound statement;

    }

    switch (expression)

    { case constant 1:

    simple statement (or)

    compound statement;

    case constant 2:

    simple statement (or)

    compound statement;

    default :

    simple statement (or)

    compound statement;

    }

    Example Without Break Statement#include #include

    Example With Break Statement

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    77/114

    #include

    void main ()

    {

    int num1,num2,choice;

    printf(Enter the Two Numbers:\n);

    scanf(%d%d,&num1,&num2);

    printf(1 ->A

    ddition\n);printf(2->Subtraction\n);

    printf(3->Multiplication\n);

    printf(4->Division\n);

    printf(Enter your Choice:\n);

    scanf(%d,&choice);

    switch(choice)

    {

    case 1:

    Printf(Sum is %d\n, num1+num2);

    case 2:

    Printf(Diif. is %d\n, num1-num2);

    case 3:

    Printf(Product is %d\n, num1*num2);

    case 4:

    Printf(Division is %d\n, num1/num2);

    default:

    printf (Invalid Choice..\n);

    }

    getch();

    }

    #include

    void main ()

    {

    int num1,num2,choice;

    printf(Enter the Two Numbers:\n);

    scanf(%d%d,&num1,&num2);

    printf(1 ->A

    ddition\n);printf(2->Subtraction\n);

    printf(3->Multiplication\n);

    printf(4->Division\n);

    printf(Enter your Choice:\n);

    scanf(%d,&choice);

    switch(choice)

    {

    case 1:

    printf(Sum is %d\n, num1+num2);

    break;

    case 2:

    printf(Diif. is %d\n, num1-num2);

    break;

    case 3:

    printf(Product is %d\n, num1*num2);

    break;

    case 4:

    printf(Division is %d\n, num1/num2);break;

    default:

    printf (Invalid Choice..\n);

    }

    getch();

    }

    Rules for Switch

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    78/114

    Rules for Switch

    The expression in the switch statement must be an integer or character constant.

    No real numbers are used in an expression.

    The default is optional and can be placed anywhere, but usually placed at end. The case keyword must be terminated with colon (:);

    No two case constant are identical.

    The values of switch expression is compared with case constant in the orderspecified i.e from top to bottom.

    A switch may occur within another switch, but it is rarely done. Such statementsare called as nested switch statements.

    The switch statement is very useful while writing menu driven programs.

    Iteration Statements

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    79/114

    Iteration Statements1. Iteration statements is also known as Looping statement.2. A segment of the program that is executed repeatedly is called as a loop.

    3.S

    ome portion of the program has to be specified several number of times or until aparticular condition is satisfied.4. Such repetitive operation is done through a loop structure.5. The Three methods by which you can repeat a part of a program are,

    1. while Loops

    2. do.while loops3. for Loop

    Loops generally consist of two parts :

    Control expressions: One or more control expressions which control the execution of

    the

    loop,

    Body : which is the statement or set of statements which is executed

    over and

    over

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    80/114

    Any looping statement , would include the following steps:

    a) Initialization of a condition variableb) Test the control statement.

    c) Executing the body of the loop depending on the condition.

    d) Updating the condition variable.

    While Loop

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    81/114

    e oop

    A while loop has one control expression, and executes as longas that expression is true. The general syntax of a while loop is

    A while loop is an entry controlled loop statement.

    initialize loop counter;

    while (condition)

    {

    statement (s);increment or decrement loop counter

    }

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    82/114

    Start

    Initialize

    Test Condition

    Body of Loop

    Increment or Decrement

    Stop

    False

    True

    Example:

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    83/114

    p

    // Print the I Values

    #include

    void main()

    {

    int i;

    clrscr();

    i = 0;while(i

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    84/114

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    85/114

    Start

    Initialize

    Test Condition

    Body of Loop

    Increment or Decrement

    Stop

    False

    True

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    86/114

    Sl.No. while loop do-while loop

    1. The while loop tests the condition before

    each iteration.

    The do whi le loop tests the condition after

    the first iteration.

    2. If the condition fails initially the loop is

    Skipped entirely even in the first iteration.

    Even if the condition fails initially the loop is

    executed once.

    Difference Between While Loop and Do While Loop

    Example:

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    87/114

    // Print the I Values

    #include

    void main()

    {

    int i;

    clrscr();

    i = 1;while(i

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    88/114

    The for loop is another repetitive control structure, and is used toexecute set of instruction repeatedly until the condition becomesfalse.

    To set up an initial condition and then modify some value to performeach succeeding loop as long as some condition is true.

    The syntax of a for loop is

    The three expressions :

    expr1 - sets up the initial condition,

    expr2 - tests whether another trip through the loop should be taken,

    expr3 - increments or updates things after each trip.

    for(expr1; expr2 ;expr3)

    {

    Body of the loop;

    }

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    89/114

    Start

    Initialize; test_condition; Increment / Decrement

    Body of Loop

    Stop

    Example

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    90/114

    #include

    void main()

    {

    for (int i = 1; i

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    91/114

    Case 1:

    The statement

    p = 1;

    for (n = 0; n < 17; ++ n)

    can be rewritten as

    for (p = 1, n = 0; n < 17;++n)

    Case 2:

    The second feature is that the test condition mayhave any compound

    relation and

    the testing need not be limited only to the loop control variable.

    sum = 0;

    for (i = 1; i < 20 && sum < 100; ++ i)

    {

    sum = sum + i;

    printf(%d %d\n, i, sum);

    }

    Additional Features of for Loop Conti

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    92/114

    Case 3:

    It also permissible to use expressions in the assignment statements of initialization

    and increments sections.

    For Example:for (x = (m + n) / 2; x > 0; x = x / 2)

    Case 4:

    Another unique aspect of for loop is that one or more sections can be omitted, if

    necessary.

    For Example:

    m = 5;for ( ; m ! = 100 ;)

    {

    printf(%d\n,m);

    m = m + 5;

    }

    Both the initialization and increment sections are omitted in the for statement. The

    initialization has been done before the for statement and the control variable is incrementedinside the loop. In such cases, the sections are left blank. However, the semicolonsseparating the sections must remain. If the test condition is not present, the for statementsets up an infinite loop. Such loops can be broken using break or goto statements in theloop.

    Additional Features of for Loop Conti

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    93/114

    Case 5:

    We can set up time delay loops using the null statement as follows:

    for ( j = 1000; j > 0; j = j 1)

    1. This is loop is executed 1000 times without producing any output; it simplycauses a

    time delay.

    2. Notice that the body of the loop contains only a semicolon, known as a nullstatement.

    Nesting of for Loop

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    94/114

    g p

    The One for statement within another for statement is called Nesting for Loop.

    Syntax:

    for (initialize; test_condi; incre. / decre.)

    {

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

    ---------------for (initialize; test_condi; incre. / decre.)

    {

    -----------

    -----------

    }

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

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

    }

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

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

    Outer

    for LoopInner for

    Loop

    Example

    // Print the I and J Value

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    95/114

    // Print the I and J Value

    #include#includevoid main(){

    int I, j;clrscr();

    for (i = 1; I < = 10 ; I ++){

    printf (The I Value is %d \n", i);

    for (j = 1; j < = 10; j ++){

    printf (The J Value is %d \n",

    j);}

    }getch();}

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    96/114

    JUMPS IN LOOPS

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    97/114

    1. Loops perform a set of operations repeatedly until the control variable fails to satisfy the

    test condition.2. The number of times a loop is repeated is decided in advance and the test condition is

    written to achieve this.

    3. Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to

    leave the loop as soon as a certain condition occurs.

    4. Jumps out of a Loop is Classified into three types

    1. break;

    2. continue;

    3. goto;

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    98/114

    The break Statement1. A break statement is used to terminate of to exit a for, switch, while or do while

    statements and the execution continues following the break statement.

    2. The general form of the break statement is

    3. The break statement does not have any embedded expression or arguments.

    4. The break statement is usually used at the end of each case and before the start of the next

    case statement.

    5. The break statement causes the control to transfer out of the entire switch statement.

    break;

    #include

    void main()

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    99/114

    void main()

    {

    int i;

    clrscr();

    i = 1;

    for(i=0;i

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    100/114

    The continue Statement The continue statement is used to transfer the control to the beginning of the loop, there

    by terminating the current iteration of the loop and starting again from the next iteration

    of the same loop.

    The continue statement can be used within a while or a do while or a for loop.

    The general form or the syntax of the continue statement is

    The continue statement does not have any expressions or arguments.

    Unlike break, the loop does not terminate when a continue statement is encountered, but it

    terminates the current iteration of the loop by skipping the remaining part of the loop and

    resumes the control tot the start of the loop for the next iteration.

    continue;

    #include

    void main()

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    101/114

    void main()

    {

    int i;

    clrscr();

    i = 1;

    for(i=0;i

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    102/114

    Sl.No. break continue

    1. Used to terminate the loops or to exit loop

    from a switch.

    Used to transfer the control to the start of

    loop.

    2. The break statement when executed

    causes

    immediate termination of loop containing

    it.

    Continue statement when executed causes

    Immediate termination of the current

    iteration of the loop.

    Differences Between Break and Continu

    e Statement

    The goto Statement

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    103/114

    The goto Statement The goto statement is used to transfer the control in a loop or a function from one point to

    any other portion in that program.

    If misused the goto statement can make a program impossible to understand.

    The general form or the syntax of goto statement is

    The goto statement is classified into two types

    a. Unconditional goto

    b. Conditional goto

    goto label;

    Statement (s);

    .

    label:

    statement (s);

    UnconditionalGoto

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    104/114

    The Unconditional goto means the control transfer from one block to

    another block without checking the test condition.

    Example:

    #include

    void main()

    {

    clrscr();

    Start:

    printf(Welcome\n);

    goto Start;

    getch();

    }

    ConditionalGoto

    Th C diti l t th t l t f f bl k t th

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    105/114

    The Conditional goto means the control transfer from one block to another

    block with checking the test condition.

    #include

    void main()

    {

    int a, b;

    clrscr();

    printf (Enter the Two Value:\n);

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

    if (a > b)

    goto output_1;

    else

    goto output_2;

    output_1:printf (A is Biggest Number);

    goto Stop;

    output_2:

    printf (B is Biggest Number);

    goto Stop;

    Stop:

    getch();

    }

    STORAGE CLASSES

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    106/114

    STORAGE CLASSES

    A storage class defines the scope(visibility) and life time of variables and/orfunctions within a C Program. There are

    following storage classes which can beused in a C Program

    * auto

    * register

    * static

    * extern

    auto - Storage Class

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    107/114

    auto Storage Class

    auto is the default storage class for all

    local variables.

    auto int Month;

    Example 1:

    main()

    {

    auto int i=10;

    printf(%d,i);}

    Example 2:

    main()

    {

    auto int i;

    printf(%d,i);}

    register - Storage Class

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    108/114

    register Storage Class

    registeris used to define local variables that

    should be stored in a register instead of RAM.

    This means that the variable has a maximum

    size equal to the register size (usually one word)and cant have the unary '&' operator applied to it

    (as it does not have a memory location).

    {

    register int Miles;}

    static - Storage Class

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    109/114

    static Storage Class

    static is the default storage class for

    global variables. The two variables below

    (count and road) bothhave a static

    storage class.static int Count;

    E l

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    110/114

    Example

    main()

    {

    add();

    add();

    }

    add()

    {

    static int i=10;

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

    }

    E l

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    111/114

    Example

    void func(void);

    static count=10;

    main()

    {

    while (count--)

    {

    func();}

    }

    void func( void )

    {

    static i = 5;

    i++;printf("i is %d and count is %d\n", i, count);

    }

    extern - Storage Class

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    112/114

    g

    All variables we have seen so farhave had limitedscope (the block in which they are declared) andlimited lifetimes (as for automatic variables).

    However, in some applications it may be useful tohave data which is accessible from within any block

    and/or which remains in existence for the entireexecution of the program. Such variables are calledglobal variables, and the C language providesstorage classes which can meet these requirements;namely, the external (extern) and static (static)classes.

    Declaration for external variable is as follows:

    extern int var;

    E ample

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    113/114

    Example

    int i=10;

    main()

    {

    int i=2;

    printf(%d,i);

    display();

    }

    display()

    {printf(\n%d,i);

    }

  • 8/6/2019 Fundamentals of ProgrammingC Class1

    114/114

    ThankYou!