COMP 172 SM

download COMP 172 SM

of 103

Transcript of COMP 172 SM

  • 7/30/2019 COMP 172 SM

    1/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 1

    COMP 172 3 (2+1)

    COMPUTER PROGAMMING AND DATA STRUCTURES

    Objective The importance of Computer Programming and Data Structures is well known in

    various engineering fields. The main objective of introducing this subject in the degree courseof Agricultural Engineering is to expose the student with fundamental knowledge on software

    of computers as specially to C Programming. It will also impart knowledge related to the

    Data Structures.

    Lecture Topic

    Theory

    1. Introduction to Software & Programming Languages

    2. Definitions, Properties, Differences of an Algorithm and Flowcharts3. Flowchart symbols & Advantages and disadvantages of Flowcharts & Algorithms4. Introduction & Fundamentals of C5. Steps in learning C (Character set, Identifiers, Keywords)6. Steps in learning C (Data types)7. Steps in learning C (Constants)8. Steps in learning C (Variables, Escape sequences)9. Steps in learning C (Operators)10. Steps in learning C (Statements)11. Steps in learning C (Header Files, Input & Output functions: Formatted I/O -

    functions Unformatted I/O functions)12. Basic Structure of a simple C program13. Decision Making/Control Statements

    14. Branching, Concept of Looping/The looping statements15. Concept of Arrays & Types of Arrays16. Types of functions (Library functions & User defined functions)17. Concept of Functions (Defining a function & Function Prototypes)18. Concept of a String Library Functions19. Concept of Pointers20. Concept of Structures21. Concept of Unions22. Introduction to a Data Structures23. Types of Data Structures (Primary & Secondary Data Structures)24. Concept of a Linked Lists & Types of a Linked Lists25. Basic operations of a Linked Lists26. Concept of Stacks & Operations on Stacks (PUSH & POP Operations)

    27. Evaluation of arithmetic expressions (Notations: Prefix, Infix, Postfix)28. Conversion of Notations29. Converting infix notation to postfix notation30. Evaluating an expression in postfix notation31. Concept of queues & types of queues32. Operations on a queue (ENQUEUE & DEQUEUE Operations)

    Practical

    1. Introduction to a C complier & How to handle the C compiler(Keys used in C Compiler)

    2. Building an executable version of a C program

    (Basic Structure of a simple C program)

    3. Developing and executing simple C programs

  • 7/30/2019 COMP 172 SM

    2/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 2

    (Ex: Arithmetic operation on numbers and etc.,)4. Developing and executing simple C programs

    (By using some mathematical & logical operations)

    5. Developing and executing simple C programs(By using Control statements: if, if-else, multiple if-else)

    6. Developing and executing simple C programs(By using Control statements: nested if-else, conditional operators)

    7. Developing and executing simple C programs(By using goto, continue and switch statements)

    8. Developing and executing simple C programs(By using loops: while, do while loops)

    9. Developing and executing simple C programs(By using loops: for loop)

    10. Developing and executing simple C programs(By using arrays: single/one dimensional arrays)

    11. Developing and executing simple C programs(By using arrays: double (or) two dimensional arrays)

    12. Developing and executing simple C programs(By using a string functions: strlen( ), strrev( ), strcpy( ))

    13. Developing and executing simple C programs(By using a string functions: strcat( ), strlwr( ), strupr( ))

    14. Developing and executing simple C programs(By using user defined functions, pointers, structures, unions)

    15. Developing and executing C programs(By using Linked lists & operations: Insertion & Deletion of a nodes

    to and from a linked lists respectively)

    16. Developing and executing C programs(By using Stack & operations: PUSH & POP)

    &(By using Queues & operations: ENQUEUE & DEQUEUE)

    Text books:

    1. Computer Programming in C E. Balaguruswamy

    2. Data Structures Mark Allen Waise

    Reference Books:

    1. Let us C Yeswanth Kanethkar

    2. C & Data Structures P.Sudarsan, J.John Manoj Kumar

    3. C Programming & Data Structures A.P. Godse, D.A. Godse

    LECTURE 1:

  • 7/30/2019 COMP 172 SM

    3/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 3

    INTRODUCTION TO SOFTWARE & PROGRAMMING LANGUAGES

    *Software*

    Software is the collection of programs to perform specific task.

    The Softwares are categorized into three types, they are:

    1. System Software2. Application Software3. Firmware(ROM-BIOS)

    1. System Software :-

    The system software is also known as the "Operating System(OS)" It is also known as"Basic Software" of PC.

    It acts as an interface between user and the system peripherals, user, application program

    and hardware.

    The primary goal of OS is thus to make done computer system easy to use and secondarygoal is hardware resource management.

    The user interact with the computer and software through the OS.

    The OS is the first software loaded when a computer boots up.

    All computers have an OS that is used for starting the computer and running otherprograms (Application Programs) .

    Os perform important task like receiving input from the keyboard, mouse and sending

    information to the screen, keeping track of files and take appropriate action.

    Ex:Windows 95,98.Windows XP 2000 ProfessionalWindows XP 2002 Professional (Service Pack2),Windows XP 2007 Professional.etc.,

    Types of Operating Systems:-

    The operating system is a collection of programs used to operate a computer system.

    It takes the responsibility of computers' overall operation and supervision.

    In that way, it coordinates among various devices and programs, and provides aninterface between a programmer and the computer system.

    OS is popularly used term for the abbreviation of the operating system.

    DOS became the most widely used microcomputer operating system.

    Today, DOS has been replaced on many computers by more powerful operatingsystems such as Windows, UNIX, Windows NT, and OS/2.

    These more powerful operating systems make it possible to run tasks on lessexpensive microcomputers that were once performed on expensive mainframe and

    minicomputers.

  • 7/30/2019 COMP 172 SM

    4/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 4

    Operating Systems are broadly classified, according to number of users itsupports, into two categories:

    Single User Operating Systems

    Multi User Operating Systems

    Only one user can work at a time on a computer system with a single user operatingsystem.

    More than one user can work at a time on a computer system with a multi user operatingsystem.

    The following are lists of some popular operating systems:-

    Single User Operating Systems:-

    OS/2

    MS DOS

    WINDOWS 95

    WINDOWS 98 WINDOWS XP & 2000 Versions

    Multi User Operating Systems:-

    UNIX

    LINEX

    WINDOWS NT

    Features of Operating System:-

    It controls overall operations of a computer. It coordinates among various devices and programs. It makes computer machines to work with users.

    It executes programs, allocates memory space, and schedules jobs. It provides users an interface to computing resources. It prevents interference between different users in a multi-user system. It takes users' commands and responds to them suitably. It deals with any faults that may occur in the computer.

    2. Application Software :-

    Application software is the software designed for the specific purposes to accomplish thespecific task.

    Application softwares are written by users.

    The operating system provide a set of services for the applications running on yourcomputer, and it also provide the fundamental user interface' for your computer.

    3. Firmware:-

    Firmware is one of the most common users of flash memory is for the basic input outputsystem of your computer, commonly known as the "BIOS"(Bye-Ose).

    ROM-BIOS is a set of programs built in to the computer that perform the most basic, low-level and intimate control supervision operation for the computer.

    The basic purpose of ROM-BIOS is to take care of the immediate needs of the computer's

    hardware and to isolate all other programs from the details of how the hardware works.

  • 7/30/2019 COMP 172 SM

    5/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 5

    BIOS is the partly software and partly hardware.

    It is bridge between computer hardware and software The following are some of the functions of BIOS:

    It boots the computer

    It validates the pc's configuration.

    It provides interaction between hardware of the pc and its software.

    *Programming languages*

    Programming Language:-

    Language is a sequential arrangement of set ofInstructions to perform a Several tasks.

    Computer languages can be divided into two groups:

    High-Level Languages

    Low-Level Languages

    The following figure shows the levels of the Computer Languages :

    High-Level Languages:-

    High-level languages are designed to be easier to use, more abstract, and more portablethan low-level languages.

    The lowest-level programming language machine languages are the only languagesunderstood by computers.

    While easily understood by computers, machine languages are almost impossible forhumans to use because they consist entirely of numbers.

    Programmers, therefore, use either a high-level programming language or an assemblylanguage.

  • 7/30/2019 COMP 172 SM

    6/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 6

    Ultimately, programs written in a high-level language must be translated into machinelanguage by a CompilerorInterpreter.

    A vocabulary and set of grammatical rules for instructing a computer to perform specifictasks. The termprogramming language usually refers to high-level languages, such as

    BASIC, C, C++, COBOL, FORTRAN, Ada, and Pascal.

    Each language has a unique set of keywords (words that it understands) and a specialsyntax for organizing program instructions.

    The main advantage of high-level languages over low-level languages is that they areeasier to read, write, and maintain.

    Low-level Languages:-

    There are two different category of languages are to be contained in the lowest levellanguages, they are:

    i. Assembly Languagesii. Machine Languages

    i. Assembly Languages :

    Lying between machine languages and high-level languages are languages calledAssembly Languages.

    Assembly languages are similar to machine languages, but they are much easier toprogram in because they allow a programmer to substitute names for numbers.Machine languages consist of numbers only.

    An assembly language contains the same instructions as a machine language, but theinstructions and variables have names instead of being just numbers.

    Assembly language programs are translated into machine language by a programcalled an Assembler.

    ii. Machine Languages :-

    High-level programming languages, while simple compared to human languages, aremore complex than the languages the computer actually understands, calledMachine Languages.

    Each different type of CPU has its own unique machine language.

    Every CPU has its own unique machine language.

    Programs must be rewritten or recompiled, therefore, to run on different types ofcomputers.

    A programming language that is once removed from a computer's machine language.

    Machine languages consist entirely of numbers and are almost impossible for humansto read and write.

  • 7/30/2019 COMP 172 SM

    7/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 7

    LECTURE 2:

    DEFINITIONS, PROPERTIES, DIFFERENCES OF AN ALGORITHM & FLOWCHARTS

    *Algorithm & Flowchart*

    Algorithm is a tool that represents program logic sequence in simple steps and in the languageeasily understandable by us.

    Algorithms are supported by a graphical tool called Flowchart.

    Flowchart is a tool that can help us to develop and represent graphically program logicsequence. It will also enable us to trace and detect any logical or other errors before the programsare written.

    Before you start coding a program it is necessary to plan the step by step solution to the task yourprogram will carry out. Such a plan can be symbolically developed using a diagram. This diagramis then called a Flowchart.

    Algorithm:-

    An algorithm is a step-by-step problem solving procedure that can be carried out by acomputer.

    The essential properties of an algorithm are:-

    It should be simple. It should be clear with no ambiguity.

    It should lead to a unique solution of the problem.

    It should involve a finite number of steps to arrive at a solution.

    It should have the capability to handle some unexpected situations which may

    arise during the solution of a problem. Advantages:-

    It is a step by step solution to a given problem which is very easy to understand.

    It has got a definite procedure which can be exacted within a set period of time.

    It is easy to first develop an algorithm, then convert it into a flowchart and then into acomputer program.

    It has got a beginning and an end within which there are definite procedures toproduce outputs within a specified period of time.

    It is easy to debug as every step has got its own logical sequence.

    It is independent of programming languages.

    Disadvantages:-

    It is time consuming and cumbersome as an algorithm is developed first which is

    converted into flow chart and then into a computer program.

  • 7/30/2019 COMP 172 SM

    8/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 8

    Flowchart:-

    Computer professionals use two types of flowcharts, Flowcharts used by computerprofessionals are:

    Program Flowcharts

    System Flowcharts

    Program Flowcharts:-

    These are used by programmers.

    A program flowchart shows the program structure, logic flow and operationsperformed. It also forms an important part of the documentation of the system.

    It broadly includes the following :-

    Program Structure

    Program Logic

    Data Inputs at various stages

    Data Processing

    Computations and Calculations

    Conditions on which decisions are based

    Branching & Looping Sequences

    Various Outputs

    System Flowcharts:-

    System Flowcharts are used by system analyst to show various processes, subsystems, outputs and operations on data in a system.

    Use of flowcharts offers the following advantages as mentioned below:

    Developing the program logic and sequence.

    A pictorial method of communicating your ideas to others.

    The operation that will be executed at each step.

    It shows the execution of logical steps without the syntax andlanguage complexities of a program.

    You can walk through your program with sample data to get the exactidea about the result of each step.

    Compare the results obtained from the algorithm, flowchart with theexpected result. Rectify any inconsistency.

    To get logical consistency.

    Select best option from various ways of solving the problem. This canbe used to reduce the program size.

    Simplify trouble shooting and tracing of logical errors.

    Assist in documentation of the program.

  • 7/30/2019 COMP 172 SM

    9/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 9

    LECTURE 3:

    FLOWCHART SYMBOLS, ADVANTAGES & DISADVANTAGES OFFLOWCHARTS & ALGORITHMS

    *Flowchart Symbols*

    A large number of programmers use flowcharts to assist them in the development ofcomputer programs.

    Flowcharts has many standard symbols.

    In using the symbols following points have to be kept in mind :

    All flowcharts must have a start and stop terminator.

    All shapes must be aligned horizontally and vertically.

    The arrows drawn must touch the shapes.

    In case of decision shape, the yes and no branches must be clearly labeled.

    The flowchart must have a title stating what the flowchart will do.

    Symbols must contain the necessary information to execute the step (or) Thedetails inside the symbol must be clearly legible.

    In case of predefined process, the symbol must contain the name of the

    process.

    The shape of the symbol is important and must not be changed.

    The size can be changed as required.

    The flow lines must not cross each other.

    Following are various Symbols Used to Draw a Flow Charts:-

    Symbol Symbol Name Meaning

    Terminator A flowchart should alwaysbegin and end with thissymbol.

    Process This symbol is used to indicatea process.

    Decision Each decision that is made isrepresented with this symbol.The flow comes from the topand the various possibleoutcomes come out of thethree other points of thediamond.

  • 7/30/2019 COMP 172 SM

    10/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 10

    Input/Output This symbol representsinformation entering (or)leaving a process. This is usedto indicate input from theterminal(from the user)/ outputto the terminal display(to the

    user).

    Symbol Symbol Name Meaning

    On-Page Connector. This symbol used to connectmultiple lines of the flow charttogether to other related.

    Off-Page Connector This symbol used when youwant to continue the flow chartin another page.

    Sequence (or) DirectionLines

    The arrow denotes direction ofthe flow of the sequence ofevents that occur.

    Differences Between Algorithm & Flowchart :-

    S.NO ALGORITHM FLOWCHART

    1. An algorithm is the finite of step-by-stepinstructions that solve a program. A flow chart is a diagrammaticrepresentation or pictorial representationof the algorithm or of the plan of solutionof a problem.

    2. Algorithm gives verbal representationwhich is almost similar to Englishlanguage. Suitable for large andmodular programs.

    Gives pictorial representation.Suitable for small programs.

    3. Easier to understand To understand flowchart one has to befamiliar wit symbols.

    4. Drawing tools are not required Required.

    5. Algorithm can be typed so reproductionis easy.

    Flowcharts cannot be typed. Soreproduction is a problem

  • 7/30/2019 COMP 172 SM

    11/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 11

    LECTURE 4:

    INTRODUCTION & FUNDAENTALS OF C*Introduction to C*

    C is a general purpose structured programming language developed at Bell laboratories in

    1972.

    It was designed and written by a system programmer named Dennis Ritchie.

    C was powerful programming language, which is attracting considerable attention worldwide

    because it is reliable, simply, easy to use, and highly portable(i.e., a program written in C can

    be transferred easily from one computer to another computer).

    Applications of C :-

    C language is used for developing database systems, graphics packages,

    spread sheets, CAD/CAM applications, word processors, office automation,

    scientific and engineering applications.

    Learning C is easier than any other programming language.

    The following are steps in learning C:-

  • 7/30/2019 COMP 172 SM

    12/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 12

    LECTURE 5:

    STEPS IN LEARNING C (CHARACTER SET, IDENTIFIERS, KEYWORDS)

    *Steps in Learning C*

    Character Set:-

    A character set denotes an alphabet, digit, (or) special characters can be combined to form

    variables.

    C uses constants, variables, operators, keywords, and expressions as building block to form a

    basic C program.

    Valid characters used in C programming are as follows:

    Alphabets:

    Lower case: a b c . . . . . . x y z

    Upper case: A B C . . . . . . X Y Z

    Digits:

    0 1 2 . . . . . . 8 9 10

    Special Characters:

    + plus sign minus sign _ underscore/ slash ! exclamation mark # number sign< less than > greater than = equal to? question mark % percent sign single quotation double quotation ; semicolon , comma{ left flower brace } right flower brace [ left bracket] right bracket ( left parenthesis ) right parenthesis& ampersand | vertical bar * asterisk. dot operator back slash

    Tokens:-

    Tokens are the smallest individual unit in a program.

    Tokens supported in C are as follows:

    Identifiers

    Keywords

    Constants

    String literals

  • 7/30/2019 COMP 172 SM

    13/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 13

    Operators

    Identifier:-

    A C program is usually written with these tokens, as per syntax of the C language.

    An identifier is a string of alphanumeric characters that begins with an alphabeticcharacter (or) an under score character that are used to identify (or) name

    various programming elements such as:

    variables, function names, array names, tags and members of

    structures, unions, typedef names , enumeration constants and so on

    An underscore character is considered as a letter in identifiers and it is

    usually used in the middle of an identifier.

    Rules for constructing identifiers:-

    The first character in an identifier must be an alphabet (or) an underscore and can befollowed by any alphabets (or) digits or under scores.

    No commas (or) blank spaces are allowed within an identifier.

    No special character other than the underscore can be used to represent identifiers.

    The name used to represent an identifier should not be a keyword.

    Identifiers are case sensitive.

    Identifiers can be of any length, but first 31 characters are recognized.

    Valid examples of identifiers:-

    ChennaI PRIYA FLOAT average_value SuChiTraKUMARA _raja One_And_Only mark_1

    Invalid examples of identifiers :-

    786 (sum) 100th cost$ [Rupa] FIVE STARVanitha float

    Keywords:-

    Keywords are also referred, as reserved words(predefined words) are words

    whose meaning has been already defined in C compiler.

    All keywords have fixed meanings and their meanings cannot be changed.

    Keywords are used for their intended purpose and they cannot be used as identifiers.

    All keywords must be compulsorily written in lowercase.

    The followings are keywords used in C :-

    auto double int struct

  • 7/30/2019 COMP 172 SM

    14/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 14

    break else long switchcase enum register typedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeof volatile

    do if static while

    LECTURE 6:

    STEPS IN LEARNING C (DATA TYPES)*Steps in Learning C*

    Data Types:-

    The data types supported in a language dictates the type of values, which can be processed bythe programming language.

    C language is rich in its data types.

    It supported wide variety of data types each of which may be represented differently with incomputer's memory, which allows the programmer to select the appropriate type to the needs ofthe application.

    Data types in C can be broadly classified as three types, they are

    1. Primary data types

    2. User-defined data types

    3. Empty data type.

    All C compilers supports four primary data types namely,

    Character data type represented as char

  • 7/30/2019 COMP 172 SM

    15/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 15

    Integer data type represented as int

    Floating-point data type represented as float

    Double-precision floating-point data type represented as double.

    1. Primary Data types:-

    Data type Size (bytes) Range

    char 1 -128 to 127

    int 2 -32768 to 32767float 4 3.4e-38 to 3.4e+38

    double 8 1.7e-308 to 1.76+308long double 10 3.4 e-4932 to 1.1e 4932

    Integer Data Types:-

    C deals with several kinds of numbers. Whole numbers, which are used

    frequently, are referred as integers.

    It occupies two bytes for their storage.

    In order to have control over the range of numbers and storage space in memoryshort int, int, long int in both signed and unsigned forms are used.

    The long int data type represents large integer values and requires double the

    amount of storage as regular integer data type.

    The unsigned long int data type represents large integer values that are used to

    store large range of values than long int data type.

    Data Type Size(bytes) Range

    short int (or) signed short int 2 -32,768 to 32,767int (or) signed int 2 32,768 to 32,767

    unsigned short int 2 0 to 65,535unsigned int 2 0 to 65,535long int (or) signed long int 4 -2,147,483,648 to 2,147,483,647unsigned long int 4 0 to 4,294,967,295

    Floating Point Data Types:-

    C deals several kinds of numbers.

    Real numbers, which are used frequently, are called as floating-point numbers.

    The float data type is used to store a floating point number.

    Floating point data types store numerical values with s fractional portion.

  • 7/30/2019 COMP 172 SM

    16/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 16

    They usually occupy 4 bytes of memory for their storage. These are known as

    single precision numbers.

    When the range provided by a float data type is not sufficient, double data type is

    used.

    The double data type represents the same data type, that float represents butwith a greater precision hence it requires 8 bytes of memory for their storage in

    the memory. These are known as double precision numbers.

    To increase the precision further we can use long double which uses 10 bytes of

    memory for their storage. These are known as extended precision numbers.

    Character Data types:-

    Character data type is used to represents individual characters.

    The char data type generally requires one byte of memory for their storage.

    In order to have control over the range of characters and storage space in

    memory, signed and unsigned char data type are used.

    Data type Size (bytes) Range

    char (or) signed char 1 -128 to 127unsigned char 1 0 to 255

    2. User Defined Data types :-

    C supports a feature known as type definition that allows the user to define new data

    types that are equivalent to existing data types.

    The user-defined data type identifier can later be used to declare variables.

    There are two types of user defined data types are used in C:

    Type Definition

    Enumerated Data Type

    Type Definition:-

    The keyword typedefis used to define new data type names.

    Note that you are not actually creating a new data type, but rather defining a

    new name for an existing data type.

    The general form (or) syntax of the defining a new data type is :

    typedef data type identifier;Where identifier refers to new name(s) given to the data type.

    They can later used to declare variables as

    age child, adult;average mark1,mark2;string name[20];

  • 7/30/2019 COMP 172 SM

    17/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 17

    Where

    child and adult are declared as integer variables/identfiers,

    mark1 and mark2 are declared as floating-point variables/identifiers,

    name is declared as character array variable/identifier.

    typedefcan also be used to define structures.

    The main advantage of type definition is that, you can create meaningful

    data type names for increasing the readability of the program.

    They also suggest the purpose of the data type names used in the

    program.

    Examples of type definition are:

    typedef int age;typedef float average;typedef char string;

    Where

    age symbolize int,

    average symbolize float and

    string symbolize char.

    Enumerated Data Type:-

    The enumerated data type gives an opportunity to invert your own data type

    with a set of named integers constants represented by identifiers that

    specifies all valid values a variables of that type may have.

    They can be used in any expression where integer constants are valid.

    The general form (or) syntax of Enumerated Data Type is:

    enum identifier {enumeration _list} list_of_variables;

    Where

    enum is a keyword, which is used to specify the enumerated data

    type which can be used to declare the enumeration _list also

    referred as enumeration constants.

    Ex:enum month{JAN,FEB,. . . . . . . . NOV,DEC};

    Where

    New data type month in which the enumeration _list is

    JAN,...,DEC.

    The values for the enumeration _list are set automatically tointegers 0 to 11.

  • 7/30/2019 COMP 172 SM

    18/103

  • 7/30/2019 COMP 172 SM

    19/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 19

    Ex: -43

    Integer constants can be specified in three ways. They are,

    Decimal integer constant

    Octal integer constant

    Hexadecimal integer constant

    Ex:

    The value 35, can be written in any of the three ways as,

    35 representing a decimal constant

    043 representing a octal constant

    0x23 representing a Hexadecimal constant

    The leading 0(zero) to an integer constant specifies, that it is an

    octal integer constant.

    It can containing digits from 0 to 7.

    The leading 0x (or) 0X to an integer constant specifies, that it is a

    hexadecimal constant.

    It can contain digits from 0 to 9 and letters a to f(or) A to F.

    Rules for constructing integer constants :-

    An integer constant may be positive or negative(default sign is positive).

    An integer constant should not have a decimal point.

    No commas and blank spaces are allowed in an integer constant.

    An integer constant, should not use exponent e.

    Real Constants:-

    Real Constants are often called as floating-point constants.

    They can be written in two forms. They are:

    Fractional form

    Exponential form

    Fractional form:-

  • 7/30/2019 COMP 172 SM

    20/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 20

    Fractional part consists of a series of digits representing the whole part of the

    numbers, followed by a decimal point, followed by a series of digits

    representing the fractional part.

    Rules for constructing real constants(fractional form) :-

    A real constant may be positive (or) negative (default sign is positive).

    A real constant must have a decimal point.

    No commas and blank spaces are allowed in a real constant.

    Exponential Form:-

    Exponential form of representation of real constant is usually used if the

    value of a constant is either too small (or) too large. In this representation, the real constant is represented in two parts.

    The part appearing before e is called mantissa, where as the partfollowing e is called exponent.

    The exponent consists of an optional plus (or) minus sign followed by aseries of digits.

    Ex:343x10-6 is represented in exponential form as 343e-6.

    Rules for constructing real constants(Exponential form) :-

    The mantissa part and the exponential part should be separated by a lettere.

    The mantissa part and the exponential part may be positive (or)negative(default sign is positive)

    The mantissa and exponent part must have at least one digit.

    No commas and blank spaces are allowed in a real constant.

    2. Character Constant :-

    Single Character Constants:-

    A Single Character Constant (or) Character Constant contains a single character

    enclosed within a pair of single quotes.

    A Single Character Constant must be either a single alphabet (or) a single special

    character enclosed in single quotes.

    The length of the Single Character Constant is only one.

    Ex: A k 4 * _

    String Constant:-

    A character string, a string constant (or) literal consists a sequence of charactersenclosed within in a double quotes.

    A string constant may consists of any combination of digits, letters, escapesequences, and spaces.

  • 7/30/2019 COMP 172 SM

    21/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 21

    The end of the string is marked with a single character called as the NULL character\0.

    It occupies two bytes of size for their storage capacity.

    Ex: Kumar Ag.B.Tech 434 etc.;

    Rules for Constructing string constants:-

    A string constant may be a single alphabet (or) a digit, (or) a special

    character (or) sequence of alphabets (or) digits enclosed in double

    quotes.

    Every string constant ends up with a NULL character, which is

    automatically assigned.

    LECTURE 8:

    STEPS IN LEARNING C (VARIABLES, ESCAPE SEQUENCES)

    *Steps in Learning C*

    Variables:-

    A quantity which may vary during program execution, is as a variable.

    Variable name is a arbitrary name, an identifier used to refer to the area of memory in which a

    particular value is stored.

    These memory locations can contain an integer, real, single character, (or) a string constant.

    Declaration of Variables:-

    A data item must be assigned to a variable at some point in the program.

    The information represented by the variable can change during execution of the program, butdata type associated with the variable cannot change.

    A variable name used by the programmer can be in a meaningful way to reflect its use (or)function (or) nature in the program.

    All variables used in the program must be declared before all executable statements(i.e.; atthe start of each function after the opening flower braces ( { ) of the program.

    Declaration of variable begins with its type followed by one (or) more variable names.

    Declaration assigns the variable to a specific data type and there by allocate memory to thevariable depending upon the data type.

    Ex:int a1,a2,a3;char c1,c2,c3;float x1;x2;x3;

    In the first declaration, a1,a2,a3 are variables declared as typeinteger.

    In the next declaration c1,c2,c3 are variables declared as typecharacter.

    In the next declaration x1,x2,x3 are variables declared as typefloating-point variables.

  • 7/30/2019 COMP 172 SM

    22/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 22

    Initialization of Variables:-

    Variables can also be initialized when they are declared.

    This is done by adding an equal sign followed by the required value to be initialized after thedeclaration.

    Ex:

    int a=6, b=8;

    char c1=kumar;

    float x1=434.4;

    The first declaration declares two variables a and b of type integer and

    their by initializing the variables with the values 6 and 8 respectively.

    Types of variable:-

    Constant Variables:-

    The keyword const is used for this purpose.

    It protects variables from modification during execution of a program.

    Ex:const int x= 34;const float y=234;

    In the first declaration, x is a variable declared as type integer.

    In the next declaration, y is a variable declared as type floating-

    point.

    The keyword const is used for this purpose.

    It protects variables from modification during execution of a program.

    Volatile Variables:-

    The variables that can be changed at any time by a function in which it is present

    (or) by any other function in the same program are called as volatile variables.

    The volatile is used for this purpose.

    Ex: volatile int z=5000;

    If the value of a variable in the current function is to be

    maintained constant and desired not to be changed by any other

    external function, then the variable should be declared as:

    volatile const int z=5000;

    Escape Sequences :-

    Certain constants are non printable, which means that they are not displayed on the screen (or) in

    the printer, called as escape sequences.

    C supports certain escape sequences(backslash character constants) that are used in output

    statements.

  • 7/30/2019 COMP 172 SM

    23/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 23

    Although they consist of two characters, they represent only one character.

    Ex:\0 -- null \b blank space \t horizontal tab \n new line

    LECTURE 9:

    STEPS IN LEARNING C (OPERATRS)

    *Steps in Learning C*

    Operators:-

    An Operator is a symbol (or) a special character that tells the computer to perform certain

    mathematical (or) logical operations, which is applied to operands to give a result.

    Operators are used in programs to manipulate data and variables.

    The data items that operators act upon to evaluate expressions are called as Operands.

    The Operators are used in C are:

    1. Arithmetic Operators 6. Logical Operators

    2. Unary Operators 7. Bitwise Operators

    &

    Increment and Decrement Operators 8. Conditional Operator

    3. Relational Operators 9. Assignment Operators

    4. Equality Operators 10. Special Operators

    1. Arithmetic Operators :-

    C language has all the basic arithmetic operators.

    following table shows the various arithmetic operators and their meaning:

    Operator Meaning

    + Addition- Subtraction* Multiplication/ Division

    % Modulo operation(remainder after integer division)

    2. Unary Operators :-

  • 7/30/2019 COMP 172 SM

    24/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 24

    The operator that act upon a single operand to produce a new value are called as unary

    operators.

    Unary operators are written after their operands.

    The following table shows the various unary operators and their meaning:

    Operator Meaning

    - Unary minus

    ++(increment operator) Increment by 1

    -- (decrement operator) Decrement by 1

    sizeof Returns the size of the operand.

    Unary minus:-

    The most common unary operation is the unary minus, which is distinctively different

    from the arithmetic operator, which denotes subtraction.

    The subtraction operation requires two operands, where as the unary operation, with

    unary minus requires only one operand.

    The unary minus is used to indicate (or) change the algebraic sign of a value.

    sizeof operator:-

    The sizeofoperator is not a library function but a keyword, which returns the size of

    the operand in bytes.

    The sizeof operand always precedes its operand.

    The following are various expressions and results of sizeof operator:

    Expression Result

    sizeof(char) 1

    sizeof(int) 2

    sizeof(float) 4

    sizeof(double) 8

    3. Relational Operators :-

    Relational operators are symbols that are used to test the relationship b/w two variables

    (or) b/w variables and constant.

    This operators are used for checking conditions in control statements.

    The following table shows the various relational operators and their meaning:

    Operator Meaning

    < less than

    > greater than

  • 7/30/2019 COMP 172 SM

    25/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 25

    >= greater than or equal to

    4. Equality Operator :-

    Closely associated with the relational operators are two equality operators.

    The following table shows the equality operators and their meaning:

    Operator Meaning

    == equal to

    != not equal to

    5. Logical Operator :-

    In addition to arithmetic and relational operators, C has three logical operators for

    combining logical values and creating new logical values.

    The following table shows the various logical operators and their meaning:

    The result of the logical AND operation will be true, if the both operands are true.

    The result of the logical OR operation will be true if either of the operand is true

    or both the operands are true.

    The logical NOT operator simply reverses the value of the expression thatfollows it(i.e; true becomes false and false becomes true).

    Ex: The various expressions when x=9,y=5,z=a and their results are:

    Expression Result Value

    (x>=5) && (z==a) True 1

    (x>=6) || (z==a) True 1

    (x>=15) || (z==b) False 0

    (x>8) True 1

    !(x>8) False 0

    Operator Meaning

    ! NOT

    && Logical AND

    || Logical OR

  • 7/30/2019 COMP 172 SM

    26/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 26

    6. Bitwise Operator :-

    The bitwise operators are the bit manipulation operators.

    They can manipulate individual bits within the piece of data.

    These operators can operate on integers and characters but not on floating pointnumbers having double data types.

    The following table shows the various bitwise operators and their meaning:

    7. Conditional Operator :-

    An expression that evaluates conditions is called as conditional expressions.

    The operator used to evaluate conditional expression is called as a conditional operator

    denoted by (?:).

    It is also referred to as ternary operator, since it takes three operands as its

    arguments.

    The general form or the syntax of the conditional operator is:

    expr1 ? expr2 : expr3;

    When evaluating a conditional expression, expr1 is evaluated first.

    If expr1 is true,expr2 is alone evaluated.

    If expr1 is false,expr3 is alone evaluated.

    Ex:

    a= ((b bitwise shift right operator

  • 7/30/2019 COMP 172 SM

    27/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 27

    If b is lesser than 2, the value of a will be 8.

    If b is grater than 2, then the value of a will be 6.

    8. Assignment Operators :-

    Assignment operators are used to assign the result of an expression to a variable.

    The equal(=) is an assignment operator.

    It is used to form a assignment expressions, which assigns the value of an expression to

    an identifier, which may be written in the form of

    Identifier=expression;Where

    identifier generally represents a variable and expression represents a

    constant (or) a variable (or) complex expression.

    In addition, C has a set of shorthand assignment operators of the form:

    Identifier=expression;

    The following table shows the various assignment operators and their meaning:

    9. Special Operators :-

    Some of the special operators used in C are listed below.

    These operators are referred as separators.

    Ampersand(&)

    Comma(,)

    Asterisk(*)

    Hash(#)

    Operator Meaning

    += Assign sum

    -= Assign sub

    *= Assign product

    /= Assign quotient

    %= Assign reminder

  • 7/30/2019 COMP 172 SM

    28/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 28

    Braces({ })

    Parenthesis(( ))

    Colon(:) and Semicolon(;) etc..,

    LECTURE 10:

    STEPS IN LEARNING C (STATEMENTS)

    *Steps in Learning C*

    Statements:-

    A statements in a program carries out some specific action.

    Statements used in C are classified as three types, they are

  • 7/30/2019 COMP 172 SM

    29/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 29

    1. Expression Statements

    2. Compound Statements

    3. Conditional Statements

    1. Expression Statements :-

    An expression is a combination of constants, variables, operators, and function calls

    written in any form as per syntax of the C language.

    The value produced by these expression can be stored in variables and used as

    apart for evaluating larger expressions.

    An expression statement consists of valid C expressions, ending with a semicolon.

    Variable = expression;

    The expression refers to a constant value (or) an arithmetic expression (or) a function

    which assigns a value to the variable.

    Ex:age=21;

    result=pow(2,4);

    area_of_circle=3.14*r*r;

    2. Compound Statements :-

    A group of valid C expression statements placed within an opening flower brace {

    and a closing flower brace } is referred as a compound statement.

    Ex:{

    x=(a+(b-c)*c);y=(a-b+d);z=(a*b-c)/d;

    }

    A compound statement can also have another compound statement, (or) a

    control statement in it.

    3. Control Statements :-

    The statements, that we have seen so far, are normally executed as they appear in

    the program.

    By default, the statements in the program are executed sequentially.

    However, in practice we have situations where we have to change the order of

    execution of statements until the some specified conditions are met.

    The control statements alter the execution of statements depending upon the

    conditions specified inside the parenthesis.

  • 7/30/2019 COMP 172 SM

    30/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 30

    Ex:if(a>=b)

    {

    Expression Statement(s);.

    }

    LECTURE 11:

    STEPS IN LEARNING C (HEADER FILES, INPUT & OUTPUT FUNCTONS)FORMATTED & UNFORMATTED I/O FUNCTIONS)

    *Steps in Learning C*

    Header Files:-

    Library functions that have similar functions are grouped together as programs(with file

    extensions .h) in separate library files.

  • 7/30/2019 COMP 172 SM

    31/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 31

    These library files are supplied as a part of the C compiler.

    In order to use library function it is necessary to include a specific information within the mainportion of the program, called the header files.

    The genera form (or) syntax of including a header file in the program is

    #include< filename.h>Where

    filename represents the header file which has their file extension as .h.

    The different header files in C language are:

    stdio.h conio.h math.h string.h*Input & Output in C*

    One of the primary advantages of modern computers is their ability to communicate with the userduring program execution.

    This feature enables the programmer to enter the values for the variables, when the program is inexecution without altering the program.

    Once the required value has been entered and the ENTER key is pressed, program executionstarts again, and the output is displayed in the screen.

    To perform input and output operations, C has a number of input and output functions.

    These functions can be broadly classified into two types. They are:

    Formatted I/O functions

    Unformatted I/O functions

    Formatted I/O functions:-

    The formatted I/O functions read any type of data as input from the user and displays of

    data output in the screen.

    They use format strings (conversion specifiers) for identifying the type of data invovled.

    The scanf( ) function is formatted input function

    The printf( ) function is formatted output function

    Unformatted I/O functions:-

    All unformatted I/O function reads and displays only char data type.

    They dont use format strings for identifying the type of the data involved, since all data

    are considered in character format.

    The getch( ) , getche( ) , and getchar( ) are single character unformatted input functions.

    The put( ) , putchar( ) , are single unformatted input functions.

  • 7/30/2019 COMP 172 SM

    32/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 32

    The gets( ) , puts( ) , are unformatted I/O functions.

    LECTURE 12:

    BASIC STRUCTURE OF A SIMPLE C PROGRAM

    *Structure of C Program*

    These header files contains information about various library functions that are functionally same.

    Every C program contains a number of building blocks.

  • 7/30/2019 COMP 172 SM

    33/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 33

    These building blocks should be written in a correct order and procedure, for the C program toexecute without any errors.

    To know about the building blocks in detail, let us see a sample program for calculating the sumof two integers and to display its result.

    /* Program to calculate the sum of two integers */ /* Title camment */#include /* Library file Access */void main( ) /* Function*/{int x, y, sum; /* Declaration of variables*/printf( Enter the values of x and y:\n); /*Output statement*/scanf(%d %d, &x, &y); /*Input statement*/sum= x+y; /*Assignment statement*/printf(The sum of the variables x and y = %d,sum);/*Output statement*/

    }

    Comments are added at each end of the statement in order to understand the overall programorganization easily. Let us see each comment statement in detail.

    /* Title Comment*/

    Any comment statement used in the program must be enclosed within /* */.

    The comment statement is used to identify the purpose of the program.

    This statement is usually specified at start of a program, but they can be specified anywhere in the program.

    This may (or) may not be present in the program as per the programmer wish.

    The comment statement is not a executable statement.

    The compiler skips the line when it encounters a comment statement.

    Comment statements may be included in between the program to understand eachstatement used in the program.

    Its a good programming practice to include comment statements in a program.

    /* Library file Access */

    The second line in the program #include refers to a special file which contains, theinformation about the various input and output operations which must be included in theprogram when it is compiled.

    The header file stdio.h contains the information of all the standard input and outputfunctions in C.

    There are many header files like math.h , string.h, ete.., which are used in the programsdepending upon the library functions used in the program.

  • 7/30/2019 COMP 172 SM

    34/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 34

    Header files are usually enclosed in < > (or) .

    If u do not include the header file stdio.h in the program, the C compiler may complainabout undefined functions and data types used in the program.

    /* Function*/

    The third line in the program is main( ) is a function, which may consists of one (or) morestatements.

    Every C program must contain at least one function which must be a main( ).

    A C program will always begin by executing the main( ) function.

    This main( ) function will access other functions used in the program.

    The empty parenthesis followed by main( ) indicates that this function does not include any

    arguments.

    The remaining lines of the program are enclosed within a pair of braces.

    The statements enclosed within a pair of braces are referred as the body of the functions.

    These lines are within the compound statement main( ).

    /* Declaration of variables*/

    A declaration of a variable is a statement that gives information to the C compiler about the

    variables to be used in the program.

    General form (or) the syntax of declaring a variable is

    Data type variable(s);

    The declaration consists of a data type, followed by one (or) more variable names,separated by commas ending with a semicolon.

    Ex:

    int x, y, sum;

    Where

    int is the data type in C and x and y are variables and sum is variable names to

    be used in the program.

    The type of variable informs the compiler how the variable values are to be

    stored(i.e., how much of memory space is to be allocated).

    Note that all variables used in the program must be declared before all

    executable statements.

  • 7/30/2019 COMP 172 SM

    35/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 35

    /*Output statement*/

    The other lines in the program are statements.

    The first statement is the printf( ) statement, that generates a request to the user to giveinformation (i.e., values) for the variables x and y for summation.

    The printf( ) statement is usually called as the output statement since it display the messageon the screen.

    The information to be displayed in the screen must be specified within double quotes( )

    /*Input statement*/

    The value for the variables x and y are entered into the computer through the scanf( )

    statement, which is below the printf( ) statement.

    The scanf( ) statement is usually called as the input statement because it reads the valuesto be processed by the computer.

    /*Assignment statement*/

    The fourth line is an important for this program since it adds the two valued of x and yentered through the keyboard.

    This statement is called as an assignment statement sine it assign the value of x+y to the

    variable name sum.

    /*Output statement*/

    The last line is the printf( ) statement ,which displays the output of the program (.e., thesummation of x and y) in the screen.

    Important points to be noted while writing a C program:

    All statements must be written in lowercase letters.

    However, symbolic constants , identifiers can be written in lowercase and/or upper

    case letters.

    All statements must be end with a semicolon.

    Comment statements can be included wherever necessary in the program . Its a

    good programming practice to include comment statements in a program.

    White spaces during variable declaration , within arguments in functions, before and

    after operators.

    The opening and closing flower braces used in a program should be balanced, i.e.; if

    opening braces are three, then the closing braces should also be three.

  • 7/30/2019 COMP 172 SM

    36/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 36

    *The main( ) Function*

    A function is a self-contained program segment that carries out some specific, well defined taskwhenever it is accessed.

    A program can have one or more functions but there should be at least one function, which mustbe a main( ) function.

    Empty parenthesis following the word main are necessary.

    Some programmers place the main( ) function at the beginning of the file, and other use it at theend. Regardless of their location, every C program must contain a main( ) function.

    The main( ) function consists of two parts namely, the declaration part and the execution part.

    The declaration part declares all the variables used in the executable part.

    Initialization of variables can also be done in the declaration part.

    Declaration of variables allocates a memory spaces according to their data types specified.

    The execution part contains one (or) more statements following the declaration part.

    The execution part uses all the variables declared in the declaration part.

    The declaration and execution parts must appear between the opening and the closing braces ofthe main( ) function.

    The program begins its execution at the opening flower brace { and ends its execution in theclosing flower brace }.

    The closing flower brace of the main( ) function is the logical end of the program.

    All statements in the declaration and executable part ends with semicolon.

    A main( ) function may (or) may not contain a declaration statement but it should have anexecutable statement.

    The empty parenthesis followed by main( ) indicates that this function does not include anyarguments.

    LECTURE 13:

    DECISION MAKING (OR) CONTROL STATEMENTS

    *Control statements*

    The statements, that we have seen so far, are normally executed as they appear in the program.

  • 7/30/2019 COMP 172 SM

    37/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 37

    By default, the statements in the program are executed sequentially.

    However, in practice we have situations where we have to change the order of execution of

    statements until the some specified conditions are met.

    The control statements alter the execution of statements depending upon the conditions specified

    inside the parenthesis.

    The different decision control (or) decision-making statements in C are:

    The if statement

    The if-else statement

    The multiple if-else statements

    The nested if-else statements

    The switch statement

    The if statement:-

    Like many programming languages, C also uses the keyword if to implement decision control

    statements.

    The general form (or) syntax of an if statement is:

    if(condition){

    executable -X-statement(s);}

    executable -Y-statement(s);

    The above syntax shows the operation of an if statement.

    The condition used in an if statement should be specified within parenthesis.

    When a program with if statement is evaluated the condition specified after the if

    statement is executed first.

    If the condition is true then the executable-X-statement(s) within the flower braces will be

    executed.

    If the condition is false, the control will be directly transferred to the statement outside the

    flower braces and executes executable-Y-statement(s) without executing executable-X-

    statement(s).

    The executable-X-statement(s) referred as the body of the statement, should enclosed

    within flower braces.

    Ex:If a and b are two variables the actual conditions are:

    a==b , a!=b , a>b , a=b , a

  • 7/30/2019 COMP 172 SM

    38/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 38

    The if-else statements:-

    The if-else statement is an extension of an ordinary if statement.

    The if statement by default will execute a single statement (or) group of statements when the

    condition is true, but if does nothing when the condition is false.

    Hence, we are using an else statement to execute a single statement (or) group of statements

    when the when the condition is false.

    The general form (or) syntax of an if-else statement is:

    if(condition)

    {executable -X-statement(s);

    }

    else{

    executable -Y-statement(s);}

    The above syntax shows the operation of an if statement.

    The condition used in the if statement should be specified within parenthesis.

    If condition is true the statement(s) following if until else will be executed.

    If the condition is false the statement(s) following the else will be executed.

    The group of statements after the if up to and not including the else are called as

    the if block.

  • 7/30/2019 COMP 172 SM

    39/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 39

    The group of statements after the else are called as the else block.

    The Multiple if else statement:-

    When a series of decisions are involved we have to use more than one if-else statement

    called as multiple ifs.

    Multiple if else statements are much faster than a series of if-else statements, since the if

    structure is exited when any one of the condition is satisfied.

    The general form (or) syntax of an Multiple if-else statement is:

    if(condition){

    executable -X-statement(s);}

    else if(condition){

    executable -Y-statement(s);}

    else{

    executable -Z-statement(s);}

    The Nested if-else statements:-

    One (or) more if-else statements inside an if-else statement is called as nested if

    statements.

    The general form (or) syntax of an Multiple if-else statement is:

  • 7/30/2019 COMP 172 SM

    40/103

  • 7/30/2019 COMP 172 SM

    41/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 41

    The default group may appear any where within the switch statement, it need not be placed at

    the end.

    LECTURE 14:

    BRANCHING & CONCEPT OF LOOPING STATEMENTS

    *Branching & Looping*

    One of several possible actions will be carried out depending upon the outcome of the logical test

    is referred as branching.

  • 7/30/2019 COMP 172 SM

    42/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 42

    Some portion of the program (or) segment of the program has to be executed several number

    times (or) until a particular condition is being met. This is referred as looping.

    Some portion of the program has to be specified several number of times (or) until a particular

    condition is satisfied.

    Such repetitive operation is done through a loop structure.

    The loop concept is essential and it is fundamental for good programming.

    The three methods by which you can repeat a part of a program are,

    By using a while loop

    By using a do-while loop

    By using a for loop

    While LOOP:-

    The simplest of all the looping structures in C is the while loop.

    The general form (or) the syntax of while loop is:

    initialize loop counter;while(condition){

    Statement(s);increment (or) decrement loop counter;

    }

    The above figure shows the operation of the while loop.

    A looping process generally has three steps. They are,

    Initialization of the counter

    Test for a specified condition for execution of the statements inthe loop

  • 7/30/2019 COMP 172 SM

    43/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 43

    Incrementing (or) Decrementing the counter.

    In looping, a sequence of statements is executed until some conditions are satisfied.

    A loop consists of two segments:

    One is referred as the body of the loop and the other is

    Control statement.

    The control statement tests certain conditions and then directs the repeated execution of the

    statement(s) contained in the body of the loop structure.

    When the condition specified inside the parenthesis of while loop is satisfied, the control is

    transferred to the statement(s) inside the loop and executes the body of the loop and

    increments (or) decrements the loop counter.

    The loop is continues when the condition is violated.

    The while loop tests the condition before each iteration.

    If the condition initially fails the loop is skipped entirely even the first iteration itself.

    do while LOOP:-

    The do-while loop sometimes referred as do loopdiffers from its counterpart the while loop

    in checking the condition.

    The condition of the loop is not tested until the body of the loop has been execute once.

    If the condition is false, after the first loop iteration the loop terminates.

    However if the condition is true the loop continues.

    The general form (or) the syntax of the do-while loop is:

    initialize loop counter;do{

    Statement(s);increment (or) decrement loop counter;

    }while(condition);

    In do-while the statements would be executed at least once even if the condition fails for the

    first time itself.

  • 7/30/2019 COMP 172 SM

    44/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 44

    The control enters the loop without testing any condition and the body of the loop is executed

    once.

    After executing once, the while statement it checks the condition, since the condition is true

    control is transferred again to the starting of the do loop and the body of the loop is again

    executed.

    This process continues until the condition is false.

    for Loop:-

    The for loop allows us to specify three things about the loop in a single line. They are,

    Initializing the value for the loop

    Condition in the loop counter to determine whether the loop should continue (or) not.

    Incrementing (or) decrementing the value of loop counter each time the program

    segment has been executed.

    The general form (or) the syntax of the for loop is:

    for(e1; e2; e3){statement(s);

    }

    Where

    e1 is an expression which is used to initialize one (or) more variables used in the for

    loop. (Initialization)

    e2 is an expression which is used to test the condition in the for loop. (Condition)

    e3 is another expression used for incrementing the index which may/may not be

    initialized in the expression. (Increment (or) Decrement)

  • 7/30/2019 COMP 172 SM

    45/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 45

    When the for loop starts its execution the expression(s) present in e1 will be

    initialized first and then checks for the condition in expression e2.

    If the condition satisfies, the statement(s) in the body of the loop is executed once

    and then increments (or) decrements the index as in expression e3.

    The looping action continues as long as the condition in e2 is true.

    Note that the control goes to expression e1 only when it enters loop for the first time

    only, after that depending upon the condition the expressions e2 and e3 are

    executed alternatively.

    *The break Statement*

    The break statement is used to terminate (or) exitfrom switch statement.

    The general form (or) the syntax of the breakstatement is

    break;

    The break statement does not have any embedded

    expression (or) arguments.

    The break statement can be also used within a for,while (or) do-while loops.

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

    The keyword break breaks the control only from theloop in which it is placed.

    The above program prints the numbers 0 through 10 on the monitor. Then the loopterminates because break causes immediate exit from the loop. Overriding the conditionaltest i

  • 7/30/2019 COMP 172 SM

    46/103

  • 7/30/2019 COMP 172 SM

    47/103

  • 7/30/2019 COMP 172 SM

    48/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 48

    LECTURE 15:

    CONCEPTS OF ARRAYS & TYPES OF ARRAYS

    *Arrays*

    C language provides the capability that enables the user to design a set of similar data typescalled arrays.

    They are defined in the same manner as ordinary variables except that each array name mustbe accomplished by size specification within square braces capable of storing more than onevalue at time.

    The array is defined as a set of homogeneous data items of the same type that share acommon name.

    The individual values in the array are called elements.

    Each array element is referred by specifying the array name, followed by a number withinsquare braces referred as an index (or) subscript.

    The dimension of an array is determined by the number of subscripts needed to identify eachelement.

    A subscript must be always enclosed in square braces[ ], placed after the array name.

    Each subscript must be expressed as a non-negative integer.

    Declaring Arrays:-

    Like an ordinary variable, an array variable should also be declared.

    The general form (or) syntax of declaring an array is:

    datatype arrayName[Subscript];

    Where

    arrayName is a valid C variable of type datatype

    subscript is an integer constant indicating the maximum number of elements

    that can be stored in the array.

    Ex: int days[31];

    is read as days,an array of 31 int values.

    In the above declaration:

    int-data type

    days- name of the array

  • 7/30/2019 COMP 172 SM

    49/103

  • 7/30/2019 COMP 172 SM

    50/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 50

    The arrays that have seen so far are all single dimensional arrays.

    A list of items can be given a variable name using only one subscript and such a

    variable is called as a single dimensional array also referred as list.

    The main purpose of an array is to reserve space for the elements in memory.

    The general form (or) syntax of an array declaration is:

    storageType dataType arrayName[Size];

    Where

    storage Type while declaring an array is optional.

    The dataType specified the type of elements that will be stored in the array.

    The arrayName is the name used to identify the array.

    The rule for naming arrays are same as identifiers.

    The size is a positive integer constant, indicating the maximum number of

    elements that can be stored in the array.

    Each subscript must be expressed as an non-negative integer.

    In an n-element array, the array elements are stored in x[0],x[1],x[n-2],x[n-1]order.

    Ex: int value[50];

    char book[104];

    In the first example, int specifies the type of the variable and value

    specifies the name of the array.

    The number 50 within square braces indicates the maximum number

    of elements to be stored in the array.

    In second one the book is character array with a size of104

    elements.

    Double Dimensional Arrays :-

    Array whose elements are specified by two subscripts are referred as two-

    dimensional arrays (or) double dimensional arrays.

    The double dimensional array is defined in the same manner as single dimensional

    array except that it requires two pairs of square brackets for two subscripts.

    The double dimensional array is also referred as matrix.

  • 7/30/2019 COMP 172 SM

    51/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 51

    Each subscript must be expressed as non negative integer.

    The general form (or) syntax of a double (or) two dimensional array is:

    storageType dataType arrayName[rowsize][colsize];

    Where

    storage Type while declaring an array is optional.

    The dataType specified the type of elements that will be stored in the

    array.

    The arrayName is the name used to identify the array.

    The rule for naming arrays are same as identifiers.

    The rowsize and colsize are positive value integer constants.

    These two subscripts indicate, the number of array elements

    associated with each subscript.

    Two square braces are used to indicate the values of two subscripts.

    Ex: int mark[2][2];

    The above array declaration defines the table as an integer array having 2

    rows and 2 columns.

    An array elements start with an index zero and so the individual elements of

    the array will be

    int mark [0][0] [0][1][1][0] [1][1]

    The first element stored in the memory location [0][0],followed by the

    second element in [0][1] and so on, and the last element will be stored in

    the memory location [1][1].

    An m X n, double dimensional array can have a table of values having

    m rows and n columns.

    It is not compulsory that the row-size and col-size should be equal.

    Care must be taken to initialize the values of the elements.

  • 7/30/2019 COMP 172 SM

    52/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 52

    LECTURE 16:

    TYPES OF FUNCTIONS (LIBARARY FUNCTIONS & USER DEFINED FUNCTIONS)

    *Types Of Functions* A function is a self contained program segment (block of segments) that performs some specific

    well-defined task when called.

    Functions break large computing tasks in to smaller ones.

    C allows programmers to define their own functions for carrying out various individualtasks.

    C has been designed to make functions efficient and easy to use.

    C programs generally consist of many small functions rather than few big ones.

    Every C program consists of one or more functions, but there should be at least onefunction which must be main( ).

    Each time when a new program is written, main( ) function must be defined.

    The main ( ) function calls another function to share the work.

    C functions may be classified into two categories namely

    Library functions User-defined functions

    *Library Function*

    C's standard library provides a rich collection of functions for performing input, output,

    string manipulations, common mathematical calculations, and many other functions for

    performing useful operations.

    There are many library:

    Functions that carries standard input and output operations

    Ex: scanf( ) , printf( ), gets( ), puts( ) etc..,

    Functions that perform operations on characters

  • 7/30/2019 COMP 172 SM

    53/103

  • 7/30/2019 COMP 172 SM

    54/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 54

    Inside func function

    Once the function func( ) has completed its execution, control is transferred or

    returned to the next statement from which the function is called (i.e., to thesecond printf( ) function inside the main( ) function).

    The printf( ) function displays the message:

    Again inside main function

    and the program ends.

    This is compulsory when the function is called from another function.

    Generally, a function will process information that is passed to it from the calling

    part of the program.

    Information is passed to the function via special identifiers called arguments orparameters and returned via the return statement.

    Advantages of Functions:-

    There are many advantages in using functions for writing programs.

    For example, many programs may require a particular group of statements to be executedrepeatedly from different places within the program. These repeated statements can beplaced within a single function, which can be executed whenever it is needed.

    Thus, the use of a function avoids the need for same statements to be repeated in aprogram and thus saves memory.

    The use of functions also enables a programmer to build user-defined library functions offrequently used routines containing system dependent features. Each routine can beprogrammed as a separate function and stored within a special library file.

    These user-defined library functions can be added as a later part of the C programminglibrary.

    Note:

    The semicolon is present in

    the function, when thefunction is called within the

  • 7/30/2019 COMP 172 SM

    55/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 55

    LECTURE 17:

    CONCEPT OF FUNCTIONS (DEFINING A FUNCTIONS & FUNCTION PROTOTYPE)

    Defining a Function :-

    A function definition consists of two parts. They are,

    Argument declaration

    Body of the function

    The first part of the function specification consists of type specification of the value returnedby the function followed by the function name, a set of arguments (may or may not bepresent) separated by commas and enclosed in parenthesis.

    If the function definition does not include any arguments, an empty pair of parenthesis mustfollow the function name.

    The general form or the syntax of defining a function is,

    returnType functionName (argument list){

    declaration (s) ;statement (s); Body of the function

    return(expression);

    }

    Where

    The returnType specifies the data type of the value to be returned by the function.C assumes that every function will return a value.

    The returnType is assumed to be of type int by default if it is not specified.

    The functionName is used to identify the function.

    The rules for naming a function are same as identifiers.

    The argument list specified inside the parenthesis after the function name isoptional.

  • 7/30/2019 COMP 172 SM

    56/103

  • 7/30/2019 COMP 172 SM

    57/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 57

    The expression within parenthesis of the return statement is the value, which is returned to

    the called function.

    If the function reaches the final closing braces without any return statement, control will be

    transferred to the calling function without passing any value.

    The returnType specified in this case is void.

    *The return Statement*

    The return statement is used to return the control from the calling function to the nextstatement of the called portion of the program.

    The return statement also causes the program logically to return to the point from where thefunction is accessed (called).

    The return statement returns one value per call.

    The return statement can be any one of the types as shown below:

    return;return();return(constant);return(variable);return(expression);return(conditional expression);return(function);

    The first and second return statements, does not return any value, and are just equal to theclosing brace of the function.

    If the function reaches the end without using a return statement, the control is simplytransferred back to the calling portion of the program without returning any value.

    The presence of an empty return statement (without any expression or constant or variable) isrecommended in such situations.

    These return statements returns a value 1 to the calling function.

    The third return statement returns a constant to the calling function.

    For example:if(x

  • 7/30/2019 COMP 172 SM

    58/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 58

    The fifth return statement returns a value depending upon the result of the expressionspecified inside the parenthesis.

    For example:

    return(a +.b * c) ;

    returns a value depending upon the values of a, b.and c.

    The sixth return statement returns a value depending upon the result of the conditionalexpression specified inside the parenthesis.

    For example:return(a > b ? a : b);

    The above return statement returns a value depending upon the value ofthe variables a and b.

    The last return statement calls the function specified inside the parenthesis and collects the

    result obtained from that function, and returns it to the calling function.For example:

    return(power(3,2));

    returns a value, obtained after evaluating the power( ) function.

    Important points to be noted while using return statement:-

    The limitation of a return statement is that it can return only one value from the called functionto the calling function.

    The return statement can be present anywhere in the function, not necessarily at the end of

    the function.

    Number of return statements used in a function are not restricted, since the return statementwhich executes first will return the value from the called function to the calling function and theother return statements are left unexecuted.

    If the called function does not return any value, then the keyword void must be used as thereturn type specifier.

    Parenthesis used around the expression in a return statement is optional.

    Function Prototypes:-

    A C function returns an integer value by default.

    Whenever a call is made to a function the compiler assumes that this function would return avalue of type int.

    If you decide that a function should return a value other than int, then it is necessary tomention the first line of the function in the program, before it is used, which is called as thefunction prototype also referred as the function declaration.

    The function prototype not only identifies the return type of the function, but also the name ofthe function, the number of parameters in the function, the data types of the parameterspassed and the order in which they are expected.

    Function prototypes are usually written at the beginning of the program explicitly before alluser-defined functions including the main () function.

  • 7/30/2019 COMP 172 SM

    59/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 59

    The general form or the syntax of declaring a function prototype is,

    returnType functionName(dtl argl,dt2 arg2,...,dtn argn);

    Where

    returnType represents the data type of the value that is returned by the function, anddtl,dt2, . . ., dtn represents the data types of the arguments arg1, arg2, . .., argn.

    The data types of the arguments should be specified compulsorily in the functionprototype, but specifying the arguments of the data types is optional.

    The function prototype resembles the first line of the function definition (but the firstline of the function definition does not end with a semicolon).

    The names of the arguments within the function prototype need not be declaredelsewhere in the program.

    The data types of the actual arguments must confirm to the data types of thearguments within the prototype.

    For example:

    int sum(int x);Where

    sum is the name of the function, int before the function name fact( )

    indicates that the function returns a value of type int.

    The variable x inside the parenthesis is the parameter passed to the called

    function.

    The data type int before the parameterx indicates that it is of type integer.

    * Types of Functions*

    A function depending upon the arguments present or not and whether a value is returned or not,may be classified as

    1. Function with no argumentsand no return values.

    2. Function with return valuesand no arguments.

    3. Function with arguments andno return values.

    4. Function with arguments andreturn values.

    1. Function with no arguments andno return values:

    When a function has noarguments, it does not receiveany data from the calling

    Ex.Program:

    #include#includevoid name( ); /* function prototype */void main( ){

    name( );}void name( ){

    char empname[25];printf("Enter the employee name :);

    scanf("%s", empname);printf ( "The employee name is %s", empname);

    }output:

    Enter the employee name : RamaThe employee name is Rama

  • 7/30/2019 COMP 172 SM

    60/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 60

    function, similarly when a function has no return values, the calling function does notreceive any data from the called function.

    Hence, there is no data transfer between the calling function and the called function.

    If such functions are used to perform any operation, they read the input and display the

    output in the same block.

    In Ex.Program:

    main ( ) is the calling function which calls the function name( ).

    The function name( ) contains no arguments and hence, there are no argument

    declarations.

    Note that the called function (i.e., name) receives its data (i.e., name of the employee)

    directly from the input terminal (i.e., keyboard)and displays the contents ofempname to

    the output terminal (i.e., screen) in the called function itself.

    No return statement is employed since there is nothing to be returned.

    The closing brace of the function indicates the end of execution of the function, thusreturning the control, back to the calling function.

    The keyword void is used before the function name( ) to indicate that there are no

    return values.

    2. Function with retrun values and noarguments:

    When a function has no arguments, itdoes not receive any data from thecalling function, but it can do someprocess and then return the result tothe called function.

    Hence, there is data transfer betweenthe calling function and the calledfunction. .

    Ex.Program:

    /* Program to find the sum of even numbers

    within the limit */#include#includeint sum( ); /* function prototype */void main( ){

    printf ( " is %d" , sum ( ) ) ;}int sum( ){int i, n, result=0;printf("Enter the limit : "};scanf("%d", &n) ;printf("Sum of Even numbers within %d"

    ,n);for(i=2;i

  • 7/30/2019 COMP 172 SM

    61/103

    Computer Programming and DataStructures

    College of Agricultural Engineering, Bapatla 61

    In Ex.Program:

    main ( ) is the calling function which calls the function sum ( ) .

    The function sum ( ) contains no arguments and hence, there are no argument

    declarations.

    Note that the called function (i.e., sum ( ) receives its data (i.e., the limit for calculating the

    even numbers) directly from the input terminal (ie., keyboard) in the called function (i.e.,

    sum ( ) ).

    The return statement is employed in this function to return the sum of first n even

    numbers calculated within the limit and the result is displayed from the main ( ) function to

    the standard output device (i.e., screen).

    Note that int is used before the function name sum ( ) instead of void since it returns a

    value of type int to the called function.

    3. Function with arguments and no retrun values :

    When a function has arguments, it receives data from the calling function.

    The main( ) function will not have any control over the way in which the functionsreceives its-input data.

    We can also make the calling function to read data from the input terminal and pass itto the called function.

    This approach seems better becau