+ All Categories

7days c

Date post: 05-Apr-2018
Category:
Upload: arvind-singh
View: 221 times
Download: 0 times
Share this document with a friend

of 34

Transcript
  • 8/2/2019 7days c

    1/34

    By-Arvind Singh

  • 8/2/2019 7days c

    2/34

    History of C:-

    C is a programming language developed at AT & Ts Bell Laboratories of USA in 1972. Itwas designed and written by a man named Dennis Ritchie. In that time some languageswere there like Algol-60 and Pascal. C language is member of Algol-60 based languages.CPL (Combined Programming Language) was built but it never implemented after BCPL

    (Basic CPL) came as implemented language. It was rewritten by Ken Thompson in 1970named B specially for UNIX Operating System. Dennis M. Ritche added some new featuresand introduced a new language called C language. The major advance of C over thelanguages B and BCPL was its typing structure. C language adopted some features fromAlgol-68 also.

    The Future of C Language:-

    Although the C may be a base for successful object oriented extensions like C++ and Java,C still running to remain and be used with same qualities as ever. C is still a preferablelanguage to write short efficient low-level code that interacts with the hardware and OS.The old C programmers sometimes used assembly language for doing jobs that is not

    possible to do in C. In future, the programmers in other programming languages may dothe same. They will write the code in their favorite language and for low-level routines andefficiency they will code in C using it as an assembly language.

    Advantages of C language:-- It's a systems language (which means it can be used to do low-level programming withminimal or no run-time).- It is essentially high level assembly (it was designed to write portable OS's in, )- A lot of libraries are written in C and it's easy to find reference code, and to get support.- C code is readable by people who understand most other curly-bracket languages (C++,D, Java, C#).- It lacks advance features (somewhat a disadvantage), but combined with the above pointit's a good language to demonstrate code in.

    C lacks features like classes, templates, and exceptions.

    Overall, it's declining as an applications language, but still holding strong as a systemslanguage.

    Disadvantages of C Language:-1. There is no runtime checking.

    2.There is no strict type checking( for ex: we can pass an integer value for the floating datatype).

    3. As the program extends it is very difficult to fix the bugs

    What is the age of C ?Since the time, it was developed almost 30 years ago; C has been in use, without itsimportance being marginalized. Over a period of time a huge amount of source code hasbeen developed and been made available, and therefore, there is a lot of C to be leant andto be used.

  • 8/2/2019 7days c

    3/34

  • 8/2/2019 7days c

    4/34

    Primary data typeAll C Compilers accept the following fundamental data types

    1. Integer int

    2. Character char

    3. Floating Point float

    4. Double precision floating point double

    5. Void void

    The size and range of each data type is given in the table below

    DATA TYPE RANGE OF VALUES

    char -128 to 127

    Int -32768 to +32767

    float 3.4 e-38 to 3.4 e+38

    double 1.7 e-308 to 1.7 e+308

  • 8/2/2019 7days c

    5/34

    Integer Type :

    Integers are whole numbers with a machine dependent range of values. A goodprogramming language as to support the programmer by giving a control on a range ofnumbers and storage space. C has 3 classes of integer storage namely short int, int andlong int. All of these data types have signed and unsigned forms. A short int requires halfthe space than normal integer values. Unsigned numbers are always positive and consumeall the bits for the magnitude of the number. The long and unsigned integers are used todeclare a longer range of values.

    Floating Point Types :Floating point number represents a real number with 6 digits precision. Floating pointnumbers are denoted by the keyword float. When the accuracy of the floating point numberis insufficient, we can use the double to define the number. The double is same as float but

    with longer precision. To extend the precision further we can use long double whichconsumes 80 bits of memory space.

    Void Type :Using void data type, we can specify the type of a function. It is a good practice to avoidfunctions that does not return any values to the calling function.

    Character Type :A single character can be defined as a defined as a character type of data. Characters areusually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitlyapplied to char. While unsigned characters have values between 0 and 255, signedcharacters have values from 128 to 127.

    Size and Range of Data Types on 16 bit machine.

    TYPE SIZE (Bits) Range

    Char or Signed Char 8 -128 to 127

    Unsigned Char 8 0 to 255

    Int or Signed int 16 -32768 to 32767

  • 8/2/2019 7days c

    6/34

    Unsigned int 16 0 to 65535

    Short int or Signed short int 8 -128 to 127

    Unsigned short int 8 0 to 255

    Long int or signed long int 32 -2147483648 to 2147483647

    Unsigned long int 32 0 to 4294967295

    Float 32 3.4 e-38 to 3.4 e+38

    Double 64 1.7e-308 to 1.7e+308

    Long Double 80 3.4 e-4932 to 3.4 e+4932

    Non-Primitive Data Type:-A non-primitive data type is am abstract data type that is built out of primitive data types -linked list, queue, stack, etc.

    Declaration of VariablesEvery variable used in the program should be declared to the compiler. The declaration doestwo things.

    1. Tells the compiler the variables name.2. Specifies what type of data the variable will hold.

    Example:Int sum;Int number, salary;Double average

  • 8/2/2019 7days c

    7/34

    Datatype Keyword Equivalent

    Character char

    Unsigned Character unsigned char

    Signed Character signed char

    Signed Integer signed int (or) int

    Signed Short Integer signed short int (or) short int (or) short

    Signed Long Integer signed long int (or) long int (or) long

    UnSigned Integer unsigned int (or) unsigned

    UnSigned Short Integer unsigned short int (or) unsigned short

    UnSigned Long Integer unsigned long int (or) unsigned long

    Floating Point float

    Double Precision Floating Point double

    Extended Double Precision Floating Point long double

  • 8/2/2019 7days c

    8/34

    User defined type declaration:-In C language a user can define an identifier that represents an existing data type. The userdefined datatype identifier can later be used to declare variables. The general syntax istypedef type identifier;>

    here type represents existing data type and identifier refers to the row name given to thedata type.Example:typedef intsalary;

    typedef floataverage;

    Here salary symbolizes int and average symbolizes float. They can be later used to declarevariables as follows:

    Units dept1, dept2;Average section1, section2;

    Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 andsection2 are indirectly float data type.

    The second type of user defined datatype is enumerated data type which is defined asfollows.

    Enum identifier {value1, value2 . Value n};

    The identifier is a user defined enumerated datatype which can be used to declare variablesthat have one of the values enclosed within the braces. After the definition we can declarevariables to be of this new type as below.

    enum identifier V1, V2, V3, Vn

    The enumerated variables V1, V2, .. Vn can have only one of the values value1, value2 ..value n

    Example:enumday {Monday, Tuesday, . Sunday};

    enumday week_st, week end;

    week_st = Monday;

    week_end = Friday;

    if(wk_st == Tuesday) week_en = Saturday;

  • 8/2/2019 7days c

    9/34

    Declaration of Storage Class:-Variables in C have not only the data type but also storage class that provides informationabout their location and visibility. The storage class divides the portion of the programwithin which the variables are recognized.

    auto :Auto is the default storage class. It is a local variable known only to the function in

    which it is declared.

    static :Local variable which exists and retains its value even after the control is transferredto the calling function.

    extern :Global variable known to all functions in the file

    register : Social variables which are stored in the register.

    Defining Symbolic Constants:-A symbolic constant value can be defined as a preprocessor statement and used in theprogram as any other constant value. The general form of a symbolic constant is

    # definesymbolic_name value of constant

    Valid examples of constant definitions are :

    # define marks 100# define total 50# define pi 3.14159

    These values may appear anywhere in the program, but must come before it is referencedin the program.It is a standard practice to place them at the beginning of the program.

    Declaring Variable as Constant:-

    The values of some variable may be required to remain constant through-out the program.We can do this by using the qualifier const at the time of initialization.

    Example:Const int class_size = 40;The const data type qualifier tells the compiler that the value of the int variable class _sizemay not be modified in the program.

  • 8/2/2019 7days c

    10/34

    Format Specifiers in C:-

    %c

    %d

    %i

    %f%e

    %E

    %g

    %G

    %o

    %s

    %u

    %x

    %X%p

    %n

    %%

    The character format specifier.

    The integer format specifier.

    The integer format specifier (same as %d).

    The floating-point format specifier.The scientific notation format specifier.

    The scientific notation format specifier.

    Uses %f or %e, whichever result is shorter.

    Uses %f or %E, whichever result is shorter.

    The unsigned octal format specifier.

    The string format specifier.

    The unsigned integer format specifier.

    The unsigned hexadecimal format specifier.

    The unsigned hexadecimal format specifier.Displays the corresponding argument that is a pointer.

    Records the number of characters written so far.

    Outputs a percent sign.

    Getting Started With C:-

    Now we are going to starts with C language -----1. The Character Set Of C:- Character set can be of Alphabets, Digits or special symbols. Itcan be A,B,C.Z, a,b,cz, 1,29, !,@,#,$ and so on.

    2. Constants, Variables and Keywords:- Alphabets, Digits and Special Symbols createsConstants, Variables and keywords.

    Constants:-

    A constants is an entity that does not change. Whatever we calculated, it stores inmemory. Computer memory has millions of cells also known as memory Locations. If thememory location has a value it does not change called constant.

    Types Of Constants:-

    There are two types of constants

  • 8/2/2019 7days c

    11/34

    1.Primary Constants:-

    2. Secondary Constants:-

    Variables:-

    The Name which are given to the memory locations called Variables. These memory locationcontains constants (Integer, Real and Character). Types of variables depend on types ofvariables that it can handle.Particular type of variable can hold only the same type of constants.For Examples:- A integer type of variable can hold integer constant.

    Rules for constructing a variable name:-

    1. The first character in the variable name must be an alphabet orunderscore.

    2. There should be no commas or blank spaces within variable name.3. There should not be any special symbol within a variable name except a underscore.4. Variable name should be 31 characters long.5. variable name should be meaningful so that user can understand.

    Variable typeThe Programming language C has two main variable types1. Local Variables2.Global Variables

    1. Local Variables Local variables scope is confined within the block or function where it is defined.Local variables must always be defined at the top of a block. When a local variable is defined - it is not initialized by the system, you mustinitialize it yourself. When execution of the block starts the variable is available, and when the blockends the variable 'dies'.

  • 8/2/2019 7days c

    12/34

    2. Global Variables Global variable is defined at the top of the program file and it can be visible andmodified by any function that may reference it. Global variables are initialized automatically by the system when you define them!

    Data Type Initialserint 0char '\0'

    float 0

    pointer NULL

    If same variable name is being used for global and local variable then local variabletakes preference in its scope. But it is not a good practice to use global variables andlocal variables with the same name.

    Identifiers:-

    Identifiers are names which are given to elements of a program such as variables , arrays& functions. Basically identifiers are the group of alphabets or digits.

    Rules for making identifier name

    1. the first character of an identifiers must be analphabet or an underscore2. all characters must be letters or digits.3.There is no special characters are allowed except the underscore"_".4. There is no two underscores are allowed.5. don't use keywords as identifiers.

    C Keywords:-1. Keywords are the words whose meanings are already exist in the compiler.2. Keywords can not be use as variable names.3. Keywords are also called Reserved words.4. There are only 32 keywords available in C.

    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

  • 8/2/2019 7days c

    13/34

    Definitions v/s Declaration in CA declaration is when you declare a new variable of some specific type.A definition is when you define a new name for some particular value or type.

    /** A function is only defined if its body is given

    * so this is a declaration but not a definition

    */

    int func_dec(void);

    /** Because this function has a body, it is also* a definition.* Any variables declared inside will be definitions,* unless the keyword 'extern' is used.* Don't use 'extern' until you understand it!*/

    int def_func(void){float f_var; /* a definition */int counter; /* another definition */int rand_num(void); /* declare (but not define) another function */

    return(0);}

    How to write a first C program:-

    Rules:-

    1. In C program each instruction written as a separate statement.2. The statement of a program must be in the sequence by which we want to execute.3. Blank space are not allowed in the variable name but you can use blank spaces betweentwo words which increase readability.4. Statements should be in small case letters.5. Every statement ends with a semicolon (;).6. Semicolon is called statement terminator.7. You can put the comment within a program by using /* .*/.8. Comments are not necessary to use in a program but it is a good habit to use commentsin a program.

    Compilation and Execution of a C Program:-

    1. Write a program using editor.2. Save the file with .c extension.3. To compile the program you can select compile from compile menu and press enter

    or you can press Alt+f94. It will check the errors if program has any error it will terminate the program then

    you can find out he error and you can correct it. After correcting the error you cancompile the program again. After compiling successfully it will create a object (.obj)file.

  • 8/2/2019 7days c

    14/34

    5. Once the source program has been converted into an object file, it is still not in theform that you can run. The reason behind this is that there may be some referencesto standard library functions or user-defined functions in other object files, whichare compiled separately. Therefore these object files are to be linked together alongwith standard library functions that are contained in library files. To link our objectfile, select Link from the Compile menu. After this the .OBJ file will be compiled withthe one or more library files. The result of this linking process produces anexecutable file with .EXE extension. Figure-4 depicts this linking process.

    6. .exe file is a stand alone executable file. which can direct execute from command prompt

    7. After pressing Alt+f9 it will complete the whole process creating .OBJ and .EXE.

    8. To display the output of the program press Alt+f5.

  • 8/2/2019 7days c

    15/34

    Examples of a simple C program:-

    /* Calculation of simple interest */

    main( ){

    int p, n ;float r, si ;p = 1000 ;n = 3 ;r = 8.5 ;/* formula for simple interest */si = p * n * r / 100 ;printf ( "%f" , si ) ;}

    main():-1. main() is a function which is entry point of any program.2. main() is collective name which is given to a set of statements.

    3. This name has to be main(). It can not be change.4. Statements within a main() should be enclosed within a pair of { }.5. main()

    {statement 1;statement 2;}

    6. Every function used in a program must be declared.

    Difference between main() and other functions:-

    1. parameters to main() are passed from command line,

    2. main() is the only function declared by the compiler and defined by the user,

    3. main() is by convention a unique external function,

    4. main() is the only function with implicit return 0; at the end of main(). Whencontrol crosses the ending } for main it returns control to the operating systemby returning 0 to it (if there is no explicit return statement with a return value).The OS normally treats return 0 as the successful termination of the program.

    5. return type for main() is always is an int, (some compilers may accept voidmain() or any other return type, but they are actually treated as if it is declaredas int main(). It makes the code non-portable. Always use int main() ).

    Example:-main(){Int i;Static intj;}

  • 8/2/2019 7days c

    16/34

    NOTES:-

    1. Parameters are passed from command line to main ().2. It is the only function declares by the compiler and defines by the user.3. Return type for main() is always is an int, (some compilers may accept void main() or

    any other return type, but they are actually treated as if it is declared as int main().

    It makes the code non-portable. Always use int main() ).

    Receiving Input:-

    To receive the input from user we use scanf() function in C Language. scanf() is a functionthat reads data with specified format and is present in many other programming languages.

    int scanf(const char *format, ...);

    "scanf" stands for "scan format", because it scans the input for valid tokens and parses

    them according to a specified format.

    #include

    int

    main(void)

    {

    int n;

    while (scanf("%d", &n) == 1)

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

    return 0;

    }Types of Instructions in 'C' Language:-

    There are basically three types of instructions in C:

    (a). Type Declaration Instruction

    (b). Arithmetic Instruction

    (c). Control Instruction

    The purpose of each of these instructions is given below:

    (a). Type Declaration Instruction: To declare the type of variables .

    (b). Arithmetic instruction: To perform arithmetic operations between constants andvariables.

    (c). Control instruction: To control the sequence of execution of various statements.

    1. An arithmetic operation between integer and integer is always integer.

    2. An operation between real and real is always real.

    3. An operation between integer and real is always real.Type Conversion in Assignments

  • 8/2/2019 7days c

    17/34

    the type of the expression and the type of the

    variable on the left-hand side of the assignment operator will not

    be same. In such a case the value of the expression is promoted or

    demoted depending on the type of the variable on left-hand side of equal(=).

    For example, consider the following assignment statements.int i ;

    float b ;

    i = 6.3 ;

    b = 60 ;

    in the example above i is type of integer and b is float type but the value assigned is

    opposite to each other.

    i is having 6.3 which is float and after assigning this value, it will contain only 6 rest of .3 is

    demoted.

    and variable b is having 60 which is integer type and it assign 60.000000, promoted the

    value.

    arithmetic operations are performed in an arithmetic expression is called as Hierarchy of

    operations.

    and if a=4,b=7,c=3 then using the same expression we will obtain two different answers as

    z=5.6 or z=7.

    To avoid this condition we must be aware of hierarchy of operations.

    In arithmetic expressions scanning is always done from left to right.

    The priority of operations is as shown below,

    Priority Operators

    First Parentheses or brackets()

    Second Multiplication & Division

    Third Addition & Subtraction

    Fourth Assignment i.e.=

    If we consider the logical operators used in C language, the operator precedence will be

    like;

    OperatorsType

    ! Logical NOT

    * / %Arithmetic andmodulus

    + - Arithmetic

    Relational

  • 8/2/2019 7days c

    18/34

    == != Relational

    && Logical AND

    || Logical OR

    = Assignment

    In the tables above, the higher the position of an operator, higher is its priority.

    Control Instructions in C

    The Control Instructions enable us to

    specify the order in which instructions in a program are

    to be executed. or the control

    instructions determine the flow of control in a program. There

    are four types of control instructions in C.

    (a) Sequence Control Instruction

    The Sequence control instruction ensures that the instructions are

    executed in the same order in which they appear in the program.

    (b) Selection or Decision Control Instruction

    Decision instructions allow the computer to take

    a decision as to which instruction is to be executed next.

    (c) Repetition or Loop Control Instruction

    The Loop control instruction helps computer to execute a group of statements

    repeatedly.(d) Case Control Instruction

    same as decision control instruction.

    Control Statement:-

    There are 3 types of control statement:-

    1. If Statement

    2. If-else Statement

    3. The Conditional Operators

    If Condition:-

    if (condition is true) execute the statement; The if condition tells the compiler that thecondition is true, execute the statement. Condition of if is always within the pair ofparentheses. If condition is true the statement will execute and condition is false, thestatement will not execute. For checking condition is true or false we use the relational

  • 8/2/2019 7days c

    19/34

    operators.

    Relational Operators:-

    The ExpressionIs TrueIf

    x = = yx isequal toy

    x!=yx is notequal toy

    xyx isgreater

    than y

    x=y

    x isgreaterthan orequal toy

    Example:-main( ){int num ;printf ( "Enter a number less than 10 " ) ;scanf ( "%d", &num ) ;if( num

  • 8/2/2019 7days c

    20/34

    Example:-

    /* Calculation of gross salary */main( ){float bs, gs, da, hra ;

    printf ( "Enter basic salary " ) ;scanf ( "%f", &bs ) ;if( bs < 1500 ){hra = bs * 10/ 100 ;da = bs * 90/ 100 ;}else{hra = 500 ;da = bs * 98/ 100 ;}gs = bs + hra + da ;

    printf ( "gross salary = Rs. %f", gs ) ;}

    Nested If else:-We can use several If else condition within if block or else block. This is called nested ifelse condition.

    Example:-/* program of nested if-else */main( ){int i ;

    printf ( "Enter either 1 or 2 " ) ;scanf ( "%d", &i ) ;if( i == 1 )printf ( "You would go to heaven !" ) ;else{if( i == 2 )

    printf ( "Hell was created with you in mind" ) ;elseprintf ( "How about mother earth !" ) ;}}

    Logical operators:-

    There are only three logical operator in C.1. && AND2. || OR3. ! NOT

    The first two operator allows two or more conditions to be combined in an if statement.Example:-

  • 8/2/2019 7days c

    21/34

    main( ){int m1, m2, m3, m4, m5, per ;printf ( "Enter marks in five subjects " ) ;scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;

    if( per >= 60 )printf ( "First division" ) ;if( ( per >= 50 ) && ( per < 60 ) )printf ( "Second division" ) ;if( ( per >= 40 ) && ( per < 50 ) )printf ( "Third division" ) ;if( per < 40 )printf ( "Fail" ) ;}

    Loops:-

    Loops are required to perform the same series of actions. We frequently need to perform anaction over and over. Ability to perform a set of instructions repeatedly called loops.

    There are three types of loops:-1. for2. while3. do while

    1. for loop:-

    for(initialization_expression; loop_condition; increment_expression){

    // statements

    There are three parts which is separated by semi-colons in control block of thefor loop.initialization_expression is executed before execution of the loop starts. Thisis typically used to initialize a counter for the number of loop iterations. Youcan initialize a counter for the loop in this part.

    The execution of the loop continues until the loop_condition is false. Thisexpression is checked at the beginning of each loop iteration.

    The increment_expression, is usually used to increment the loop counter. This is

    executed at the end of each loop iteration.

    Here is an example of using for loop statement to print an integer five times

  • 8/2/2019 7days c

    22/34

    #include void main(){// using for loop statementint max = 5;int i = 0;for(i = 0; i < max;i++){

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

    2. While Loop:-

    A loop statement allows you to execute a statement or block of statements repeatedly. Firstit check the condition then execute it. If condition is true it execute otherwise dont executethe statement. Here is syntax of while loop statement:

    while(expression) {// statements

    }Here is a while loop statement demonstration program:

    #include void main(){int x = 10;int i = 0;// using while loop statementwhile(i < x){i++;printf("%d\n",i);}// when number 5 found, escape loop body

    int numberFound= 5;intj = 1;while(j < x){if(j == numberFound){printf("number found\n");break;}printf("%d...keep finding\n",j);j++;}}

    Do While Loop:-do while loop statement allows you to execute code block in loop body at least once. Here isdo while loop syntax:

    do {// statements} while (expression);

    Here is an example of using do while loop statement:

  • 8/2/2019 7days c

    23/34

    #include void main(){int x = 5;int i = 0;// using do while loop statementdo{

    i++;printf("%d\n",i);}while(i < x);

    }

    The Odd LoopOdd loop executed the statements withinthem a finite number of times. it execute the statements finite times in the loop.

    /* Execution of a loop an unknown number of times */main( )

    {char another ;int num ;do{printf ( "Enter a number " ) ;scanf ( "%d", &num ) ;printf ( "square of %d is %d", num, num * num ) ;printf ( "\nWant to enter another number y/n " ) ;scanf ( " %c", &another ) ;} while ( another == 'y' ) ;}

    Bitwise operations

    & AND

    &= AND

    | OR

    |= OR

    ^ XOR

    ^= XOR

    ~ one'scompliment

    =Shift Right

    >>=Shift Right

  • 8/2/2019 7days c

    24/34

    AND OR and XOR

    These require two operands and will perform bit comparisons.AND & will copy a bit to the result if it exists in both operands.

    main(){unsigned inta = 60;/* 60 = 0011 1100 */unsigned intb = 13;/* 13 = 0000 1101 */unsigned intc = 0;

    c = a & b; /* 12 = 0000 1100 */}

    OR | will copy a bit if it exists in either operand.

    main(){unsigned inta = 60;/* 60 = 0011 1100 */unsigned int b = 13;/* 13 = 0000 1101 */unsigned intc = 0;

    c = a | b; /* 61 = 0011 1101 */}

    XOR ^ copies the bit if it is set in one operand (but not both).

    main(){unsigned inta = 60;/* 60 = 0011 1100 */unsigned int b = 13;/* 13 = 0000 1101 */unsigned intc = 0;

    c = a ^ b; /* 49 = 0011 0001 */}

    Ones ComplementThis operator is unary (requires one operand) and has the effect of 'flipping' bits.

    main()

    {unsigned int Value = 4; /* 4 = 0000 0100 */

    Value = ~ Value; /* 251 = 1111 1011 */

    }

    Bit shift.The following operators can be used for shifting bits left or right.

  • 8/2/2019 7days c

    25/34

    ,=

    The left operands value is moved left or right by the number of bits specified by the rightoperand. For example:

    main()

    {unsigned int Value=4; /* 4 = 0000 0100 */unsigned intShift=2;

    Value = Value = 40 ) && ( per < 50 ) )printf ( "Third division" ) ;if( per < 40 )printf ( "Fail" ) ;

  • 8/2/2019 7days c

    26/34

    }

    Break Statement:-break statement is used to break any type of loop such as while, do while and for loop.break statement terminates the loop body immediately.

    Example:-

    #include #define SIZE 10void main(){// demonstration of using break statementint items[SIZE] = {1,3,2,4,5,6,9,7,10,0};int number_found = 4,i;for(i = 0; i < SIZE;i++){if(items[i] == number_found){printf("number found at position %d\n",i);break;// break the loop}printf("finding at position %d\n",i);}

    Continue Statement:-

    continue statement is used to break current iteration. After continue statement the controlreturns to the top of the loop test conditions.

    Example continues:-// demonstration of using continue statementfor(i = 0; i < SIZE;i++){if(items[i] != number_found){

    printf("finding at position %d\n",i);continue;// break current iteration}// print number found and break the loopprintf("number found at position %d\n",i);break;}}

    Switch Statement:-

    The switch statement allows you to select from multiple choices based on a set of fixedvalues for a given expression. break keyword is used to signal the end of the block. Hereare the common switch statement syntax:

    switch (expression){

    case value1: /* execute unit of code 1 */

    break;

    case value2: /* execute unit of code 2 */

    break;

  • 8/2/2019 7days c

    27/34

    default: /* execute default action */

    break;

    }

    Here is an example of using C switch statement

    #include

    const int RED = 1;

    const int GREEN = 2;

    const int BLUE = 3;

    void main(){

    int color = 1;

    printf("Enter an integer to choose a

    color(red=1,green=2,blue=3):\n");

    scanf("%d",&color);

    switch(color){

    case RED: printf("you chose red color\n");

    break;

    case GREEN:printf("you chose green color\n");

    break;

    case BLUE:printf("you chose blue color\n");

    break;

    default:printf("you did not choose any color\n");

    }

    }

    Goto statement:-

    The goto statement is use for a jump from one point to another point within a function.

    Example:-

    #include

    #include

    int main() {

    int n = 0;

    loop: ;

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

    n++;

    if (n

  • 8/2/2019 7days c

    28/34

    Functions:-A function is a block of code that performs a particular task. It has a name and it is reusableand it can be executed from as many different parts in a C Program as required. It alsooptionally returns a value to the calling programSo function in a C program has some properties discussed below. Every function has a unique name. This name is used to call function from main()

    function. A function can be called from within another function. A function is independent and it can perform its task without intervention from orinterfering with other parts of the program. A function performs a specific task. A task is a distinct job that your program mustperform as a part of its overall operation, such as adding two or more integer, sorting anarray into numerical order, or calculating a cube root etc. A function returns a value to the calling program. This is optional and depends upon thetask your function is going to accomplish. Suppose you want to just show few lines throughfunction then it is not necessary to return a value. But if you are calculating area ofrectangle and wanted to use result somewhere in program then you have to send back(return) value to the calling function.C language is collection of various inbuilt functions. If you have written a program in C thenit is evident that you have used Cs inbuilt functions. Printf, scanf, clrscr etc. all are Cs

    inbuilt functions. You cannot imagine a C program without function.

    Example:-int sum (int x, int y){int result;result = x + y;return (result);}

    Types of functions:

    A function may belong to any one of the following categories:1. Functions with no arguments and no return values.2. Functions with arguments and no return values.3. Functions with arguments and return values.4. Functions that return multiple values.5. Functions with no arguments and return values.

    #include#includevoid add(int x,int y){int result;result = x+y;

    printf("Sum of %d and %d is %d.\n\n",x,y,result);}void main(){clrscr();add(10,15);add(55,64);

  • 8/2/2019 7days c

    29/34

    add(168,325);getch();}

    Call by value and Call by reference:-

    The argument passed to a function can be of two types:-

    1. value passed (call by value)2. address passed (call by reference)

    Let's say we have an integer variable named x.A call to a function by value using x means (a copy of) the value that x stores is passed inthe function call and no matter what the function does with that value, the value stored in xremains unchanged.A call to a function by reference using x means a reference (also called a pointer or alias) tothe variable x is passed in the function call and so any changes the function makes usingthis reference will actually change the value stored in x.

    Pointer:-In c a pointer is a variable that points to or references a memory location in which data isstored. Each memory cell in the computer has an address that can be used to access thatlocation so a pointer variable points to a memory location we can access and change thecontents of this memory location via the pointer.

    Pointer declaration:A pointer is a variable that contains the memory location of another variable. The syntax isas shown below. You start by specifying the type of data stored in the location identified bythe pointer. The asterisk tells the compiler that you are creating a pointer variable. Finallyyou give the name of the variable.

    type * variable name

    Example:

    int*ptr;float*string;

    Address operator:Once we declare a pointer variable we must point it to something we can do this byassigning to the pointer the address of the variable you want to point as in the followingexample:

    ptr=&num;

    This places the address where num is stores into the variable ptr. If num is stored inmemory 21260 address then the variable ptr has the value 21260.

    /* A program to illustrate pointer declaration*/

    main(){int *ptr;

  • 8/2/2019 7days c

    30/34

    int sum;sum=45;ptr=printf (\n Sum is %d\n, sum);printf (\n The sum pointer is %d, ptr);}

    /* Program to display the contents of the variable their address using pointer variable*/

    #include< stdio.h >{int num, *intptr;float x, *floptr;char ch, *cptr;num=123;x=12.34;ch=a;intptr=&x;cptr=&ch;

    floptr=&x;printf(Num %d stored at address %u\n,*intptr,intptr);printf(Value %f stored at address %u\n,*floptr,floptr);printf(Character %c stored at address %u\n,*cptr,cptr);}

    Pointer expressions & pointer arithmetic:

    Like other variables pointer variables can be used in expressions. For example if p1 and p2are properly declared and initialized pointers, then the

    /* Program to display the contents of the variable their address using pointer variable*/

    include< stdio.h >{int num, *intptr;float x, *floptr;char ch, *cptr;num=123;x=12.34;ch=a;intptr=&x;cptr=&ch;floptr=&x;printf(Num %d stored at address %u\n,*intptr,intptr);printf(Value %f stored at address %u\n,*floptr,floptr);printf(Character %c stored at address %u\n,*cptr,cptr);}

    /*Pointer expression and pointer arithmetic*/#include< stdio.h >main(){

  • 8/2/2019 7days c

    31/34

    int ptr1,ptr2;int a,b,x,y,z;a=30;b=6;ptr1=&a;ptr2=&b;x=*ptr1+ *ptr2 6;

    y=6*- *ptr1/ *ptr2 +30;printf(\nAddress of a +%u,ptr1);printf(\nAddress of b %u,ptr2);printf(\na=%d, b=%d,a,b);printf(\nx=%d,y=%d,x,y);ptr1=ptr1 + 70;ptr2= ptr2;printf(\na=%d, b=%d,a,b);}

    Pointers and function:The pointer are very much used in a function declaration. Sometimes only with a pointer acomplex function can be easily represented and success. The usage of the pointers in a

    function definition may be classified into two groups.1. Call by reference2. Call by value.

    Call by value:We have seen that a function is invoked there will be a link established between the formaland actual parameters. A temporary storage is created where the value of actualparameters is stored. The formal parameters picks up its value from storage area themechanism of data transfer between actual and formal parameters allows the actualparameters mechanism of data transfer is referred as call by value. The correspondingformal parameter represents a local variable in the called function. The current value ofcorresponding actual parameter becomes the initial value of formal parameter. The value of

    formal parameter may be changed in the body of the actual parameter. The value of formalparameter may be changed in the body of the subprogram by assignment or inputstatements. This will not change the value of actual parameters.

    #include< stdio.h >void main(){int x,y;x=20;y=30;printf(\n Value of a and b before function call =%d %d,a,b);fncn(x,y);printf(\n Value of a and b after function call =%d %d,a,b);

    }fncn(p,q)int p,q;{p=p+p;q=q+q;}

    Call by Reference:

  • 8/2/2019 7days c

    32/34

    When we pass address to a function the parameters receiving the address should bepointers. The process of calling a function by using pointers to pass the address of thevariable is known as call by reference. The function which is called by reference can changethe values of the variable used in the call.

    /* example of call by reference*/

    #include< stdio.h >void main(){int x,y;x=20;y=30;printf(\n Value of a and b before function call =%d %d,a,b);fncn(&x,&y);printf(\n Value of a and b after function call =%d %d,a,b);}

    fncn(p,q)

    int p,q;{*p=*p+*p;*q=*q+*q;}

    Pointer to arrays:An array is actually very much like pointer. We can declare the arrays first element as a[0]or as int *a because a[0] is an address and *a is also an address the form of declaration isequivalent. The difference is pointer is a variable and can appear on the left of theassignment operator that is lvalue. The array name is constant and cannot appear as theleft side of assignment operator.

    /* A program to display the contents of array using pointer*/main(){int a[100];int i,j,n;printf("\nEnter the elements of the array\n");scanf(%d,&n);printf("Enter the array elements");for(I=0;I< n;I++)scanf(%d,&a[I]);printf("Array element are");for(ptr=a,ptr< (a+n);ptr++)

    printf("Value of a[%d]=%d stored at address %u",j+=,*ptr,ptr);}

    Strings are characters arrays and here last element is \0 arrays and pointers to char arrayscan be used to perform a number of string functions.

  • 8/2/2019 7days c

    33/34

    Pointers and structures:We know the name of an array stands for the address of its zeroth element the sameconcept applies for names of arrays of structures. Suppose item is an array variable ofstruct type. Consider the following declaration:

    struct products

    {char name[30];int manufac;float net;item[2],*ptr;This statement declares item as array of two elements, each type struct products and ptr asa pointer data objects of type struct products, theassignment ptr=item;would assign the address of zeroth element to product[0]. Its members can be accessed byusing the following notation.ptr- >name;ptr- >manufac;ptr- >net;The symbol - > is called arrow pointer and is made up of minus sign and greater than sign.Note that ptr- > is simple another way of writing product[0].

    When the pointer is incremented by one it is made to pint to next record ie item[1]. Thefollowing statement will print the values of members of all the elements of the productarray.for(ptr=item; ptr< item+2;ptr++)printf("%s%d%f\n",ptr- >name,ptr- >manufac,ptr- >net);

    We could also use the notation

    (*ptr).number

    to access the member number. The parenthesis around ptr are necessary because themember operator . Has a higher precedence than the operator *.

  • 8/2/2019 7days c

    34/34


Recommended