notes on c programming compiled by atul sir

Upload: atul-gupta

Post on 04-Apr-2018

236 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    1/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    1

    Mob-8080373934

    1.INTRODUCTION

    1.1 HISTORY

    C was developed by Dennis Retchie in 1972 at the Bell Telephone Laboratories in .S.A. C wasderived from a Language known as BCPL which was evolved at the Massachusetts Institute ofTechnology in the late 60s. BCPL was used to develop an operating system known asMULTICS for early multi-user time shared computers. One of the aims of BCPL was to achieveefficiency in compiled code. Thus BCPL was defined such that a translator could produceefficient machine Language code. C being a successor of BCPL has a similar philosophy. CLanguage has been defined so that it has the advantages of a high level language namelymachine independence. At the same time it is concise, providing only the bare essentials requiredin a language so that a translator can translate it in to an efficient machine language code. Until

    1978, C was confined to use within Bell Laboratories. In 1978, when Brian Kernighan andRitchie published a description of the language, known as k & rc computer professionals gotimpressed with Cs many desirable features. By mid 1980s, popularity of C became wide spreadNumerous C Compiler were written for computers of all sizes.

    1.2 WHY USE C?

    C (and its object oriented version, C++) is one of the most widely used third generationprogramming languages. Its power and flexibility ensure it is still the leading choice for almost

    all areas of application, especially in the software development environment. Many applicationsare written in C or C++, including the compilers for other programming languages. It is thelanguage many operating systems are written in including Unix, DOS and Windows . Itcontinues to adapt to new uses, the latest being Java, which is used for programming Internetapplications. C has many strengths, it is flexible and portable, it can produce fast, compact code,it provides the programmer with objects to create and manipulate complex structures (e.g classesin C++) and low level routines to control hardware (e.g input and output ports and operatingsystem interrupts). It is also one of the few languages to have an international standard, ANSI C.

    1.3 ALGORITHMS

    1. An algorithm is a description of a procedure which terminates with a result.2. Algorithms is used or solve the problem step by step. It is the part of Software Designing.3. An Algorithm defines as the step by step method that can be carried out for solvingprogramming problems. An Algorithm tells Computer that how to solve the problemSystematically to get desired output.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    2/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    2

    Mob-8080373934

    We follow following steps to design an algorithm.

    1.4 DEVELOPING ALGORITHMS

    Step 1START

    It represents beginning of the algorithm.

    Step 2DECLAREThe variables used in algorithm are declared in this step.

    Step 3INPUTHere we input the values

    Step 4FORMULAThe required result is generated in this step.

    Step 5OUTPUTIt displays the output or result.

    Step 6STOPIt is an end of Algorithm

    An very simple example of an algorithm is multiplying two numbers:on first computers withlimited processors, this was accomplished by a routine that in a number of loop based on the firstnumber adds the second number. The algorithm translates a method into computer commands.

    1.5 ALGORITHMIC EFFICIENCY

    In computer science,efficiency is used to describe properties of an algorithm relating to howmuch of various types of resources it consumes. Algorithmic efficiency can be thought of asanalogous to engineering productivity for a repeating or continuous process, where the goal is toreduce resource consumption, including time to completion, to some acceptable, optimal level.

    The two most frequently encountered and measurable metrics of an algorithm are:-

    speed or running timethe time it takes for an algorithm to complete, and

    'space'the memory or 'non-volatile storage' used by the algorithm during its operation.but also might apply to

    transmission sizesuch as required bandwidth during normal operation or size ofexternal memory-such as temporary disk space used to accomplish its task and

    perhaps even

    http://www.scriptol.com/programming/algorithm-definition.php#examplehttp://en.wikipedia.org/wiki/Computer_sciencehttp://en.wikipedia.org/wiki/Computer_sciencehttp://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Computational_resourcehttp://en.wikipedia.org/wiki/Productivityhttp://en.wikipedia.org/wiki/Memoryhttp://en.wikipedia.org/wiki/Non-volatile_storagehttp://en.wikipedia.org/wiki/External_memoryhttp://en.wikipedia.org/wiki/External_memoryhttp://en.wikipedia.org/wiki/External_memoryhttp://en.wikipedia.org/wiki/Non-volatile_storagehttp://en.wikipedia.org/wiki/Memoryhttp://en.wikipedia.org/wiki/Productivityhttp://en.wikipedia.org/wiki/Computational_resourcehttp://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Computer_sciencehttp://www.scriptol.com/programming/algorithm-definition.php#example
  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    3/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    3

    Mob-8080373934

    the sizeof required 'longterm' disk space required after its operation to record its outputor maintain its required function during its required useful lifetime

    the performance per watt and the total energy, consumed by the chosen hardwareimplementation (with its system requirements, necessary auxiliary support systemsincluding interfaces, cabling, switching, cooling and security), during its required useful

    lifetime.

    http://en.wikipedia.org/wiki/Performance_per_watthttp://en.wikipedia.org/wiki/Performance_per_watthttp://en.wikipedia.org/wiki/Total_energyhttp://en.wikipedia.org/wiki/Computer_hardwarehttp://en.wikipedia.org/wiki/System_requirementshttp://en.wikipedia.org/wiki/Hardware_interfaceshttp://en.wikipedia.org/wiki/Switching_centerhttp://en.wikipedia.org/wiki/Computer_coolinghttp://en.wikipedia.org/wiki/Computer_securityhttp://en.wikipedia.org/wiki/Computer_securityhttp://en.wikipedia.org/wiki/Computer_coolinghttp://en.wikipedia.org/wiki/Switching_centerhttp://en.wikipedia.org/wiki/Hardware_interfaceshttp://en.wikipedia.org/wiki/System_requirementshttp://en.wikipedia.org/wiki/Computer_hardwarehttp://en.wikipedia.org/wiki/Total_energyhttp://en.wikipedia.org/wiki/Performance_per_watt
  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    4/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    4

    Mob-8080373934

    2. C LANGUAGE

    2.1 Structure of a C Program:-

    The structure of a C program can by explained by taking an example of a C program tocalculate area and perimeter of a rectangle. The program is written as follows.

    /* This program prints a one-line message */#include void main(){

    printf("Hello World\n");}

    Comments In the above program the first line in the program starts with /* and ends with */. Any

    thing written between /* and */ is called a comment. /**/ its is a multiline Comment and Single line Comment is represented by // In the C Language comments are an aid to the programmer to read and understand a

    program. It is not a statement of the language. The compiler ignores comments. It is a good practice to include comments in a program which will help in understanding a

    program.

    PREPROCESSOR DIRECTIVENow let us observe the line

    # include

    This is called a preprocessor directive. It is written at the beginning of the program. Itcommands that the contents of the file stdio.h should be included in the compiledmachine code at the place where # include appears. The file stdio.h contains the standardinput/output routines.

    All preprocessor directives begin with pound sign # which must be entered in the firstcolumn. The # include line must not end with a semicolon. Only one preprocessordirective can appear in one line.

    main( ) Function The next line is main( ). It defines what is known as a function in C. A C program is

    made up of many functions. The function main( ) is required in all C programs. It indicates the start of a C program. We will use main( ) at the beginning of all programs.

    Observe that main( ) is not followed by a comma or semicolon.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    5/97

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    6/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    6

    Mob-8080373934

    2.1.7.Multiple declarations

    #include

    int main()

    {int m,y,d;

    m = 1;y = 2;d = 3;

    printf(" %d %d %d \n",m, y, d);return 0;

    }

    C Keywords Keywords are the words whose meaning has already been explained to the C

    compiler. Keywords cannot be used as variable names because if we do so we are trying to

    assign a new meaning to the keyword, which is not allowed by the computer. The keywords are also called Reserved words. There are 32 keywords available in

    C.

    Following is list of keywords in C.auto double if staticbreak else int struct

    case enum long typedefconst float register unioncontinue far return unsigneddefault for short voiddo goto signed white

    Interpreter Vs CompilerProgramming languages can be divided into two major categories: low level and high level. "Assembly

    language" and "machine language" are called low-level languages because they more than others

    "speak" the language the computer understands. On the other hand, C, C++, Pascal, BASIC, Visual Basic,

    Java, and COBOL are high-level languages because they require more manipulation by the computer, aprocess called compiling.

    1) CompilerA compiler is a special program that processes statements written in a particular

    programming language and converts them into machine language, a "binary program" or

    "code," that a computer processor uses. Typically, a programmer writes language statements in

    a language such as C, Pascal, or C++ one line at a time using a tool called an editor. The "edited"

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    7/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    7

    Mob-8080373934

    file contains the source statements. The programmer then runs the appropriate language

    compiler (there may be several compilers for each language), specifying the name of the file that

    contains the source statements.

    When executing the file, the compiler first parses or analyzes all of the language

    statements syntactically in a sequential manner and then, in one or more successive passes,

    builds the output code, ensuring that statements that refer to other statements are referenced

    correctly in the final code. The code is linked to various libraries, which are common code

    sections found in many programs. The use of libraries helps keep redundant coding to a

    minimum. The compilation output is sometimes referred to as object code or an object module.

    (Note that the term "object" as used in this instance is not related to object-oriented

    programming. The object code as used here refers to machine code that the processor executes

    one instruction at a time.)

    2) InterpreterInterpreters translate code one line at time, executing each line as it is "translated,"

    much the way a foreign language interpreter would translate a book, by translating one line at a

    time. Interpreters do generate binary code, but that code is never compiled into one program

    entity. Instead, the binary code is interpreted each and every time the program executes. Someexamples of interpreted programs are BASIC, QBASIC, and Visual Basic (version 5 of which has

    both a compiler and interpreter). Where compiled programs can run on any computer,

    interpreted programs can only run on computers that also have the interpreter.

    Interpreters offer programmers some advantages that compilers do not. Interpreted

    languages are easier to learn than compiled languages, which is great for beginning

    programmers. An interpreter lets the programmer know immediately when and where

    problems exist in the code; compiled programs make the programmer wait until the program is

    complete.

    2.2 C - Storage Classes:

    A storage class defines the scope (visibility) and life time of variables and/or functions within aC Program.

    There are following storage classes which can be used in a C Program

    auto register static extern

    2.2.1 auto - Storage Class

    auto is the default storage class for all local variables.

    {int Count;auto int Month;

    }

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    8/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    8

    Mob-8080373934

    The example above defines two variables with the same storage class. auto can only be usedwithin functions, i.e. local variables.

    2.2.2 register - Storage Class

    register is used to define local variables that should be stored in a register instead of RAM. Thismeans that the variable has a maximum size equal to the register size (usually one word) andcant have the unary '&' operator applied to it (as it does not have a memory location).

    {register int Miles;

    }

    Register should only be used for variables that require quick access - such as counters. It shouldalso be noted that defining 'register' goes not mean that the variable will be stored in a register. Itmeans that it MIGHT be stored in a register - depending on hardware and implimentationrestrictions.

    2.2.3 static - Storage Class

    static is the default storage class for global variables. The two variables below (count and road)both have a static storage class.

    static int Count;int Road;

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

    }

    static variables can be 'seen' within all functions in this source file. At link time, the staticvariables defined here will not be seen by the object modules that are brought in.

    static can also be defined within a function. If this is done the variable is initalised at run time butis not reinitalized when the function is called. This inside a function static variable retains itsvalue during vairous calls.

    void func(void);

    static count=10; /* Global variable - static is the default */

    main(){while (count--){

    func();}

    }

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    9/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    9

    Mob-8080373934

    void func( void ){static i = 5;i++;printf("i is %d and count is %d\n", i, count);

    }

    This will produce following result

    i is 6 and count is 9i is 7 and count is 8i is 8 and count is 7i is 9 and count is 6i is 10 and count is 5i is 11 and count is 4i is 12 and count is 3i is 13 and count is 2i is 14 and count is 1i is 15 and count is 0

    NOTE : Here keyword voidmeans function does not return anything and it does not take anyparameter. You can memoriese void as nothing. static variables are initialized to 0 automatically.

    Definition vs Declaration : Before proceeding, let us understand the difference betweendefintion and declaration of a variable or function. Definition means where a variable or functionis defined in realityand actual memory is allocated for variable or function. Declaration meansjust giving a reference of a variable and function. Through declaration we assure to the complierthat this variable or function has been defined somewhere else in the program and will beprovided at the time of linking. In the above examples char *func(void) has been put at the top

    which is a declaration of this function where as this function has been defined below to main()function.

    There is one more very important use for 'static'. Consider this bit of code.

    char *func(void);

    main(){

    char *Text1;Text1 = func();

    }

    char *func(void){

    char Text2[10]="martin";return(Text2);

    }

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    10/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    10

    Mob-8080373934

    Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storageclass of 'auto' and will disappear when we exit the function and could be overwritten butsomething else. The answer is to specify

    static char Text[10]="martin";

    The storage assigned to 'text2' will remain reserved for the duration if the program.

    2.2.4 extern - Storage Class

    extern is used to give a reference of a global variable that is visible to ALL the program files.When you use 'extern' the variable cannot be initalized as all it does is point the variable name ata storage location that has been previously defined.

    When you have multiple files and you define a global variable or function which will be used inother files also, then extern will be used in another file to give reference of defined variable or

    function. Just for understanding extern is used to decalre a global variable or function in anotherfiles.

    File 1: main.c

    int count=5;

    main(){write_extern();

    }

    File 2: write.c

    void write_extern(void);

    extern int count;

    void write_extern(void){printf("count is %i\n", count);

    }

    Here extern keyword is being used to declare count in another file.

    Now compile these two files as follows

    gcc main.c write.c -o write

    This fill produce write program which can be executed to produce result.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    11/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    11

    Mob-8080373934

    3 Concept of scalar Data Types

    3.1 Data Type:

    3.1.1.What is a data type:

    For each variable you have to attach some data type.

    The data type defines:

    1. the amount of storage allocated to variables.2. the values that they can accept.3. the operations that can be performed on variables.

    3.1.2.Introduction to Data Types

    1. Data type determines how much storage space is allocated to variables.2. Data type determines the permissible operations on variables.3. The variables should be declared by specifying the data type.1. There is a family of integer data types and floating-point data types.2. Characters are stored internally as integers3. Characters are interpreted according to the character set.1. The most commonly used character set is ASCII.2. In the ASCII character set, A is represented by the number 65.

    3.1.3.C Numeric Data Types

    Keyword Variable Type Range

    char Character (or string) -128 to 127

    int Integer -32,768 to 32,767

    short Short integer -32,768 to 32,767

    short int Short integer -32,768 to 32,767

    long Long integer -2,147,483,648 to 2,147,483,647unsigned char Unsigned character 0 to 255

    unsigned int Unsigned integer 0 to 65,535

    unsigned short Unsigned short integer 0 to 65,535

    unsigned long Unsigned long integer 0 to 4,294,967,295

    float Single-precision +/-3.4E10^38 to +/-3.4E10^38

    floating-point

    (accurate to 7 digits)

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    12/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    12

    Mob-8080373934

    double Double-precision +/-1.7E10^308 to +/-1.7E10^308

    floating-point

    (accurate to 15 digits)

    C has really only four types of variables:1. char2. int3. float4. double

    3.2 Other Data Types:

    3.2.1 Bit:

    Each 1 or 0 is called a bit.

    1. Number 1 is 01 in binary.2. Number 2 is 10 in binary.3. Number 3 is 11 in binary.4. Number 4 is 100 in binary.1. For data type char, 8 bits are allocated (1 byte = 8 bits).2. Using 8 bits, you can normally represent decimal numbers from 0 to 255 (0000 0000 to 1111 113. With signed data type, the leftmost bit is the sign of the number.4. If the sign bit is 0, the number is positive,5. If it is 1, the number is negative.1. The range of the number depends on the number of bytes allocated.2. The range of the number also depends whether the number is signed.

    3.2.2 Bits right and left shift:

    #include

    int main(void){

    unsigned int original = 0xABC;

    unsigned int result = 0;unsigned int mask = 0xF;

    printf("\n original = %X", original);

    /* Insert first digit in result */result |= original&mask;

    /* Get second digit */

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    13/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    13

    Mob-8080373934

    original >>= 4;result = 4;

    result

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    14/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    14

    Mob-8080373934

    3. The total memory allocated to the union is equal to the maximum size of the member.#include union marks{

    float percent;char grade;

    };int main ( ){

    union marks student1;student1.percent = 98.5;printf( "Marks are %f address is %16lu\n", student1.percent, &student1.percenstudent1.grade = 'A';printf( "Grade is %c address is %16lu\n", student1.grade, &student1.grade);

    }O/P->Marks are 98.500000 address is 2293620Grade is A address is 2293620

    3.2.4 Constants

    Constant variables are just like normal variables in declaration but Values assigned to it will not change iEntire program life.

    #include

    main(){

    const int x = 20;const float PI = 3.14;

    printf("\nConstant values are %d and %.2f\n", x, PI);

    }O/P->Constant values are 20 and 3.14

    3.2.5 Hexadecimal Numbers:

    1. Hexadecimal numbers use base 16.2. The characters used in hexadecimal numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.3. You can print numbers in hexadecimal form by using the format "x".

    #include

    main(){

    int i = 65;

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    15/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    15

    Mob-8080373934

    printf("%x", i);}

    3.2.6 Octal Numbers:

    Represent a number by using the octal number system.

    The octal number system that is, base 8.

    Use "%o" to print octal numbers.

    #include main(){

    int i = 65;

    printf("%o", i);}

    O/P->101

    3.2.7 Register variable

    Register variable is for faster access.

    Register variable cannot be global variables.

    #include

    main(){

    register int i = 0;

    for( i=0;ivalue of i is 0

    value of i is 1

    3.3 Type Cast or Conversion

    3.3.1 Type Conversion

    1. Type conversion occurs when the expression has data of mixed data types.2. In type conversion, the data type is promoted from lower to higher.3. The hierarchy of data types: double, float, long, int, short, char.

    Example : char c=`a`;

    int i=c;

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    16/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    16

    Mob-8080373934

    3.3.2 Forced Conversion

    Forced conversion occurs when you are converting the value of the larger data type to the value of the

    smaller data type

    When floating points are converted to integers, truncation occurs.

    #include

    main(){

    double f1 = 12.23456;

    printf("%d \n", (int)f1);}O/P->12

    3.3.3 Type CastingType casting is used when you want to convert the value of a variable from one type to another.

    Type casting does not change the actual value of the variable.

    #include

    main(){

    double d1 = 1234.56;int i1=456;

    printf("the value of d1 as int without cast operator %d\n",d1);printf("the value of d1 as int with cast operator %d\n",(int)d1);

    printf("the value of i1 as double without cast operator %f\n",i1);printf("the value of i1 as double with cast operator %f\n",(double)i1);

    i1 = 10;printf("effect of multiple unary operator %f\n",(double)++i1);i1 = 10;printf("effect of multiple unary operator %f\n",(double)- ++i1);i1 = 10;printf("effect of multiple unary operator %f\n",(double)- -i1);i1 = 10;printf("effect of multiple unary operator %f\n",(double)-i1++);

    }

    O/P-> the value of d1 as int without cast operator 1889785610the value of d1 as int with cast operator 1234the value of i1 as double without cast operator 1234.559570the value of i1 as double with cast operator 456.000000effect of multiple unary operator 11.000000effect of multiple unary operator -11.000000effect of multiple unary operator 10.000000effect of multiple unary operator -10.000000

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    17/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    17

    Mob-8080373934

    3.3.4 Data type cast: from int to float

    #include

    int main(void){int count = 110;

    long sum = 10L;float average = 0.0f;

    average = (float)sum/count;

    printf("\nAverage of the ten numbers entered is: %f\n", average);return 0;

    }

    O/P->Average of the ten numbers entered is: 0.090909

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    18/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    18

    Mob-8080373934

    4 Expressing Algorithm Sequence

    4.1 What is Operator?

    Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are calledoperands and + is called operator. C language supports following type of operators.

    Arithmetic Operators Logical (or Relational) Operators Bitwise Operators Assignment Operators Misc Operators

    4.1.1 Arithmetic Operators:

    Here are following arithmetic operators supported by C language:

    Assume variable A holds 10 and variable B holds 20 then:

    Operator Description Example

    + Adds two operands A + B will give 30

    - Subtracts second operand from the first A - B will give -10

    * Multiply both operands A * B will give 200

    / Divide numerator by denumerator B / A will give 2

    %Modulus Operator and remainder of after an

    integer divisionB % A will give 0

    ++Increment operator, increases integer value

    by one

    A++ will give 11

    --Decrement operator, decreases integer value

    by oneA-- will give 9

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    19/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    19

    Mob-8080373934

    Example:main(){

    int a = 21;int b = 10;int c ;

    c = a + b;printf("Line 1 - Value of c is %d\n", c );c = a - b;printf("Line 2 - Value of c is %d\n", c );c = a * b;printf("Line 3 - Value of c is %d\n", c );c = a / b;printf("Line 4 - Value of c is %d\n", c );c = a % b;printf("Line 5 - Value of c is %d\n", c );c = a++;printf("Line 6 - Value of c is %d\n", c );c = a--;

    printf("Line 7 - Value of c is %d\n", c );

    }

    O/P

    Line 1 - Value of c is 31Line 2 - Value of c is 11Line 3 - Value of c is 210Line 4 - Value of c is 2Line 5 - Value of c is 1

    Line 6 - Value of c is 21Line 7 - Value of c is 22

    4.1.2 Logical (or Relational) Operators:

    There are following logical operators supported by C language

    Assume variable A holds 10 and variable B holds 20 then:

    Operator Description Example

    ==Checks if the value of two operands is equal

    or not, if yes then condition becomes true.(A == B) is not true.

    != Checks if the value of two operands is equal

    or not, if values are not equal then condition

    (A != B) is true.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    20/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    20

    Mob-8080373934

    becomes true.

    >

    Checks if the value of left operand is greater

    than the value of right operand, if yes then

    condition becomes true.

    (A > B) is not true.

    =

    Checks if the value of left operand is greater

    than or equal to the value of right operand, if

    yes then condition becomes true.

    (A >= B) is not true.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    21/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    21

    Mob-8080373934

    if( a == b ){

    printf("Line 1 - a is equal to b\n" );}else{

    printf("Line 1 - a is not equal to b\n" );}if ( a < b ){

    printf("Line 2 - a is less than b\n" );}else{

    printf("Line 2 - a is not less than b\n" );}if ( a > b ){

    printf("Line 3 - a is greater than b\n" );}else{

    printf("Line 3 - a is not greater than b\n" );}/* Lets change value of a and b */a = 5;b = 20;if ( a = a ){

    printf("Line 5 - b is either greater than or equal to b\n" );}if ( a && b ){

    printf("Line 6 - Condition is true\n" );}if ( a || b ){

    printf("Line 7 - Condition is true\n" );}/* Again lets change the value of a and b */a = 0;b = 10;if ( a && b ){

    printf("Line 8 - Condition is true\n" );}else{

    printf("Line 8 - Condition is not true\n" );}if ( !(a && b) ){

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    22/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    22

    Mob-8080373934

    printf("Line 9 - Condition is true\n" );}

    }

    This will produce following result

    Line 1 - a is not equal to bLine 2 - a is not less than bLine 3 - a is greater than bLine 4 - a is either less than or euqal to bLine 5 - b is either greater than or equal to bLine 6 - Condition is trueLine 7 - Condition is trueLine 8 - Condition is not trueLine 9 - Condition is true

    4.1.3 Bitwise Operators:

    Bitwise operator works on bits and perform bit by bit operation.

    Assume if A = 60; and B = 13; Now in binary format they will be as follows:

    A = 0011 1100

    B = 0000 1101

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

    A&B = 0000 1100

    A|B = 0011 1101

    A^B = 0011 0001

    ~A = 1100 0011

    There are following Bitwise operators supported by C language

    Operator Description Example

    &Binary AND Operator copies a bit to the

    result if it exists in both operands.(A & B) will give 12 which is 0000 1100

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    23/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    23

    Mob-8080373934

    |Binary OR Operator copies a bit if it exists in

    eather operand.(A | B) will give 61 which is 0011 1101

    ^Binary XOR Operator copies the bit if it is set

    in one operand but not both.

    (A ^ B) will give 49 which is 0011 0001

    ~Binary Ones Complement Operator is unary

    and has the efect of 'flipping' bits.(~A ) will give -60 which is 1100 0011

    > 2 will give 15 which is 0000 1111

    Example:

    main(){

    unsigned int a = 60; /* 60 = 0011 1100 */

    unsigned int b = 13; /* 13 = 0000 1101 */int c = 0;

    c = a & b; /* 12 = 0000 1100 */printf("Line 1 - Value of c is %d\n", c );

    c = a | b; /* 61 = 0011 1101 */printf("Line 2 - Value of c is %d\n", c );

    c = a ^ b; /* 49 = 0011 0001 */printf("Line 3 - Value of c is %d\n", c );

    c = ~a; /*-61 = 1100 0011 */

    printf("Line 4 - Value of c is %d\n", c );

    c = a > 2; /* 15 = 0000 1111 */printf("Line 6 - Value of c is %d\n", c );

    }

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    24/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    24

    Mob-8080373934

    This will produce following result

    Line 1 - Value of c is 12Line 2 - Value of c is 61Line 3 - Value of c is 49Line 4 - Value of c is -61Line 5 - Value of c is 240Line 6 - Value of c is 15

    4.1.4 Assignment Operators:

    There are following assignment operators supported by C language:

    Operator Description Example

    =

    Simple assignment operator, Assigns

    values from right side operands to left

    side operand

    C = A + B will assigne value of A + B into C

    +=

    Add AND assignment operator, It adds

    right operand to the left operand and

    assign the result to left operand

    C += A is equivalent to C = C + A

    -=

    Subtract AND assignment operator, It

    subtracts right operand from the left

    operand and assign the result to left

    operand

    C -= A is equivalent to C = C - A

    *=

    Multiply AND assignment operator, It

    multiplies right operand with the left

    operand and assign the result to left

    operand

    C *= A is equivalent to C = C * A

    /=

    Divide AND assignment operator, Itdivides left operand with the right

    operand and assign the result to left

    operand

    C /= A is equivalent to C = C / A

    %= Modulus AND assignment operator, It C %= A is equivalent to C = C % A

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    25/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    25

    Mob-8080373934

    takes modulus using two operands and

    assign the result to left operand

    > 2

    &= Bitwise AND assignment operator C &= 2 is same as C = C & 2

    ^=bitwise exclusive OR and assignment

    operatorC ^= 2 is same as C = C ^ 2

    |=bitwise inclusive OR and assignment

    operator

    C |= 2 is same as C = C | 2

    Example:

    main(){

    int a = 21;int c ;

    c = a;printf("Line 1 - = Operator Example, Value of c = %d\n", c );

    c += a;printf("Line 2 - += Operator Example, Value of c = %d\n", c );

    c -= a;printf("Line 3 - -= Operator Example, Value of c = %d\n", c );

    c *= a;printf("Line 4 - *= Operator Example, Value of c = %d\n", c );

    c /= a;printf("Line 5 - /= Operator Example, Value of c = %d\n", c );

    c = 200;c %= a;

    printf("Line 6 - %= Operator Example, Value of c = %d\n", c );

    c = 2;printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );

    c &= 2;

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    26/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    26

    Mob-8080373934

    printf("Line 9 - &= Operator Example, Value of c = %d\n", c );

    c ^= 2;printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );

    c |= 2;

    printf("Line 11 - |= Operator Example, Value of c = %d\n", c );

    }

    This will produce following result

    Line 1 - = Operator Example, Value of c = 21Line 2 - += Operator Example, Value of c = 42Line 3 - -= Operator Example, Value of c = 21Line 4 - *= Operator Example, Value of c = 441Line 5 - /= Operator Example, Value of c = 21

    Line 6 - %= Operator Example, Value of c = 11Line 7 - = Operator Example, Value of c = 11Line 9 - &= Operator Example, Value of c = 2Line 10 - ^= Operator Example, Value of c = 0Line 11 - |= Operator Example, Value of c = 2

    4.1.5 Misc Operators

    There are few other operators supported by C Language.

    Operator Description Example

    sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return 4.

    & Returns the address of an variable. &a; will give actaul address of the variable.

    * Pointer to a variable. *a; will pointer to a variable.

    ? : Conditional Expression If Condition is true ? Then value X : Otherwisevalue Y

    Operators Categories:

    All the operators we have discussed above can be categorized into following categories:

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    27/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    27

    Mob-8080373934

    Postfix operators, which follow a single operand. Unary prefix operators, which precede a single operand. Binary operators, which take two operands and perform a variety of arithmetic and

    logical operations. The conditional operator (a ternary operator), which takes three operands and evaluates

    either the second or third expression, depending on the evaluation of the first expression. Assignment operators, which assign a value to a variable. The comma operator, which guarantees left-to-right evaluation of comma-separated

    expressions.

    4.1.6 Precedence of C Operators:

    Operator precedence determines the grouping of terms in an expression. This affects how anexpression is evaluated. Certain operators have higher precedence than others; for example, themultiplication operator has higher precedence than the addition operator:

    For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higherprecedence than + so it first get multiplied with 3*2 and then adds into 7.

    Here operators with the highest precedence appear at the top of the table, those with the lowestappear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    Category Operator Associativity

    Postfix () [] -> . ++ - - Left to right

    Unary + - ! ~ ++ - - (type) * & sizeof Right to left

    Multiplicative * / % Left to right

    Additive + - Left to right

    Shift > Left to right

    Relational < >= Left to right

    Equality == != Left to right

    Bitwise AND & Left to right

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    28/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    28

    Mob-8080373934

    Bitwise XOR ^ Left to right

    Bitwise OR | Left to right

    Logical AND && Left to right

    Logical OR || Left to right

    Conditional ?: Right to left

    Assignment = += -= *= /= %= >>=

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    29/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    29

    Mob-8080373934

    printf("Hello World");

    only has a control string and, as this contains no % characters it results in Hello World beingdisplayed and doesn't need to display any variable values. The specifier %d means convert thenext value to a signed decimal integer and so:

    printf("Total = %d",total);

    will print Total = and then the value passed by &total as a decimal integer.

    The % Format Specifiers :

    The % specifiers that you can use in ANSI C are:

    Usual variable type Display

    %c char single character

    %d (%i) int signed integer

    %e (%E) float or double exponential format

    %ffloat or double signed decimal

    %o int unsigned octal value

    %p pointer address stored in pointer

    %s array of char sequence of characters

    %u int unsigned decimal

    %x (%X) int unsigned hex value

    Try following program to understand printf() function.

    #include

    main(){

    int dec = 5;char str[] = "abc";char ch = 's';float pi = 3.14;

    printf("%d %s %f %c\n", dec, str, pi, ch);}

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    30/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    30

    Mob-8080373934

    The output of the above would be:

    5 abc 3.140000 c

    Finally there are thecontrolcodes:

    \b backspace

    \f formfeed

    \n new line

    \r carriage return

    \t horizontal tab

    \' single quote

    \0 null

    If you include any of these in the control string then the corresponding ASCII control code issent to the screen, or output device, which should produce the effect listed. In most cases youonly need to remember\n for new line.

    4.2.2 scanf() function:

    This is the function which can be used to to read an input from the command line. The scanffunction works in much the same way as the printf. That is it has the general form:

    scanf(control string,variable,variable,...)

    In this case the control string specifies how strings of characters, usually typed on the keyboard,should be converted into values and stored in the listed variables.

    scanf("%d %d",&i,&j);

    will read in two integer values into i andj. The integer values can be typed on the same line oron different lines as long as there is at least one white space character between them.

    Example:#include

    int main(){

    int myvariable;

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    31/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    31

    Mob-8080373934

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

    return 0;}

    See, when we used scanf we first declared what the variables type was"%d" for int ,"%f" for float ,"%e" for a scientific notation (1e10) ,"%c" for char , "%s" forstrings.

    4.3 The Standard Library Functions

    Some of the "commands" in C are not really "commands" at all but are functions. For example,we have been using printfand scanfto do input and output, and we have used rand to generaterandom numbers - all three are functions.

    The most common libraries and a brief description of the most useful functions they containfollows:

    1. stdio.h: I/O functions:1. getchar()- returns the next character typed on the keyboard.2. putchar()- outputs a single character to the screen.3. printf() -as previously described4. scanf()- as previously described

    2. string.h: String functions1. strcat() -concatenates a copy of str2 to str12.

    strcmp()- compares two strings3. strcpy() -copys contents of str2 to str1

    3. ctype.h: Character functions1. isdigit() -returns non-0 if arg is digit 0 to 92. isalpha() -returns non-0 if arg is a letter of the alphabet3. isalnum() -returns non-0 if arg is a letter or digit4. islower()- returns non-0 if arg is lowercase letter5. isupper() -returns non-0 if arg is uppercase letter

    4. math.h: Mathematics functions1. acos() -returns arc cosine of arg2. asin()- returns arc sine of arg3. atan()- returns arc tangent of arg4. cos()- returns cosine of arg5. exp()- returns natural logarithim e6. fabs()- returns absolute value of num7. sqrt()- returns square root of num

    5. time.h: Time and Date functions

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    32/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    32

    Mob-8080373934

    1. time()- returns current calender time of system2. difftime()- returns difference in secs between two times3. clock() -returns number of system clock cycles since program execution

    6. stdlib.h:Miscellaneous functions1. malloc()- provides dynamic memory allocation, covered in future sections2. rand() -as already described previously3. srand() -used to set the starting point for rand()

    4.4 Assignment statement

    Once you've declared a variable you can use it, but not until it has been declared - attempts to usea variable that has not been defined will cause a compiler error. Using a variable means storingsomething in it. You can store a value in a variable using:

    name = value;

    For example:

    a=10;

    stores the value 10 in the int variable a. What could be simpler? Not much, but it isn't actuallyvery useful! Who wants to store a known value like 10 in a variable so you can use it later? It is10, always was 10 and always will be 10. What makes variables useful is that you can use themto store the result of some arithmetic.

    Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us see

    how C would use these operations on two float variables a and b.add

    a+b

    subtract

    a-b

    multiply

    a*b

    divide

    a/b

    Note that we have used the following characters from C'scharacter set:

    http://www.le.ac.uk/cc/rjm1/c/ccccchar.htmlhttp://www.le.ac.uk/cc/rjm1/c/ccccchar.htmlhttp://www.le.ac.uk/cc/rjm1/c/ccccchar.htmlhttp://www.le.ac.uk/cc/rjm1/c/ccccchar.html
  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    33/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    33

    Mob-8080373934

    + for add

    - for subtract

    * for multiply

    / for divide

    BE CAREFUL WITH ARITHMETIC!!! What is the answer to this simple calculation?

    a=10/3

    The answer depends upon how a was declared. If it was declared as type int the answer will be3; ifa is of type float then the answer will be 3.333. It is left as an exercise to the reader to findout the answer for a of type char.

    Two points to note from the above calculation:1. C ignores fractions when doing integer division!2. When doing float calculations integers will be converted into float.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    34/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    34

    Mob-8080373934

    5 Expressing Algorithm Iteration and

    Selection

    5.1 Loops:In every programming language, thus also in the C programming language, there are

    circumstances were you want to do the same thing many times. For instance you want to printthe same words ten times. You could type ten printf functions, but it is easier to use a loop. Theonly thing you have to do is to setup a loop that executes the same printf function ten times.

    There are three basic types of loops which are:

    for loop while loop do while loop

    5.1.1 for Loop:

    The for loop loops from one number to another number and increases by a specifiedvalue each time. A for loop has three parts:

    The setup The exit condition for which the loop finishes The part that loops, which is the statements that are repeated

    Syntax for for Loop:

    for(initialize counter variable ; condition ; increment/decrement the counter variable)

    {

    Statement1;

    ...

    Statement n;

    }

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    35/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    35

    Mob-8080373934

    Look at the example below:

    #include

    int main(){

    int i;for (i = 0; i < 10; i++){

    printf ("Hello\n");printf ("World\n");

    }return 0;}

    Note:A single instruction can be placed behind the for loop without the curly brackets.

    Lets look at the for loop from the example: We first start by setting the variable i to 0. This iswhere we start to count. Then we say that the for loop must run if the counter i is smaller thenten. Last we say that every cycle i must be increased by one (i++).

    In the example we used i++ which is the same as using i = i + 1. This is called incrementing. Theinstruction i++ adds 1 to i. If you want to subtract 1 from i you can use i--. It is also possible touse ++i or --i. The difference is is that with ++i (prefix incrementing) the one is added beforethe for loop tests if i < 10. With i++ (postfix incrementing) the one is added after the test i b){goto first;}else{goto second;}

    first:printf("\n A is greater..");goto g;

    second:printf("\n B is greater..");

    g:getch();}

    O/P

    Enter 2 nos A and B one by one :

    12 34

    B is greater..

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    40/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    40

    Mob-8080373934

    5.2 The if and switch Statement:

    Boolean Operators

    Before we can take a look at test conditions we have to know what Boolean operators are. Theyare called Boolean operators because they give you either true or false when you use them to testa condition. The greater than sign >for instance is a Boolean operator. In the table below you see all the Boolean operators:

    == Equal

    ! Not

    != Not equal

    > Greater than

    = Greater than or equal

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    41/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    41

    Mob-8080373934

    So lets take a look at an example:

    #include

    int main()

    {

    int mynumber;

    scanf("%d",&mynumber);if ( mynumber == 10 )

    printf("Is equal\n");return 0;

    }

    In the example above the user can input a number. The number is stored in the variablemynumber.

    Now take a look at the if statement: if the number stored in the variable mynumber is equal toten, then print is equal on the screen. Simple, isnt it. If the number is not equal to ten, then

    nothing gets printed.

    Now take another look at the if statement: look at the placement of the semi-colon. As you cansee there is no semi-colon behind the if statement. If there is just one instruction (if thestatement is true), you can place it after theif statement (with an indentation). Are multiple instructions necessary then you will have touse curly brackets, like so:

    if ( mynumber == 10){printf("is equal\n");printf("closing program\n");

    }

    Now we like to also print something if the if statement is not equal. We could do this byadding another if statement but there is an easier / better way. Which is using the so called

    else statement with the if statement.

    #include

    int main(){

    int mynumber;scanf("%d",&mynumber);

    if ( mynumber == 10 ){

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    42/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    42

    Mob-8080373934

    printf("Is equal\n");printf("Closing program\n");

    }else{

    printf("Not equal\n");printf("Closing program\n");

    }return 0;

    }

    Note: Take a look at the placement of the curly brackets and how the indentations are placed.This is all done to make reading easier and to make less mistakes in large programs.

    Nested if statements

    If you use an if statement in an if statement it is called nesting. Nestingif statements can

    make a program very complex, but sometimes there is no other way. So use it wisely.

    Syntax:

    if(condition)

    {

    //code

    }

    else if(condition)

    {

    //code

    }

    else

    {

    //code

    }

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    43/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    43

    Mob-8080373934

    Take a look at a nested if statement example below:

    #include

    int main()

    {int grade;

    scanf("%d",&grade);if ( grade 10 && b > 20 && c < 10 )

    If a is greater then ten and b is greater then twenty and c is smaller then ten, do something. So allthree conditions must be true, before something happens.

    With the OR ( || ) operator you can test if one of two conditions are true. Example:

    if ( a = 10 || b < 20 )

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    44/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    44

    Mob-8080373934

    If a equals ten or b is smaller then twenty then do something. So if a or b is true, somethinghappens.

    The switch statement

    The switch statement is almost the same as an if statement. The switch statement can havemany conditions. You start the switch statement with a condition. If one of the variable equalsthe condition, the instructions are executed. It is also possible to add a default. If none of thevariable equals the condition the default will be executed.

    Syntax:

    switch(expression)

    {

    case condition1: //code

    case condition 2: //code

    . . .

    case condition n: //code

    default: //code

    }

    See the example below:

    #include

    int main()

    {char myinput;

    printf("Which option will you choose:\n");printf("a) Program 1 \n");

    printf("b) Program 2 \n");scanf("%c", &myinput);

    switch (myinput){

    case 'a':printf("Run program 1\n");break;

    case 'b':{

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    45/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    45

    Mob-8080373934

    printf("Run program 2\n");printf("Please Wait\n");break;

    }default:

    printf("Invalid choice\n");break;

    }return 0;

    }

    O/P Which option will you choose:aRun program 1

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    46/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    46

    Mob-8080373934

    6 Function in C

    6.1 DefiningFunction in C:

    Most languages allow you to create functions of some sort. Functions are used to breakup large programs into named sections. You have already been using a function which is themain function. Functions are often used when the same piece of code has to run multiple times.

    A function is a block of code that has a name and it has a property that it is reusable i.e. it can beexecuted from as many different points in a C Program as required. Function groups a number ofprogram statements into a unit and gives it a name. This unit can be invoked from other parts of aprogram. A computer program cannot handle all the tasks by it self. Instead its requests otherprogram like entitiescalled functions in Cto get its tasks done. A function is a self containedblock of statements that perform a coherent task of same kind

    The name of the function is unique in a C Program and is Global. It means that a functioncan be accessed from any location within a C Program. We pass information to the functioncalled arguments specified when the function is called. And the function either returns somevalue to the point it was called from or returns nothing.

    We can divide a long C program into small blocks which can perform a certain task. A functionis a self contained block of statements that perform a coherent task of same kind.

    Structure of a Function

    There are two main parts of the function. The function header and the function body.int sum(int x, int y){

    int ans = 0; //holds the answer that will be returnedans = x + y; //calculate the sumreturn ans //return the answer

    }

    Function Header

    In the first line of the above code

    int sum(int x, int y)

    It has three main parts

    1. The name of the function i.e. sum2. The parameters of the function enclosed in paranthesis3. Return value type i.e. int

    http://www.codingunit.com/c-tutorial-the-if-and-switch-statementhttp://www.codingunit.com/c-tutorial-the-if-and-switch-statementhttp://www.codingunit.com/c-tutorial-the-if-and-switch-statement
  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    47/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    47

    Mob-8080373934

    Function Body

    What ever is written with in { } in the above example is the body of the function.

    Simple Functions

    Our first example demonstrates a simple function those purpose is to print a line of 45asterisks.The example program generates a table , and lines of asterisks are used to make thetable more readable. Heres the listing for Table:

    // table .cpp// demonstrates simpole function# includeusing namespace std;void starline( );into main (){

    starline ( );cout

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    48/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    48

    Mob-8080373934

    Why we use Functions

    The most important reason to use functions is to aid in the conceptual organization of a program.

    Another reason to use functions is to reduce program size. Any sequence of instructions that

    appears in program more than once is a candidate for being made into a function. The functionscode is stored in only one place in memory, even though the function is executed many times inthe course of the program.

    Two reasons

    1. Writing functions avoids rewriting the same code over and over. Suppose that there is a sectionof code in a program that calculates area of a triangle. If, later in the program we want to

    calculate the area of a different triangle we wont like to write the same instructions all over

    again. Instead we would prefer to jump to a section of code that calculates area and then

    jump back to the place from where you left off. This section of code is nothing but a function.

    2. Using functions it becomes easier to write programs and keep track of what they are doing. Ifthe operation of a program can be divided in to separate activities, and each activity placed in a

    different function, then each could be written and checked more or less independently.

    Separating the code in to modular functions also makes the pro-gram easier to design and

    understand.

    Function Declaration

    Just as you cant use a variable without first telling the compler what it is, you also cant use a

    funciotns without teling the compiler about it, There are two ways to do this . The approach weshow here ist o declare the funtion before it is called. The other approach is to define it beforeits called. ; well examine that next.) in the Table program, the functions starline() is declared inthe line.

    Void starline ( );

    The declaration tells the compiler that at some later point we plan to present a function calledstarline. The keyword void specifies that the function has no return value, and the emptyparentheses indicate that it takes no arguments.

    Notice that the funtois declarations is terminated with a semicolon It is a complete statement initself.

    Function declarations are also called prototypes, since they provide a model or blueprint for thefunction. They tell the compiler, a function that looks like this is coming up later in theprogram, so its all right if you see references to it before you see the function itself.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    49/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    49

    Mob-8080373934

    Calling the Function

    The function is called (or invoked) three times from main (). Each of the three calls look likethis:

    Starline():

    This is all we need to call a function name,followed by parentheses. The syntax of the call is verysimilar to that of declaration, except that the return type is not used. A semicolon terminates thecall. Executing the call statement causes the function to execute; that is, control is transferred tothe function, the statement in the function definition are executed, and then control returnsto the statement following the function call.

    Function Definition

    Finally, we come to the functions its self, which is referred to as the functions definition, The

    definition contains the actual code for the function. Heres the definition for starline( ) .

    void starline ( ){for ( intj=0, j < 45; j++ )cout

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    50/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    50

    Mob-8080373934

    main ( )

    {

    message ( );

    }

    3. Function is defined when function name is followed by a pair of braces in which one ormore statements may be present for e.g.

    message ( )

    {

    statement 1;

    statement2;

    statement 3;

    }

    4. Any function can be called from any other function even main ( ) can be called fromother functions. for e.g.

    main ( )

    {

    message ( );

    }

    message ( )

    {

    printf (\n Hello);

    main ( );

    }

    5. A function can be called any number of times for eg.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    51/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    51

    Mob-8080373934

    main ()

    {

    message ( );

    message ( );

    }

    message ( )

    {

    printf (\n Hello);

    }

    6. The order in which the functions are defined in a program and the order in which they getcalled need not necessarily be same for e.g.

    main ( );

    {

    message 1 ( );

    message 2 ( );

    }

    message 2 ( )

    {

    printf (\n I am learning C);

    }

    message 1 ( )

    {

    printf ( \n Hello );

    }

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    52/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    52

    Mob-8080373934

    7. A function can call itself such a process as called recursion.8. A function can be called from other function, but a function cannot be defined in an-other

    function. These the following program code would be wrong, since Argentina is beingdefined inside another function main ( ).

    main ( ){

    printf (\n I am in main);

    argentina ( )

    {

    printf {\n I am in argentina);

    }

    }

    9. Any C program contains at least one function.10.If a program contains only one function, it must be main( ).11.In a C program if there are more than one functional present then one of these func-tional

    must be main( ) because program execution always begins with main( ).12.There is no limit on the number of functions that might be present in a C program.13.Each function in a program is called in the sequence specified by the function calls in

    main( )14.After each function has done its thing, control returns to the main( ), when main( ) runsout of function calls, the program ends.

    Functions declaration and prototypes Any function by default returns an int value. If we desirethat a function should return a value other than an int, then it is necessary to explicitly mentionso in the calling functions as well as in the called function. for e.g

    main ( ){float a,b,printf ("\n Enter any number");

    scanf ("\% f", &a );b = square (a)printf ("\n square of % f is % f", a,b);}square (float X){float y;Y = x * x;return (y);

    }

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    53/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    53

    Mob-8080373934

    the sample run of this program is Enter any number 2.5 square of 2.5 is 6.000000 Here 6 is not asquare of 2.5 this happened because any C function, by default, always returns an integer value.The following program segment illustrates how to make square ( ) capable of returning a floatvalue.

    main ( ){float square ( );float a, b;printf ("\n Enter any number ");scanf ("%f" &a);b = square (a);printf ("\n square of % f is % f, " a,b);}float square (float x){float y;y= x *x;

    return ( y);}

    sample run Enter any number 2.5 square of 2.5 is 6.2500000

    PASSING ARGUMENTS TO FUNCTION

    An argument is a piece of data (an into value, for exp) passed from a program to the function.Arguments allow a function to operate with different values, or even to do different things,depending on the requirements of the program calling it.

    PASSING CONSTANTS

    As an exp, lets suppose we decide that the starline ( ) function in the last exp is too rigid.Instead of a function that always prints 45 asterisks, we want a function that will print anycharacter any number of times

    Heres a program, TABLEARG, that incorporates just such a function. We use arguments topass the character to be printed and the number of times to print it .

    // tablearg. Cpp

    // demonstrates funciotn arguments# include < iostream>using namespace std;void repchar(char, int); //function declarationin main ( ){repchar(" " " , 43);cout

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    54/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    54

    Mob-8080373934

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    55/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    55

    Mob-8080373934

    int system dependant

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

    The calling program supplies arguments such as - and 43 ,to the function. The variables usedwithin the functions to hold the argument values are called parameters; in repchar() the are chand n.These decelerator names ch and n, are used in the functions as they were normal variables.Placing them in the decelerators is equivalent to defining them with the statements like

    Char ch;

    Int n;l

    When the function is called, its parameters are automatically initialized to the values passed by

    the calling program.

    PASSING VARIABLES

    In the tablearg example the arguments were constants - 43,and so on. Lets look at an examplewhere variables, instead of constants ,are passed as arguments. Thisprogram,VARARG,incorporates the same repchar()function as did tablearg,but let the userspecify the character and the number of times it should be repeated.

    //vararg.cpp//demonstrates variable arguments# include using namespace std;void repchar(char,int);

    int main(){char chin;int nin;coutnin;coutnin;repchar (chin,nin);return 0;

    }

    //"""""""""""""""""""""""""""//repchar ()//function definitionvoid repchar(char ch,int n){

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    56/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    56

    Mob-8080373934

    for(int j=0,j

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    57/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    57

    Mob-8080373934

    return kg;}

    When a function returns a value. The data type of this value must be specified. The functiondeclaration does this by placing the data types, float in this case, before the function name in thedeclaration and the definition. Functions in earlier program examples returned no value, so thereturn type was void. In the above function lbstokg() returns type float, so the declaration is

    Float lbstokg(float);

    The first float specifies the return type. The float in parentheses s specifies that an argument to bepassed to lbstokg() is also of type float.

    CALL BY VALUE

    In the preceding examples we have seen that whenever we called a function we have alwayspassed the values of variables to the called function. Such function calls are called calls byvalue by this what it meant is that on calling a function we are passing values of variables to it.

    The example of call by value are shown below ;

    sum = calsum (a, b, c); f = factr (a);

    In this method the value of each of the actual arguments in the calling function is copied intocorresponding formal arguments of the called function. With this method the changes made tothe formal arguments in the called function have no effect on the values of actual argument in thecalling function. The following program illustrates this:

    main ( )

    {int a = 10, b=20;swapy (a,b);printf ("\na = % d b = % d", a,b);}swapy (int x, int y){int t;t = x;x = y;y = t;printf ( "\n x = % d y = % d" , x, y);}

    The output of the above program would be; x = 20 y = 10 a =10 b =20

    CALL BY REFERENCE

    In the second method the addresses of actual arguments in the calling function are copied in toformal arguments of the called function. This means that using these addresses we would have an

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    58/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    58

    Mob-8080373934

    access to the actual arguments and hence we would be able to manipulate them the followingprogram illustrates this.

    main ( ){int a = 10, b =20,

    swapv (&a, &b);printf ("\n a = %d b= %d", a, b);}swapr (int **, int * y){int t;t = *x*x = *y;*y = t;}

    The output of the above program would be a = 20 b =10

    More on Function:

    In this C programming language tutorial we will talk some more about functions. We will take alook at command-line parameters and function prototypes.

    Command-line parameters

    In some cases you want to give a parameter at the start of a program.For example:

    # myprogram -i

    The program myprogram will start and something extra will be done because of the command-line parameter -i (What it will do is up to you, this is just an example).

    Now lets make a program that will print the words that are typed behind the program atexecution time. (Compile the program with the name myprogram).Here is the example:

    #include

    int main(int argc, char *argv[]){

    int x;

    printf("%d\n",argc);for (x=0; x < argc; x++)

    printf("%s\n",argv[x]);return 0;

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    59/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    59

    Mob-8080373934

    }

    After compiling the program myprogram start it as follows:

    # myprogram aa bb cc dd

    In this code, the main program accepts two parameters, argc and argv. The argv parameter is anarray of pointers to a string that contains the parameters entered when the program was invokedat command line. (Pointers will be explained in a later tutorial, for now it is enough to know thatit points to an address in memory where the parameters are stored). The argc integer contains acount of the number of parameters. (In this case four).

    First the program will print the number of parameters given when the program was invoked(stored in argc). This number will be used in a for loop. In this case it will print four times.

    The second printf statement will print the parameters given when the program was invoked, oneby one. Try it! Command-line parameters can be used for many things.

    Function prototypes

    A function prototype declares the function name, its parameters, and its return type to the rest ofthe program. This is done before a function is declared. (In most cases at the beginning of aprogram).To understand why function prototypes are useful, try the following program:

    #include

    void main(){

    printf("%d\n",Add(3)); /*

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    60/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    60

    Mob-8080373934

    To solve this problem you can make use of function prototypes. If you use prototypes, C checksthe types and count of the parameter list.

    Try the next example:

    #include

    int Add (int,int); /* function prototype for Add */

    void main(){

    printf("%d\n",add(3)); /*

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    61/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    61

    Mob-8080373934

    #include

    #include

    intfactorial(int);

    intfactorial (inti)

    {

    intf;

    if(i==1)

    return1;

    else

    f = i* factorial (i-1);

    returnf;

    }

    voidmain()

    {

    intx;

    clrscr();

    printf("Enter any number to calculate factorial :");

    scanf("%d",&x);

    printf("\nFactorial : %d", factorial (x));

    getch();

    }

    So from line no. 6 14is a user defined recursive function factorial that calculates factorial of any

    given number. This function accepts integer type argument/parameter and return integer value.

    Lets see how line no. 12 exactly works. Suppose value of i=5, since i is not equal to 1, thestatement:

    f = i* factorial (i-1);

    will be executed with i=5 i.e.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    62/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    62

    Mob-8080373934

    f = 5* factorial (5-1);

    will be evaluated. As you can see this statement again calls factorial function with value i-1which will return value:

    4*factorial(4-1);This recursive calling continues until value of i is equal to 1 and when i is equal to 1 it returns 1and execution of this function stops. We can review the series of recursive call as follow:

    f = 5* factorial (5-1);

    f = 5*4* factorial (4-1);

    f = 5*4*3* factorial (3-1);

    f = 5*4*3*2* factorial (2-1);

    f = 5*4*3*2*1;

    f = 120;

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    63/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    63

    Mob-8080373934

    7 Additional C Data Types

    7.1 Array:

    What is an Array in C Language?

    An array in C Programing Language can be defined as number of memory locations, each ofwhich can store the same data type and which can be references through the same variable name.

    An array is a collective name given to a group of similar quantities. These similar quantitiescould be percentage marks of 100 students, number of chairs in home, or salaries of 300employees or ages of 25 students. Thus an array is a collection of similar elements. These similarelements could be all integers or all floats or all characters etc. Usually, the array of characters iscalled a string, where as an array of integers or floats is called simply an array. All elements of

    any given array must be of the same type i.e we cant have an array of 10 numbers, of which 5are ints and 5 are floats.

    Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.

    Declaration of an Array

    Arrays must be declared before they can be used in the program. Standard array declaration is as

    type variable_name[lengthofarray];

    Here type specifies the variable type of the element which is going to be stored in the array. In Cprogrammin language we can declare the array of any basic standard type which C languagesupports. For example

    double height[10];float width[20];int min[9];char name[20];

    In C Language, arrays starts at position 0. The elements of the array occupy adjacent locations inmemory. C Language treats the name of the array as if it were a pointer to the first element Thisis important in understanding how to do arithmetic with arrays. Any item in the array can be

    accessed through its index, and it can be accesed any where from with in the program. So

    m=height[0];

    variable m will have the value of first item of array height.

    The program below will declare an array of five integers and print all the elements of the array.

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    64/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    64

    Mob-8080373934

    int myArray [5] = {1,2,3,4,5};/* To print all the elements of the arrayfor (int i=0;i

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    65/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    65

    Mob-8080373934

    /* The output of this program isoneWay:i = 0 vect[i] = 1i = 1 vect[i] = 2i = 2 vect[i] = 3i = 3 vect[i] = 4i = 4 vect[i] = 5i = 5 vect[i] = 6i = 6 vect[i] = 7i = 7 vect[i] = 8i = 8 vect[i] = 9i = 9 vect[i] = 0

    antherWay:i = 0 vect[i] = 1i = 1 vect[i] = 2i = 2 vect[i] = 3i = 3 vect[i] = 4i = 4 vect[i] = 5

    i = 5 vect[i] = 6i = 6 vect[i] = 7i = 7 vect[i] = 8i = 8 vect[i] = 9i = 9 vect[i] = 10*/

    Copy one array into another

    There is no such statement in C language which can directly copy an array into another array. Sowe have to copy each item seperately into another array.

    #include int main(){

    int iMarks[4];short newMarks[4];iMarks[0]=78;iMarks[1]=64;iMarks[2]=66;iMarks[3]=74;for(i=0; i

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    66/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    66

    Mob-8080373934

    Multidimensional Arrays

    In C Language one can have arrays of any dimensions. To understand the conceptof multidimensional arrays let us consider the following 4 X 5 matrix

    Row

    number (i)

    Column numbers (j)

    0 11 3 5 -9 -6

    1 5 6 -8 7 24

    2 -8 9 2 12 45

    3 10 13 -10 4 5

    Let us assume the name of matrix is x

    To access a particular element from the array we have to use two subscripts on for row number

    and other for column number the notation is of the form X [i] [j] where i stands for rowsubscripts and j stands for column subscripts. Thus X [0] [0] refers to 10, X [2] [1] refers to 16and so on In short multi dimensional arrays are defined more or less in the same manner as singledimensional arrays, except that for subscripts you require two squire two square brackets. Wewill restrict our decision to two dimensional arrays.

    Below given are some typical two-dimensional array definitions

    float table [50] [50];char line [24] [40];

    The first example defines tables as a floating point array having 50 rows and 50 columns. thenumber of elements will be 2500 (50 X50).

    The second declaration example establishes an array line of type character with 24 rows and 40columns. The number of elements will be (24 X 40) 1920 consider the following twodimensional array definition int values [3] [4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10. 11, 12, };

    Values [0] [0] = 1 Values [0] [1] = 2 Values [0] [2] = 3 Values [0] [3] = 4Values [1] [0] = 5 Values [1] [1] = 6 Values [1] [2] = 7 Values [1] [3] = 8Values [2] [0] = 9 Values [2] [1] = 10 Values [2] [2] = 11 Values [2] [3] =12

    Here the first subscript stands for the row number and second one for column number. Firstsubscript ranges from 0 to 2 and there are altogether 3 rows second one ranges from 0 to 3 andthere are altogether 4 columns.

    Alternatively the above definition can be defined and initialised as

    int values [3] [4] = {{

    1, 2, 3, 4

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    67/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    67

    Mob-8080373934

    }{

    5, 6, 7, 8}{

    9, 10, 11, 12}

    };

    Here the values in first pair of braces are initialised to elements of first row, the values of secondpair of inner braces are assigned to second row and so on. Note that outer pair of curly braces isrequired. If there are two few values within a pair of braces the remaining elements will beassigned as zeros.

    Here is a sample program that stores roll numbers and marks obtained by a student side by sidein matrix

    main ( )

    {int stud [4] [2];int i, j;for (i =0; i < =3; i ++){

    printf ("\n Enter roll no. and marks");scanf ("%d%d", &stud [i] [0], &stud [i] [1] );

    }for (i = 0; i < = 3; i ++)printf ("\n %d %d", stud [i] [0], stud [i] [1]);

    }

    The above example illustrates how a two dimensional array can be read and how the values

    stored in the array can be displayed on screen.

    7.2 Structures And Union:

    STRUCTURE

    A structure is a convenient tool for handling a group of logically related data items. Structurehelp to organize complex data is a more meaningful way. It is powerful concept that we mayafter need to use in our program Design. A structure is combination of different data types usingthe & operator, the beginning address of structure can be determined. This is variable is of type

    structure, then & variable represent the starting address of that variable.

    STRUCTURE DEFINITION

    A structure definition creates a format that may be used to declare structure variables considerthe following example.

    Struct book-bank

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    68/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    68

    Mob-8080373934

    {Char title [20];Char author [15];int pages;float price;};

    Here keyword Struct hold the details of four fields these fields are title, author, pages, and price,these fields are called structure elements. Each element may belong to different types of data.Here book-bank is the name of the structure and is called the structure tag. It simply describes asshown below.

    Struct book-bank

    Title array of 20 charecters

    Author array of 15 charecters

    Pages integer

    Price float

    The general format of a structure definition is as follows

    struct teg_name{data_type member 1;data_type member 2;- - - - - -- - - - - -- - - - - -}

    ARRAY OF STRUCTURES

    Each element of the array itself is a structure see the following example shown below. Here wewant to store data of 5 persons for this purpose, we would be required to use 5 different structurevariables, from sample1 to sample 5. To have 5 separate variable will be inconvenient.

    #include < stdio.h>main(){str uct person{char name [25];char age;};struct person sample[5];int index;char into[8];for( index = 0; index

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    69/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    69

    Mob-8080373934

    {print("Enter name;");gets(sample [index]. name);printf("%Age;");gets(info);sample [index]. age = atoi (info);}for (index = 0; index

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    70/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    70

    Mob-8080373934

    char department[10];str uct{int dearness;int hous_rent;int city;}allowance;}employee;

    The salary structure contains a member named allowance which itself is a structure with 3members. The members contained in the inner, structure namely dearness, hous_rent, and citycan be referred to as :

    employee allowance. dearnessemployee. allowance. hous_rentemployee. allowance. city

    An inner-most member in a nested structure can be accessed by chaining all the concerned.Structure variables (from outer-most to inner-most) with the member using dot operator. Thefollowing being invalid.

    employee. allowance (actual member is missing)employee. hous_rent (inner structure variable is missing)Passing a Structure as a whole to a Function

    UNIONS

    Unions, like structure contain members, whose individual data types may vary. These is majordistinction between them in terms of storage .In structures each member has its own storagelocation, where as all the members of a union use the same location. Like str uctures, a union canbe declared using the keyword union is follows:

    union item{int m;float x;char c;} code;

    This declares a variable code of type union them. The union contains them members, each with adifferent date type. However, we can use only one of them at a time. This is due to the fact thatonly one location is allocated for a union variable, irrespective of its size. The compiler allocatesa piece of storage that is large enough to hold the largest variable type in the union. In thedeclaration above, the member x requires 4 bytes which is the largest among the members. Theabove figure shown how all the three variables share the same address, this assumes that a floatvariable requires 4 bytes of storage. To access a union member, we can use the same syntax thatwe as for structure members, that is,

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    71/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    71

    Mob-8080373934

    code. mcode. xcode. c are all valid

    Member variables, we should make sure that we can accessing the member whose value is

    currently storage. For examplecode. m = 565;code. x = 783.65;printf(%d, code. m); would produce erroroneous output.

    # include main( ){union{int one;

    char two;} val;val. one = 300;printf(val. one = %d\n, val. one);printf(val. two = %d\n, val. two);}

    The format of union is similar to structure, with the only difference in the keyword used. Theabove example, we have 2 members int one and char two we have then initialised the member?one? to 300. Here we have initilised only one member of the union. Using two printfstatements, then we are displaying the individual members of the union val as:

    val. one = 300val. two = 44

    As we have not initialised the char variable two, the second printf statement will give a randomvalue of 44.

    7.3 Pointers:

    What Are Pointers?

    The simple variables are used to store the literal values. Whenever a variable is declared in a

    program it is having same memory location in the storage device. The memory location is calledaddress of that variable. Hence there are some values which do not hold the literal values butstores the address (memory address) of any other variable. Such variables are called pointers(The pointers in 'C' language increase the efficiency of program to a large extent. Efficiency ofprogram to a large extent. Although they are difficult to use but it is a very powerful tool. Whilemanaging the memory. Pointers are used for many reasons like :-

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    72/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    72

    Mob-8080373934

    Pointers reduce the length and complex city of program. They increase the processing speed. They save the memory to a very large extent. A pointer enables to access any variable whether it may be outside the function i.e. a

    direct control over a variable can be made using pointers.

    To declare a pointer you must put a * in front of its name. Here is an example of how to declare apointer to an integer and an untyped pointer:

    Code:int main(){

    int *p;void *up;return 0;

    }

    You can put the address of an integer into a pointer to an integer by using the & operator to getthe integer's address.

    Code:int main(){

    int i;int *p;i = 5;p = &i;return 0;

    }

    You can access the value of the integer that is being pointed to by dereferencing the pointer. The* is used to dereference a pointer. Changing the value pointed to by the integer will change thevalue of the integer.

    Code:int main(){

    int i,j;int *p;i = 5;p = &i;j = *p; //j = i

    *p = 7; //i = 7return 0;}

    How the pointers are initialized and define how variable can be accessed through pointer

    (Arithmetic)?

    The pointer variables are declare by using the pointer notation (astric,*). They are alsoassociated with a data type which will represent the type of data to which that particular pointer

  • 7/29/2019 Notes on C Programming Compiled by Atul Sir

    73/97

    Atul Sirs Private Tuition (Engg) Structured Programming (Sem II)

    73

    Mob-8080373934

    is pointing. Here pointer variable is different from simple variables in the sense that they cannotstore some literal value but will store the address of any particular memory location. Hence it thememory location has to be stored in the pointer variable then such process is called pointerinitialization.

    The pointer initialization when done then it should be kept in the mind that the pointer only thatmemory location on which the same data type item is stored to which the pointer variable canpoint.

    Example :-

    int main(){

    Int *a,b, *d;Float c, *e;A=&b;D=&c;C=&c;

    }

    The first statement will assign the address of 'b' variable memory location to the pointer 'a'pointer 'a' is pointing to an integer type memory location and 'b' is an integer variable.

    In second statement the pointer variable is invalid, since 'd' is an integer pointer and 'c' is a floattype variable. Hence integer type pointer cannot store the float type data address.

    The third statement is valid since a float type pointer is pointing to a float type variable.

    A Pointer type variable is generally used to access the value of the variable to which pointer is

    pointing. This can be done by using the indirection operation (*- content operator). When the * isplaced in front of a pointer, it will be result in the content of that variable to which it is pointing.But since the poin