FOP Material Up to Unit - 5

290
Fundamentals of Programming (FOP) 2610001 http://www.rogerdarlington.me.uk/stories.htm l

description

FOP Material Up to Unit - 5

Transcript of FOP Material Up to Unit - 5

  • Fundamentals of Programming (FOP)

    2610001

    http://www.rogerdarlington.me.uk/stories.html

  • Introduction to programming& Basics of C: Concepts of Algorithm and Flowcharts, Process of compilation, Generation of languages, Basic features of C Language like Identifier, Keywords, Variable, data types, Operators and Expression. Basic screen and keyboard I/O 9 Lect.

    2. Control Statements: Test Conditions, Conditional execution and selection, Iteration and Repetitive Executions, Nested loops. 3 Lect.

    3. Arrays: Introduction to contiguous data types. One dimensional arrays, multidimensional arrays, Array as strings, multidimensional character arrays. Operations on strings. 4 Lect.

    4. Functions: Concept of modular programming, Using functions, Scope of data, Recursive functions. Command line arguments. 3 Lect.

    10/11/2012 2 Prepared By:Swaminarayan Priya, ISTAR

  • 5. Pointers: Need of pointer, Types and uses of pointer, Array and Pointers, Pointers and

    strings, Pointer to Pointer, Pointers and functions, other aspect of pointers. 8 Lect. 6. User Defined Data Types: Introduction to structures, usage of structure, nested structures, Union and its

    usage, Enumeration types, bit fields. 6 Lect. 7. Files: Types of files, working with files, usage of file management functions. 8 Lect. 8. Linked List: Introduction to dynamic memory allocation, singly link list, operations on singly

    link list. 6 Lect. 9. Other features of C: Bitwise operators and its usage, C Preprocessor statements. 3 Lect.

    10/11/2012 3 Prepared By:Swaminarayan Priya, ISTAR

  • Books

    Text Book: 1. Programming in C, by Pradip Dey & Manas Ghosh, Publisher Oxford

    Reference Books: 1. Programming in ANSI C, by Balagurusamy, Publisher - Tata McGraw Hill. 2. Computer Science: A Structured Programming Approach Using C, by

    Behrouz A. Forouzan & Richard F. Gilberg, Publisher Thomson Education.

    3. Programming with ANSI and Turbo C, by Ashok N Kamthane, Publisher Pearson Education.

    4. Mastering C, by Venugopal & Prasad, Publisher Tata McGraw Hill. 5. C: The Complete Reference, by Herbert Schildt, Publisher Tata McGraw

    Hill. 6. Let us C, by Yashwant Kanitkar, Publisher BPB Publication 7. Schaum's Outline of Programming with C, By: Byron Gottfried, Publisher

    Shaum Series.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 4

  • Chapter 1 Introduction to Programming: Algorithms and Flowcharts

    A computer can neither think nor a make a judgment on its own.

    Program: A program is a set of logically related instructions that is arranged in a sequence and guides the computer in solving a problem.

    Programming: The process of writing a program is called programming.

    Packaged Software: User can directly purchase readymade existing program.

    Customized Software: Developer prepare a new program from scratch.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 5

  • 1.1. Programs and Programming Computer Software

    System Software: It is a collection of programs that interfaces with the

    hardware. Categories of System Software are as follows: 1. Language Translator 2. Operating System 3. Utilities 4. Special Purpose Program Language Translator: It is a system software that transforms a computer

    program written by a user into a form that can be understood by the machine.

    Operating System: It is the master control system software which manages the computers resources effectively, take care of scheduling multiple jobs for execution, and manages the flow of data and instructions between the input/output units and the main memory.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 6

    System Software

    Application Software

    Computer Software

  • 1.1.1 System Software

    Utilities: Utility programs are those that may be requested by application programs many times during the execution phase.

    Some examples are as follows:

    1. SORT/MERGE for sorting large volumes of data and merging them into a single sorted list.

    2. Transfer programs for transforming data content from one medium to another, e.g., disk to tape, tape to disk etc.

    Special purpose software: Special programs are those that extend the capability of operating systems to provide specialized services to application programs. For e.g. loader, linker, etc.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 7

  • 1.1.2. Application Software

    Application Software is written to enable the computer to solve a specific data processing task.

    There are two categories of application software : Pre-written software packages and user application programs.

    Characteristics of Application software:

    Easy to learn and use compare to programming language

    It performs many general and special functions.

    In some of the application when it found inadequate then application programs are written to meet the exact requirements.

    A user application program may be written using one of these packages or a programming language.

    The most important categories of software packages available are:

    1. Database management software

    2. Spreadsheet software

    3. Word processing, Desktop Publishing (DTP), and presentation software

    4. Multimedia Software

    5. Data Communication software

    6. Statistical and operational research software

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 8

  • 1.2. Programming Language

    Programming Language: It is composed of a set of instructions in a language understandable to the programmer and recognizable by a computer.

    It is classified into three categories:

    1. High-level

    2. Middle-level

    3. Low-level

    High-level languages such as BASIC, COBOL (COmmon Business Oriented Language), FORTRAN (FROmula TRANlation) are used to write application programs.

    A middle-level language such as C is used for writing application and system programs.

    A low-level programming language such as the assembly language is mostly used to write system programs.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 9

  • 1.2.1. System Programming Languages

    An example of system software is an operating system consisting of many other programs that control i/o devices, memory, processor, schedule the execution of multiple tasks, etc.

    To control the computers circuitry as well as manage the resources of the computer.

    Assembly language was used to write system programs.

    But, today C is widely used to develop system software.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 10

  • There are main two main categories of application programs: Business Program and Scientific Application Program.

    Application programs are designed for specific computer applications such as payroll processing and inventory control.

    In application program, programmer does not need to control the circuitry of computer but

    Business applications are characterized by processing of large inputs and high-volume data storage and retrieval but call for simple calculations.

    Scientific Application Program: Programming languages designed for writing scientific programs contain very powerful instructions for calculations but have poor instructions for input, output etc.

    COBOL is more suitable for business applications whereas FORTRAN is more suitable for scientific applications.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 11

    1.2.2. Application Programming Languages

  • 1.2.3. Low-level language

    A low-level computer programming language is closer to the native language of the computer, which is 1s and 0s.

    Machine Language: Instructions are written in a sequence of 0s and 1s. Machine language is considered as the first generation language

    (1GL) Advantage of Machine language: The CPU directly understands machine instructions, hence no

    translation is required. It takes less execution time. Disadvantages of Machine Language: Difficult to use: It is difficult to understand and develop a program

    using machine language. Machine Dependent: Error Prone: It is very difficult to remember the various combinations

    of 1s and 0s. Difficult to debug and modify:

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 12

  • Machine Language

    Example 1:

    Machine Code Comments

    0011 1100 Load A register with value 7

    0000 0111

    0000 0110 Load B register with 10

    0000 1010

    1000 0000 A = A + B

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 13

  • Assembly Language: In this language, various symbols such as letters, digits or special characters are used to represent the operation, operand and other parts of the instruction code.

    This representations are known as mnemonic codes; they are used instead of binary codes.

    It is considered as a second generation language (2GL). Each computer has its own assembly language that is dependent upon the

    internal architecture of the processor. An assembler is a translator which converts program from assembly

    language to machine language. An assembler is a translator which converts program from assembly

    language to object code, which can then be executed by machine. Note: The object code is the machine language code.

    Mnemonics Comments LD A,7 Load register A with 7 LD B,10 Load register B with 10 ADD A,B A = A + B

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 14

    1.2.3. Low-level language

  • Assembly Language

    Advantages of Assembly Language:

    Easy to write and understand.

    More readable.

    Disadvantages of Assembly Language:

    Machine dependent

    Programming is difficult and time consuming.

    The programmer should know all about the logical structure of the computer.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 15

  • High-level languages such as COBOL, FORTRAN, BASIC etc. have instructions that are similar to human languages.

    It is also known as third-generation languages (3GL). The time and cost of creating machine and assembly language programs

    quite high. Statement Number Program Statement 10 LET X = 7 20 LET Y = 10 30 LET SUM = X + Y Advantages of high-level programming languages: Readability: More readable than assembly and machine level language. Portability: Easy Debugging: Errors can be easily detected and removed. Ease in the development of software. Disadvantage of high-level language: It takes more time for execution of program.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 16

    1.2.4. High-level languages

  • 1.3. Compiler, Interpreter, Loader and Linker

    There are two kinds of translators exist: Compiler and Interpreter

    Source Program in High Level Language Compiler Object Code in Machine Level Language

    Diagnostics: During the process of translation, the compiler reads the source programs statement wise and checks for syntax errors. In case of any error, the computer generates a printout of the same. This action is known as diagnostics.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 17

    Compiler Interpreter

    Scans entire program before translating it into machine code

    Translates and executes the program line by line

    Converts entire program to machine code and only when all the syntax errors are removed does execution take place.

    Each time the program is executed, every line is checked for syntax error and then converted to the equivalent machine code.

    Slow in debugging, i.e. removal of mistakes from a program.

    Good for fast debugging.

    Execution time is less Execution time is more.

  • 1.3.1 Compiling and Executing High-level Language Program

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 18

    The compilation process consists of two steps:

    1. The analysis of the source program

    2. The synthesis of the object program in the machine language of the specified machine.

    The analysis phase uses the precise description of the source programming language.

    A source language is described using lexical rules, syntax rules and semantic rules.

    Lexical rules specify the valid syntactic elements or words of the language.

    Syntax rules specify the way in which valid syntactic elements are combined to form the statements of the language.

    Semantic rules assign meaning to valid statements of the language.

  • The execution of a program written in high-level language involves the following steps:

    1. Translation of the program resulting in the object program.

    2. Linking of the translated program with other object programs needed for execution, thereby resulting in a binary program.

    3. Relocation of the program to execute from the specific memory area allocated to it.

    4. Loading of the program in the memory for the purpose of execution.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 19

  • Fourth Generation Languages (4GL)

    It is non-procedural language that allows the user to specify what the output should be without describing how data should be processed to produce the result.

    It requires less instructions to accomplish a particular task than a third generation language.

    The programmer should be able to write a program faster in 4GL than 3GL. The 3GL languages are procedural languages but 4GL languages are non-

    procedural languages. Major 4GLs are used to get information from files and databases.

    DBMS Package

    Some 4GLs are used to produce complex printed reports. Eg. Of Report Generators are:

    Jasper (For JAVA) Crystal Report Third Party Reports: Dundas S/ws (which produces reports, charts) VB Report

    Screen Painter

    MS Publisher (Used for designing) Dreamweaver FrontPage

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 22

  • For e.g.

    Step1: Get a record from the EMP file.

    Step2: If this is the record for MANAS, display the address.

    Step3: If this is not the record for MANAS, go to step 1, until end-of-file.

    Advantages of 4GLs:

    Programming productivity is increased. One line of a 4GL code is equivalent to several lines of a 3GL code.

    System development is faster.

    Program maintenance is faster.

    End users can often develop their own applications.

    Programs developed in 4GLs are more portable than those developed in other generation languages.

    Documentation is of improved order because most 4GLs are self-documenting.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 23

  • Third Generation Languages Fourth Generation Languages

    Meant for use by professional programmers.

    May be used by non-professional programmers as well as by professional programmers.

    Requires specifications of how to perform a task.

    Requires specifications of what task to perform. System determines how to perform the task.

    All alternatives must be specified. Default alternatives are built-in. User need not specify these alternatives.

    Requires large number of procedural instructions.

    Requires fewer instructions.

    Code may be difficult to read, understand, and maintain by the user.

    Code is easy to understand and maintain.

    Difficult to debug. Errors are easier to locate because of shorter programs, more structured code and use of defaults.

    Typically, file oriented. Typically, database oriented.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 24

  • Fifth Generation Languages(5GL)

    Natural languages represent the next step in the development of programming languages belonging to fifth generation languages.

    Natural language is similar to query language, but it eliminates the need for the user or programmer to learn a specific vocabulary, grammar or syntax.

    The text of a natural-language is statement resembles human speech closely.

    It supports machine learning.

    Natural languages already available for microcomputers include CLOUT, Q & A and SAVY RETRIEVER (for use with dbase) and HAL (Human Access Language) for use with LOTUS.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 25

  • Classification of Programming Languages

    1. Procedural Languages

    2. Problem-oriented Languages

    3. Non-procedural languages

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 26

    Programming Language High-level Language Low-level Language Procedural Non-procedural Problem-oriented Machine Assembly 1)Algorithmic 1) Functional 1) Numeric (COBOL, FORTRAN, C) (LISP, ML) (MATLAB) 2) Object-Oriented 2) Logic Based 2) Symbolic (C++, JAVA, SMALLTALK) (PROLOG) (MATHEMATICA) 3) Scripting 3) Publishing (VB, PERL) (LATEX)

  • Structured Programming Concept

    There is no standard definition of structured program.

    Structured programming is

    1. Better organization of programs.

    2. It should be understandable, i.e. more easily modifiable and suitable for documentation.

    3. More economical to run.

    4. More correct and therefore easy to debug.

    Structured Programming can be defined as a:

    1. Top-down analysis for program solving.

    2. Modularization for program structure and organization.

    3. Structured code for individual modules.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 27

  • Top-Down Analysis

    The basic steps to top-down analysis are as follows:

    Step1: Determine the complete scope of the problem to determine the basic requirement for its solution.

    Step2: Based on the definition of the problem, divide the problem into two or more separate parts.

    Step3: Carefully define the scope of each of these separate tasks and subdivide them further, if necessary, into two or more smaller tasks.

    Step4: Repeat step 3 (Every step at the lowest level describes a simple task, which cannot be broken further.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 28

  • Modular Programming

    Modular programming is a program that is divided into logically independent smaller sections, which can be written separately.

    Characteristics of Modular programming are as follows:

    A module consists of a series of program instructions.

    A module is clearly terminated by some special marker. For eg. Return statement in C language.

    A module has a unique name.

    A module has only one entry point and only one exit point from where the control is returned to the calling module.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 29

  • Algorithms

    Algorithm: It is an effective procedure for solving a problem in a finite number of steps.

    Eg. Of an algorithm: for making a pot of tea.

    1. If the kettle dose not contain water, then fill the kettle.

    2. Plug the kettle into the power point and switch it on.

    3. If the teapot is not empty, then empty the teapot.

    4. If the water in the kettle is not boiling, then go to step 5.

    5. Switch off the kettle.

    6. Pour water from the kettle into the teapot.

    Key features of an Algorithm:

    1. Sequence (also known as process)

    2. Decision (also known as Selection)

    3. Repetition (also known as iteration or looping)

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 30

  • Sequence: It means that each step or process in the algorithm is executed in the specified order.

    The decision constructs if..then, if..then..else..

    The outcome of the decision is based on some condition.

    For eg. If today is Friday then collect pay.

    If proposition then process1 else process2.

    The repetition constructs repeat and while

    The repeat loop is used to iterate a process or sequence of processes until some condition become true.

    While

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 31

    Repeat Process 1 Process 2 . . Process N

    Until proposition.

    While proposition Begin process1 process2 . . process N end

    Process1 Process2 . . Process N If proposition goto process1

  • Rules for writing Algorithm

    Each algorithm should have START and STOP statements.

    To accept data from user, the INPUT or READ statements are to be used.

    To display any user message or the content in a variable, PRINT statement will be used. The message will be enclosed within quotes.

    The arithmetic operators that will be used in the expressions are Assignment =, Addition +, Subtraction , Multiplication *, Division /

    In propositions, the commonly used relation operators will include, >, =,

  • In an academic institute, grades have to be printed for students who appeared in the final exam. The criteria for allocating the grades against the percentage of total marks obtained are as follows.

    Marks Grade Marks Grade

    91-100 O 61-70 B

    81-90 E 51-60 C

    71-80 A 0 AND N 50 AND N 60 AND N 70 AND N 80 AND N 90 AND N

  • Construct an algorithm for incrementing the value of a variable that starts with an initial value of 1 and stops when the value becomes 5.

    1. START

    2. C = 1

    3. WHILE C

  • Write an algorithm for determining the sum of the series 2 + 4 + 8 + -- up to N.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 35

    1. START 2. PRINT ENTER THE VALUE

    OF N 3. INPUT N 4. S = 0 5. C = 2 6. S = S + C 7. C = C * 2 8. IF C

  • Write an algorithm for computing the sum of the series 1+x+x2/2!+x3/3!+-- up to N terms.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 36

    1. START 2. PRINT ENTER NUMBER OF

    TERMS 3. INPUT N 4. PRINT ENTER A NUMBER 5. INPUT X 6. T = 1 7. S = 0 8. C = 1 9. S = S + T 10. T = T + X / C 11. C = C + 1 12. IF C

  • Flowchart It is a pictorial representation of the sequence of operations in a

    computer program.

    Standards for flowchart:

    Flowcharts must be drawn on white, unlined paper, on one side only.

    Flowcharts start on the top of the page and the flow down and to the right.

    Only standard flowcharting symbols should be used.

    English should be used in flowcharts, not programming language.

    The flowchart for each subroutine, if any, must appear on a separate page. Each subroutine begins with a terminal symbol with the subroutine name and a terminal symbol labeled return at the end.

    Draw arrows between symbols with a straight edge and use arrowheads to indicate the direction of the logic flow.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 37

  • Flowchart Symbols

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 38

  • Guidelines for flowcharts

    There should be a logical start and stop to the flowchart.

    The flowchart should be clear, neat and easy to follow. There should be no ambiguity in understanding the flowchart.

    The usual direction of the flow of a procedure or system is from left to right or top to bottom.

    Only one flow line should enter a decision symbol, but two or three flow lines, one for each possible answer, can leave the decision symbol.

    Only one flow line is used in conjunction with a terminal symbol.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 39

    False

    True

    START

    STOP

  • A sequence of steps or processes that are executed in a particular order is shown using process symbols connected with flow lines.

    Selection of a process or step is depicted by the decision making and process symbols.

    Iteration or looping is depicted by a combination of process and decision symbol.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 40

  • Draw a flowchart to find the sum of the first 50 natural numbers.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 41

  • Draw a flowchart to find the largest of three numbers A,B, and C.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 42

  • Draw a flowchart for computing N!.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 43

  • Draw a flowchart for calculating the simple interest using the formula SI = (P * R * N)/100, where P denotes the principal, T time and R rate of interest. Also write an algorithm for the same.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 44

  • The XYZ construction company plans to give a 5% year-end bonus to each of its employees earning Rs. 5,000 or more per year, and a fixed bonus of Rs. 250 to all other employees. Draw a flowchart and write the step-form algorithm for printing the bonus of any employee.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 45

  • Prepare a flowchart to read the marks of a student and classify them into different grades. If the marks secured are greater than or equal to 90, the student is awarded Grade A; if they are greater than or equal to 80, but less than 90, Grade B is awarded; if they are greater than or equal to 65 but less than 80, Grade C is awarded; otherwise Grade D is awarded.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 46

  • Draw a flowchart to find the roots of a quadratic equation.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 47

  • Draw a flowchart for printing the sum of even terms contained within the numbers 0 to 20.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 48

  • Advantages of using flowcharts

    Communication: Flowcharts are a better way of communicating the logic of a system to all concerned.

    Effective Analysis: With the help of flowcharts, problems can be analyzed more effectively.

    Proper Documentation: Program flowchart serves as a good program documentation needed for various purposes.

    Efficient coding: Flowchart act as a guide during the system analysis and program development phase.

    Proper Debugging: Flowcharts help in the process of debugging.

    Efficient program maintenance: The maintenance of an operating program becomes easy with the help of a flowchart.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 49

  • Limitations of using flowcharts

    Complex logic: Sometimes, the program logic is quite complicated. In such a case, a flowchart becomes complex and clumsy.

    Alterations and modifications: If alterations are required, the flowchart may need to be redrawn completely.

    Reproduction: Since the flowchart symbols cannot be typed in, the reproduction of a flowchart become a problem.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 50

  • 10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 51

    Chapter 2 : Basics of C

  • History of C Language

    C is a structured, high-level, machine independent language.

    The root of all modern languages is ALGOL, introduced in the early 1960s.

    ALGOL was the first computer language to use a block structure.

    In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language).

    In 1970, Ken Thompson created a language using many features of BCPL and called it B language.

    10/11/2012 53 Prepared By:Swaminarayan Priya, ISTAR

  • B was used to create early versions of UNIX operating system at Bell Laboratories.

    C was evolved from ALGOL, BCPL, and B by Dennis Ritchie at the Bell Laboratories in 1972.

    C uses many concepts from these languages and added the concepts of data types and other powerful features.

    C is strongly associated with UNIX operating system. UNIX is the one of the most popular network OS and the heart of the Internet data superhighway.

    In 1983, American National Standards Institute (ANSI) appointed a technical committee to define a standard for C.

    The committee approved a version of C in December 1989 which is known as ANSI C.

    It was approved by the ISO (International Standards Organization) in 1990, this version is referred as C89.

    10/11/2012 54 Prepared By:Swaminarayan Priya, ISTAR

  • During 1990s, C++, a language entirely based on C.

    C++ added several new features to C to make it not only a true object-oriented language but also a more versatile language.

    During the same period, Sun Microsystems of USA created a new language JAVA modeled on C And C++.

    10/11/2012 55 Prepared By:Swaminarayan Priya, ISTAR

  • Basic Structure of C Program Documentation Section Preprocessor Directive Block Definition Section Global Declaration Section main() Function Section {

    Declaration Part Executable Part } Subprogram Section Function 1 Function 2 . (User-defined Functions) . Function n

    10/11/2012 56 Prepared By:Swaminarayan Priya, ISTAR

  • Escape Sequence: It is used in printf statement to format the output.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 59

    Code Meaning

    \a Ring terminal bell (i.e. a for alert)

    \? Question Mark

    \b Backspace

    \r Carriage return

    \f Form feed

    \t Horizontal tab

    \v Vertical tab

    \0 ACSII Null character

    \\ Backslash

    \ Double quote

    \ Single quote

    \n New line

    \o Octal

    \x Hexadecimal constant

  • Character Set

    The characters that can be used to form words, numbers and expressions depend upon the computer on which the program is run.

    The characters in C are grouped into the following categories: Letters Digits Special Characters White space

    Note: The compiler ignores white spaces unless they are a part of a

    string constant. White spaces may be used to separate words, but are prohibited

    between the characters of keywords and identifiers.

    10/11/2012 60 Prepared By:Swaminarayan Priya, ISTAR

  • C Token

    In a passage of text, individuals words and punctuation marks are called tokens.

    Identifiers:

    An identifier is a sequence of characters invented by the programmer to identify a specific object.

    Rules for writing an identifier:

    It is case sensitive. Ie NUMBER, Number and number are different identifiers.

    The underscore should not be used as the first character of a variable name.

    A numeric digit should not be used as the first character of identifier.

    Identifier name should not be a keywords of C.

    Identifiers may be of any reasonable length; generally 8 to 10 characters should be suffice.

    10/11/2012 61 Prepared By:Swaminarayan Priya, ISTAR

  • Keywords

    10/11/2012 62 Prepared By:Swaminarayan Priya, ISTAR

    auto double int struct

    break else long switch

    case enum char Register

    union return extern Typedef

    const float short Unsigned

    continue for signed void

    default goto sizeof Volatile

    do if static while

  • Data Types of C

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 63

    Data Type

    Primitive/Basic Data Type 1. Character 2. Int 3. Float 4. double

    Derives Data Type 1. Array 2. Function 3. pointer

    User-defined Data Type 1. Structure 2. Union 3. enumerated

    Valueless Data Type 1. void

    Data type Size (bits) Range

    Char 8 (1 B) -128 to 127

    Int 16 (2 Bytes) -32768 to 32767

    Float 32 ( 4 Bs) 3.4E-38 to 3.4E+38

    Double 64 (8 Bs) 1.7E-308 to 1.7E+308

    Void 0 valueless

  • 10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 64

    Data type Format Specifier

    Size (bits) Range

    Char %c 8 (1 B) -128 to 127

    unsigned char %c 8 (1 B) 0 to 255

    signed char %c 8 (1 B) -128 to 127

    int %d 16 (2 Bytes) -32768 to 32767

    Unsigned int %u 16 (2 Bytes) 0 to 65535

    Signed int %d 16 (2 Bytes) -32768 to 32767

    Short int %hd or %hi 16 (2 Bytes) -32768 to 32767

    Unsigned short int %u 16 (2 Bytes) 0 to 65535

    Signed short int %hd 16 (2 Bytes) -32768 to 32767

    long int %ld 32 (4 Bytes) -2147483648 to 2147483647

    Unsigned long int %lu 32 (4 Bytes) 0 to 4294967295

    Signed long int %ld 32 (4 Bytes) -2147483648 to 2147483647

    Float %f 32 ( 4 Bs) 3.4E-38 to 3.4E+38

    Double %lf 64 (8 Bs) 1.7E-308 to 1.7E+308

    Long double %Lf 80 (10 Bs) 3.4E-4932 to 1.1E+4932

  • Constant

    It is a memory location whose value does not change during

    the program execution.

    EX:- PI=3.14

    Constants are defined inside the program by the programmer whereas the value of variable is read at the execution time and give by the user.

    How to declare constant?

    #define PI 3.14

    Or

    const float PI = 3.14;

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 65

  • Operator

    Unary Binary Ternary

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 66

    Arithmetic Assignment Equality Relational Logical Bitwise

  • In C, the assignment operator is the equal sign = and is used to give a variable the value of an expression.

    For example: i=0; x=34.8; sum=a+b; slope=tan(rise/run); midinit='J'; j=j+3;

    Assignment Operator

    10/11/2012 67 Prepared By:Swaminarayan Priya, ISTAR

  • Sizeof() operator sizeof can be applied to types and objects; when used with an object, brackets are not

    needed. sizeof(char) is always 1. Syntax is: int i; i = sizeof(int); i will be set to 2, assuming a 16 bit system. The result of sizeof is the amount of data used for an object in multiples of char. void main() { printf(char size = %d bytes\n,sizeof(char)); printf(short size = %d bytes\n,sizeof(short)); printf(int size = %d bytes\n,sizeof(int)); printf(long size = %d bytes\n,sizeof(long)); printf(float size = %d bytes\n,sizeof(float)); printf(double size = %d bytes\n,sizeof(double)); printf(1.55 size = %d bytes\n,sizeof(1.55)); printf(1.55L size = %d bytes\n,sizeof(1.55L)); printf(Hello size = %d bytes\n,sizeof(Hello)); }

    10/11/2012 68 Prepared By:Swaminarayan Priya, ISTAR

    Char size = 1 bytes Short size = 2 bytes Int size = 2 bytes Long size = 4 bytes Float size = 4 bytes Double size = 8 bytes 1.55 size = 8 bytes 1.55L size = 10 bytes Hello size = 6 bytes

    Note: In string, sizeof counts Null character also) 1.55 is float number but internally TC converts this float number into double, and double needs 8 bytes

  • Arithmetic Operators

    * multiplication

    / division

    % remainder after division (modulo arithmetic)

    + addition

    - subtraction and unary int main()

    {

    float a;

    a = 1 / 3; 0.3333333

    printf("%f\n", a);

    return 0;

    }

    would print 0.000000 as integer division was performed even though a is of type

    float.

    The / operator is used for two different operations: integer and floating point

    division.

    If both operands of the divide operator are of integral (char, int and its derivatives) type then integer division is performed.

    If either operand is float ,double or long double then real division is undertaken.

    10/11/2012 69 Prepared By:Swaminarayan Priya, ISTAR

  • 10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 70

    Arithmetic operator :

    +,-,*,/,%(modules)

    % (Modules) operator is used to find the reminder after division.

    EX : 20%8 will generate result 4(reminder).

    The sign of result will be the same as sign of first operand (data).

    Only integer values can be given with % operator, float and double type data can not be supported.

    Operator Name Example

    + Addition 12 + 4.9 = 16.9

    - Subtraction 3.98 4 = -0.02

    * Multiplication 2 * 3.4 = 6.8

    / Division 9 / 2.0 = 4.5

    % Remainder 13 % 3 = 1

    9 / 2 = 4

    -9/2 = -4

    printf((%d\n,-5%-2); printf((%d\n,-5%2); printf((%d\n,5%-2); printf((%d\n,5%2);

    -1 -1 1 1

  • Increment and Decrement Operators

    Increment and decrement operators give a shorthand method of adding/subtracting 1 from an object.

    ++ increment

    -- decrement

    These operators can be prefix or postfix. An example of the different behavior of the prefix and postfix forms is given below, but essentially with the prefix form the variable is changed before the value of the expression in which it appears is evaluated, and with the postfix form the variable is modified afterwards.

    b = 3;

    a = b++ + 6; /* a = 9, b = 4 */

    b = 3;

    a = ++b + 6; /* a = 10, b = 4 */

    10/11/2012 71 Prepared By:Swaminarayan Priya, ISTAR

  • Comma Operator

    Syntax:

    expressionM = (expression1, exp2, .. , exp n);

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

    A comma-linked list of expressions are evaluated left to right and value of the right-most expression is the value of the combined expression.

    For e.g.

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

    for ( n = 1, m = 10, n

  • Relational Operator

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 73

    Operator Action Example

    == Equal 5 == 5 ( result 1)

    != Not equal 5 != 5 ( result 0)

    < Less than 5 < 5.5 ( result 1)

    5.5 ( result 0)

    >= Greater than equal

    6.3 >= 5 ( result 1)

  • Logical Operator

    Operator Action Example Result

    ! Logical Negation ! ( 5 == 5) 0

    && Logical AND 5 < 6 && 6 < 6 0

    || Logical OR 5 < 6 || 6

  • Conditional Operator It is ternary operator.

    It has the general form:

    Expression1 ? Expression2 : expression3

    First expression1 is evaluated; if the result is non-zero, then expression2 is evaluated and its value is the final result. Otherwise, expression3 is evaluated and its value is the final result.

    For example,

    If ( m < n) min=m; else min = n;

    Min = (m

  • void main()

    {

    int a=5,b=3;

    printf(%d, ++(a*b+2));

    }

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 76

    void main()

    {

    printf(%d, ++2);

    }

    Compiler error Lvalue required Compiler error Lvalue required

  • Bitwise Operator

    Operator Action

    ~ Bitwise Negation

    & Bitwise AND

    | Bitwise OR

    ^ Bitwise Exclusive OR

    > Bitwise Right Shift

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 77

    Generally character, integer, float etc operate with a byte. But if we want to interact directly with the computer hardware then we must have to work at bit level. This is possible only through Bitwise Operators. One of the powerful feature is a set of bit manipulation operators. Those permit user to access and manipulate individual bits within a piece of data.

    These operators can operate upon int or char but not on float and double.

  • 1s Complement Operator:

    Here all 1s present in the number are changed to 0s and all 0s are changed to 1s.

    Eg. A = 1010 then ~A = 0101

    This operator is effectively useful in development of encryption facility.

    Right Shift Operator:

    Here >> operator shifts each bit in the operand to the right. The number of places the bits are shifted depends on the number following the operand.

    E.g. 1101 0111 >> 3 0 110 1011 - 1 time

    00 11 0101 - 2 time

    000 1 1010 - 3 time

    Note: Result of right shift operator is same as operand1 / 2.

    64 >> 2 = 64/2 = 32 >> 2 = 32/2 = 16 >> 2 = 16/2 = 8

    27 >> 1 i.e. 27 / 2 = 13

    49 >> 1 i.e. 49/2 = 24

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 78

  • Lift Shift Operator
  • Bit wise AND operator : &

    It operates on two operands.

    While operating upon these two operands they are compared on a bit by bit basis.

    Here both the operands must be of the same type (either char and int)

    E.g. 2 & 3

    0000 0010 2

    0000 0011 3

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

    0000 0010 2

    Bit wise OR operator : |

    E.g. 2 | 3

    0000 0010 2

    0000 0011 3

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

    0000 0011 3

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 80

  • Bit wise XOR operator : ^

    The XOR returns 1, when any one of the two bits or both the bits are 0. But XOR returns 1 only if one of the two bit is 1.

    E.g. 2 | 3

    0000 0010 2

    0000 0011 3

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

    0000 0011 3

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 81

  • Expressions and Statements

    An expression in C is some combination of constants, variables, operators and function calls.

    Sample expressions are: a + b 3.0*x - 9.66553 tan(angle) Most expressions have a value based on their contents. A statement in C is just an expression terminated with a

    semicolon. For example: sum = x + y + z; printf("Go Buckeyes!");

    10/11/2012 82 Prepared By:Swaminarayan Priya, ISTAR

  • Operator Precedence Chart

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 83

    Operator Type Operator Associativity

    Primary Expression Operators

    () [] . -> expr++ expr-- left-to-right

    Unary Operators * & + - ! ~ ++expr --expr (typecast) sizeof

    right-to-left

    Binary Operators

    * / %

    left-to-right

    + -

    >> =

    == !=

    &

    ^

    |

    &&

    ||

    Ternary Operator ?: right-to-left

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

  • X = 2 * 3 + 4 * 5;

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 84

    Answer : X = 26

    X = 2 * ( 3 + 4 ) * 5;

    Answer: X = 70

    X = 7*6 % 15/9;

    Answer: X = 1

    X = 7 * ( 6 % 15) / 9;

    Answer: X = 4

    X = 7 * 6 % (15 / 9);

  • Automatic Type Conversion with Assignment Operator

    Automatic conversion even takes place if the operator is the assignment operator. This creates a method of type conversion.

    For example, if x is double and i an integer, then

    x=i;

    i is promoted to a double and resulting value given to x

    10/11/2012 85 Prepared By:Swaminarayan Priya, ISTAR

  • Type Conversion in C

    When a C expression is evaluated, the resulting value has a particular data type. If all the variables in the expression are of the same type, the resulting type is of the same type as well.

    For eg.,if x and y are both of int type, the expression x + y is of int type as well.

    The smallest to the largest data types with respect to size are given as follows:

    Char -> int -> long -> float -> double

    1 byte -> 2 B -> 4 B -> 4 B -> 8 B

    Thus, an expression containing an int and a char evaluates to type int.

    An expression containing a float and a long evaluates to type float.

    10/11/2012 86 Prepared By:Swaminarayan Priya, ISTAR

  • Note: within expressions, individual operands are promoted as necessary to match the associated operands in the expression.

    If both operands are of the same type, promotion is not needed. If they are not, promotion follows these rules:

    Float operands are converted to double.

    Char or short (signed or unsigned) are converted to int (signed or unsigned).

    short

    int

    Unsigned int

    Long int

    Unsigned long int

    float

    double

    Char

    Long double

    10/11/2012 87 Prepared By:Swaminarayan Priya, ISTAR

  • Conversion by Assignment Promotion also occur with the assignment operator. The expression on the

    right side of an assignment statement is always promoted to the type of the data object on the left side of the assignment operator.

    For eg. Char c; Int j; Float f; Double d, r; R = (c * j) + (f / j) ( f + d); R = ( char * int ) + ( float / int ) ( float + double) R = double

    10/11/2012 88 Prepared By:Swaminarayan Priya, ISTAR

  • Type Casting

    The opposite of promotion, truncation moves a value from a particular type to a smaller type.

    In this case, the compiler just drops the extra bits. It may or may not generate a compile time warning for the loss of the information.

    For example, (double) I will force i to be of type double. The general syntax is (type) expression Some examples, x = (float) 77; (double) k * 57

    10/11/2012 89 Prepared By:Swaminarayan Priya, ISTAR

  • Char ch;

    Int I;

    I = 321;

    Ch = I; /* truncation of an int value to fit in a char */

    0000 0001 0100 0001 Content of i Binary equivalent of 321

    0100 0001 Content of ch after ch = I statement is executed

    Binary equivalent of 65

    Double pi; Int I ; Pi = 3.14159; I = pi; printf(d,i);

    10/11/2012 90 Prepared By:Swaminarayan Priya, ISTAR

  • 1: Which of the following is an incorrect assignment statement.

    a) N = m = 0

    b) mySize = x < y ? 9 : 11

    c) Value += 10

    d) testVal = ( x> 5 || x < 0)

    e) None of the above

    1: What will be the output:

    a) Int main()

    {

    float c = 3.14;

    printf(%f,c%2);

    return(0);

    }

    2: What will be the output:

    a) Int main()

    {

    printf(%d,A);

    return(0);

    }

    3 What will be the output:

    a) Int main()

    {

    double d = 1/2.0 1/2

    printf(%f, d);

    return(0);

    }

    10/11/2012 91 Prepared By:Swaminarayan Priya, ISTAR

    E- None of the above

    Floating point cannot be used with % operator

    Answer: 65

    0.500000

  • 4 What will be the output:

    a) Int main()

    {

    char c = A;

    printf(%c, c + 10);

    return(0);

    }

    5 What will be the output:

    a) Int main()

    {

    printf(Work Hard);

    return(0);

    }

    5 What will be the output:

    a) Int main()

    {

    int c = --2;

    printf(c = %d,c);

    return(0);

    }

    5 What will be the output:

    a) Int main()

    {

    int c = - -2;

    printf(c = %d,c);

    return(0);

    }

    10/11/2012 92 Prepared By:Swaminarayan Priya, ISTAR

    Answer: K

    Answer: WorkHard

    Answer: Lvalue required.

    Answer: c = 2

  • 8 What will be the output:

    a) Int main()

    {

    int a = 5,i;

    i = !a > 10;

    printf(I =` %d, i);

    return(0);

    }

    9 What will be the output:

    a) Int main()

    {

    printf(\nab);

    printf(\bsi);

    printf(\rha);

    return(0);

    }

    \n newline

    \b backspace

    \r - linefeed

    10 What will be the output:

    a) Int main()

    {

    int i = 5;

    printf(%d%d%d, i++,I,++i);

    return(0);

    }

    10/11/2012 93 Prepared By:Swaminarayan Priya, ISTAR

    Answer: 0

    8 What will be the output:

    a) Int main()

    {

    int a = 5,i;

    i = !(a > 10);

    printf(I =` %d, i);

    return(0);

    }

    Answer = 1

    Answer: 6 6 6

    10 What will be the output:

    a) Int main()

    {

    int i = 5;

    printf(%d%d%d, i++,i,i++);

    return(0);

    }

    6 6 5

  • 12 What will be the output:

    a) Int main()

    {

    int a = 5;

    printf(%d%d%d, ++i,++i,++i);

    return(0);

    }

    13 What will be the output:

    a) Int main()

    {

    int a = 5;

    a = printf(Good) + printf(Bye);

    printf(a = %d,a);

    return(0);

    }

    14 What will be the output:

    a) Int main()

    {

    int a = 5;

    printf(%d,scnaf(%d,&i));

    return(0);

    }

    15 What will be the output:

    a) Int main()

    {

    char n;

    n = !2;

    printf(%dn);

    return(0);

    }

    10/11/2012 94 Prepared By:Swaminarayan Priya, ISTAR

    8 7 6

    7

    2 Note: scanf returns total no of variables read by that statement.

    0

  • 16 What will be the output:

    a) Int main()

    {

    char n;

    n = !0;

    printf(%d,n);

    return(0);

    }

    17 What will be the output:

    a) Int main()

    {

    int I = -2

    printf(-I = %d \n,-i);

    return(0);

    }

    18 What will be the output: a) Int main() { int x = 10,y=15,a,b; a = x++; b = ++y; printf(%d%d \n,a,b); return(0); }

    19 What will be the output: a) Int main() { int x = 10,y=15,a,b; x = x++; y = ++y; printf(%d%d \n,x,y); return(0); }

    10/11/2012 95 Prepared By:Swaminarayan Priya, ISTAR

    1

    2

  • 20 What will be the output:

    a) Int main()

    {

    int x = 10,y=15;

    printf(%d,++(x+y));

    return(0);

    }

    21 What will be the output:

    a) Int main()

    {

    int x = 1,y=5;

    printf(%d,++x+y);

    return(0);

    }

    22 What will be the output: int a =8, b = 3, x1,x2,x3,x4; X1 = a*b x2 = a/b X3 = a%b x4 = a && b printf(%d,x1); printf(%d,x2); printf(%d,x3); printf(%d,x4);

    23 What will be the output: a) Int main() { int a = 7, b = 2; float c; c = a/b; printf(%f,c); return(0); }

    10/11/2012 96 Prepared By:Swaminarayan Priya, ISTAR

    Lvalue Required

    26

    X1 = 24 x2 = 2 x3 = 2 x4 = 1

    3.000000

  • Chapter 3 Input and Output

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 97

  • Basic Screen & Keyboard I/O in C

    Following are standard files or streams: 1. stdin: connected to the keyboard. 2. stdout: connected to the screen 3. stderr: connected to the screen Following are two data streams available on MS-DOS based

    computers, but not on UNIX or other multi-user based operating system:

    1. stdaux: connected to the first serial communications port 2. stdprn: connected to the first parallel printer port The header file contains the various declarations

    necessary for the functions. The input/output functions fall into two categories: non-

    formatted read (input) and display (output) functions and formatted input/output functions.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 98

  • Non-formatted Input and Output

    It can handle one character at a time.

    For the input functions it doesnt require key to be pressed after the entry of the character.

    For the output functions, it prints the single character on the console.

    Single character Input:

    The getchar() input function reads an unsigned char from the input stream stdin. And convert it into int, which is the return value.

    Syntax:

    char_variable = getchar();

    For e.g.

    int ch;

    ch = getchar();

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 99

  • Single Character Output: The putchar() function writes a character to the stdout data stream. It returns

    the character, On error, putchar() returns EOF. Syntax: putchar(char_variable); Where char_variable is the name of the variable that is of type char. For e.g. int ch; ch = getchar(); putchar(); Additional Single Character Input and Output Functions: getch() This input function reads, without echoing on the screen, a single

    character from the keyboard and immediately returns that character to the program.

    ch = getch(); // ch is a character variable. getche() This input function reads, with echo on the screen, a single

    character from the keyboard and immediately returns that character to the program.

    ch = getche(); // ch is a character variable.

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 100

  • Void main()

    {

    char ch;

    ch = getch();

    putch(ch);

    }

    Output: a

    Void main()

    {

    char ch;

    ch = getche();

    putch(ch);

    }

    Output: aa

    10/11/2012 101 Prepared By:Swaminarayan Priya, ISTAR

  • Input and Output

    putch() This output function writes the character directly to the screen.

    On the success, putch() returns the character printed, on error, it returns EOF.

    putch(ch); // ch is a character variable.

    10/11/2012 102 Prepared By:Swaminarayan Priya, ISTAR

  • Example -1 : Display a given character

    void main()

    {

    int ch;

    ch = 'A';

    putchar(ch);

    }

    // Output: A

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 103

    Example 2: Display a keyed-in character. void main() { int ch; clrscr(); ch = getchar(); putchar(ch); } Input: Z Output: Z

    void main() { int ch; ch = getchar(); ch++; putchar(ch); }

    Example 3: Accept a character and display the next character from the ASCII table Input: A Output: B

    Example 4: Double output of next two characters from the ASCII table. Input: a Output: bbcc

    void main() { int ch; ch = getchar(); ch++; putchar(ch); putchar(ch); ch++; putchar(ch); putchar(ch); }

  • 10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 104

    void main()

    {

    char ch;

    ch = getchar();

    ch = ch - 32;

    putchar(ch);

    }

    Read small letter and convert it into upper letter. Input: a Output: A

    Compare two numbers:

    void main() { char ch1, ch2; clrscr(); ch1 = getchar(); ch2 = getchar(); ch1 == ch2 ? printf("Equal") : printf("Not Equal"); }

  • Convert Upper letter to lower cases

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 105

    void main() { int ch,ch1; ch = getchar(); if (ch >= A' && ch

  • gets() it is used to read string from keyboard.

    puts() it is used to print string on the monitor.

    Note: All above functions require the header file to be included.

    10/11/2012 106 Prepared By:Swaminarayan Priya, ISTAR

  • Specifier Type %c character %d decimal integer %o octal integer (leading 0) %x hexadecimal integer (leading 0x) %u unsigned decimal integer %ld long int %f floating point %lf double or long double %e exponential floating point %s character string

    10/11/2012 108 Prepared By:Swaminarayan Priya, ISTAR

  • Formatting the output in printf()

    We can control how many columns will be used to output the contents of a particular variable by specifying the field width.

    The desired field width is inserted in the format specifier after the % and before the letter code indicating the data type.

    % Flag Min.Width Precision size ConversionCode

    Here, % sign and conversion code are required but the other modifiers such as width and precision are optional.

    The width modifier specifies the total no. of characters used to display the value.

    The precision indicates the no. of characters used after the decimal points. But it is used only with the floats and strings.

    When it is used with float, the precision indicates how many digits should be printed after the decimal point.

    If the precision is not specified, the default value of 6 is assumed.

    10/11/2012 109 Prepared By:Swaminarayan Priya, ISTAR

  • printf(number=%3d\n,10);

    printf(number=%2d\n,10);

    printf(number=%1d\n,10); 10

    printf(number=%7.2f\n,5.4321);

    printf(number=%.2f\n,5.4391); 5.44

    printf(number=%.9f\n,5.4321);

    printf(number=%f\n,5.4321);

    1 0

    1 0

    1 0

    5 . 4 3

    5 . 4 4

    5 . 4 3 2 1 0 0 0 0 0

    5 . 4 3 2 1 0 0

    10/11/2012 110 Prepared By:Swaminarayan Priya, ISTAR

  • printf(number=%06.1f\n,5.5);

    printf(number=%-+6.1f\n,5.5);

    printf(%-6.3f\n,17.23478);

    Note: Default justification for string and number is right but if - flag is used then it will be left justified.

    Flag Meaning

    - Left justify the display

    + Display positive or negative sing of value

    Space Display space if there is no sign

    0 Pad with leading zero

    # Use alternate form of specifier

    0 0 0 5 . 5

    + 5 . 5

    1 7 . 2 3 5

    10/11/2012 111 Prepared By:Swaminarayan Priya, ISTAR

  • Void main()

    {

    printf(%s,hello);

    printf(%3s,hello);

    printf(%10s,hello);

    printf(%-10s,hello);

    printf(%10.3s,hello);

    }

    h e l l o

    h e l l o

    H E L L o

    H E L L O

    H E L

    10/11/2012 112 Prepared By:Swaminarayan Priya, ISTAR

  • Flag with format specifier

    Action

    %#0 Adds a leading 0 to the octal number printed

    %#x or X Adds a leading Ox or OX to the hex number printed

    %#f or e Ensures that the decimal point is printed

    %#g or G Display trailing zeros in g or G type conversion and ensures decimal point is printed in floating-point number, even though it is a whole number. Void main()

    { int x = 20; printf(Octal value of %d = %o,x,x); o/p: Octal value of 20 = 24 printf(Hexa value of %d = %x,x,x); o/p: Hexa value of 20 = 14 printf(Octal value of %d = %#o,x,x); o/p: Octal value of 20 = 024 printf(Hexa value of %d = %#x,x,x); o/p: Hexa value of 20 = 0X14 }

    10/11/2012 113 Prepared By:Swaminarayan Priya, ISTAR

  • 10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 114

    float f=12; printf(%f,f); o/p: 12.000000 printf(%#f,f); o/p: 12.000000 printf(%e,f); o/p: 1.200000e+01 printf(%g,f); o/p: 12 printf(%#g,f); o/p: 12.0000 f = 122 printf(%#g,f); o/p: 122.000 F = 1223 printf(%#g,f); o/p: 1223.00 F = 12345 printf(%#g,f); o/p: 12345.0 F = 123456 printf(%#g,f); o/p: 123456. F = 1234567 printf(%#g,f); o/p: 1.23457e+06

  • 10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 115

    void main() { float p = 3.123456,q=1.12,r=123; clrscr(); printf("%f %f %f",p,q,r); printf("\n%g %g %g",p,q,r); printf("\n%#g %#g %#g",p,q,r); }

    Output: 3.123456 1.120000 123.000000 3.12346 1.12 123 3.12346 1.12000 123.000

    If #g is used then it will display number within 7 positions.

  • 10/11/2012 116 Prepared By:Swaminarayan Priya, ISTAR

  • Control Code Action

    \b Backspace

    \f Form feed

    \n New line

    \r Line feed

    \t Horizontal tab

    \ Single quote

    \0 null

    Sample output: printf(Hello world) o/p: Hello world Int i1=2,i2=3; printf(sum is %d,i1+i2); o/p: sum is 5 printf(%3d\n%3d\n%3d\n,5,25,125); o/p: 5 25 125 PI = 3.1415926535 Printf(%4.2f,pi); o/p: 3.14 Char color*10+ = red; printf(Color is %s,color); o/p: Color is red printf(Color is %10s,color); o/p: Color is red printf(Color is %-10s,color); o/p: Color is red

    10/11/2012 117 Prepared By:Swaminarayan Priya, ISTAR

  • Input function scanf()

    The scanf() function works in much the same way as the printf(). General form of scanf() statement is, scanf(control_string,var1_address, var2_address,);

    Where the control string is also known as format string is a list of

    format specifiers indicating the format and type of data to be read from the standard input device.

    There must be the same no of format specifiers and addresses as there are input fields.

    scanf(%d%d%d%c,&a,&b,&c,&x); Assume that the user wants a,b,c and x to be 1,2,3 and z. The user

    would have to type 1 2 3z If, instead, the user types 1 2 3 z then the value of x will be a space.

    If the user wants to be able to enter the line this way, the scanf ()

    needs to be coded as follows: scanf(%d%d%d %c,&a,&b,&c,&x);

    10/11/2012 118 Prepared By:Swaminarayan Priya, ISTAR

  • Note: Using spaces between integer field specifications is optional. For eg., while reading integers x,y and z

    scanf(%d%d%d,&a,&b,&c); Is equivalent to scanf(%d %d %d,&a,&b,&c);

    If a width modifier is used, it specifies the maximum no. of

    characters to be read.

    Then scanf() will read either as many characters as specified by the width modifier or until it sees white space.

    void main() {

    int no; scanf(%2d,&no); if input is 12345 printf(%d,no); output is only 12 no++; 13 printf(%d,no); output is 13

    }

    10/11/2012 119 Prepared By:Swaminarayan Priya, ISTAR

  • Void main() { int a,b,c; int num; num = scanf(%d%d%d,&a,&b,&c); printf(I have read %d values \n,num); } Suppose Input = 10 20 30 Then O/p = I have read 3 values. If Input = 10 20 hello Then O/p = I have read 2 values. If Input = hello 10 20 30 Then O/p = I have read 0 values.

    10/11/2012 120 Prepared By:Swaminarayan Priya, ISTAR

  • void main()

    {

    int x;

    scanf(You typed %d\n,x); }

    Note: In scanf() statement, the format string should never end with a new line character.

    10/11/2012 121 Prepared By:Swaminarayan Priya, ISTAR

  • Print formatted number.

    /123/

    /123_-_-_-_/

    /-_-_-_-123/

    void main() { printf(%d,123); printf(%-10d,123); printf(%10d,123); }

    10/11/2012 122 Prepared By:Swaminarayan Priya, ISTAR

  • Print formatted floating-point number

    /1234.560000/

    /1.234560e+03/

    /1235/

    /1234.6/

    /1234.560_-/

    /_-1234.560/

    /_1.235e+03/

    Void main() { printf(%f\n,1234.56); printf(%e\n,1234.56); printf(%4.f\n,1234.56); printf(%6.1f\n,1234.56); printf(%-10.3f\n,1234.56); printf(%10.3e\n,1234.56); } 10/11/2012 123 Prepared By:Swaminarayan Priya, ISTAR

  • #define test Outstanding Program!

    Void main()

    { printf(/%2s/\n,test);

    printf(/%22s/\n,test);

    printf(/%22.5s/\n,test);

    printf(/%-22.5s/\n,test);

    }

    /Outstanding Program!/ / Outstanding Program!/ / Outst/ /Outs /

    10/11/2012 124 Prepared By:Swaminarayan Priya, ISTAR

  • Chapter: 4

    Control Statements

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 126

  • Control Statement Statement: A statement is a syntactic construction that performs an action

    when a program is executed.

    Statement blocks: In C, any sequence of statements can be grouped together to function as a syntactically equivalent single statement by enclosing the sequence in braces. These groupings are called statement blocks.

    Categories of statement:

    Assignment Statement: here values, sometimes the results of calculations, are stored in variables.

    Input/Output statement: here the data is read in or printed out.

    Control Statement: through which the program makes a decision about what to do next.

    C has two types of Control structures: selection (decision) and repetition (loop).

    10/11/2012 127 Prepared By:Swaminarayan Priya, ISTAR

  • Selection or Branching statement:

    Sometimes it is desirable to alter sequential flow of Control to provide for a choice of action.

    Used to have a program execute different statements depending on certain conditions. In a sense, makes a program smarter by allowing different choices to be made.

    In C, there are three decision making statements.

    1. if execute a statement or not

    2. if-else choose to execute one of two statements

    3. switch choose to execute one of a number of statements

    10/11/2012 128 Prepared By:Swaminarayan Priya, ISTAR

  • Iteration or Loop statements:

    A loop is simply a statement or a collection of statements that is executed repetitively until a certain condition is reached after which execution moves to the next executable statement.

    In C language, loops are for, while and do-while

    10/11/2012 129 Prepared By:Swaminarayan Priya, ISTAR

  • Program control statements

    if

    Conditional Type

    Iteration/Looping Selection/ Branching

    Unconditional Type while for

    switch If-else If-else-if

    Do -while

    Goto break continue

    10/11/2012 130 Prepared By:Swaminarayan Priya, ISTAR

  • We can specify the condition for selection and iteration by using relational and logical operators.

    Syntax for writing test condition

    Var/exp/const OPERATOR var/exp/const

    10/11/2012 131 Prepared By:Swaminarayan Priya, ISTAR

  • Selection Statements

    Three versions of selection statements:

    1. One-way decisions using if statement

    2. Two-way decisions using if statement

    3. Multi-way decisions using if statement

    The if statement allows branching (decision making) depending upon a condition. Program code is executed or skipped.

    The basic syntax is if (control expression)

    program statement;

    If the control expression is TRUE, the body of the if is executed. If it is FALSE, the body of the if is skipped.

    There is no then keyword in C!

    10/11/2012 132 Prepared By:Swaminarayan Priya, ISTAR

  • Theses code fragments illustrate some uses of the if statement

    Avoid division by zero if (x!=0)

    y/=x;

    Customize output

    if (grade>=90) printf("\nCongratulations!"); printf("\nYour grade is "%d",grade);

    Nested ifs

    if (letter>='A') if (letter>='Z') printf("The letter is a capital \n");

    10/11/2012 133 Prepared By:Swaminarayan Priya, ISTAR

  • Write a program that prints the largest among three numbers

    #include Void main() { int a,b,c,max; printf(enter three values\n); scanf(%d%d%d,&a,&b,&c); max = a; if (max>b) max=b; if (max>c) max=c; printf(Largest Number is %d,max); }

    START

    PRINT ENTER THREE NUMBERS

    INPUT A,B,C

    MAX = A

    IF B>MAX THEN MAX=B

    IF C>MAX THEN MAX=C

    PRINT LARGEST NUMBER IS, MAX

    STOP

    10/11/2012 134 Prepared By:Swaminarayan Priya, ISTAR

  • TWO-WAY DECISIONS USING IF-ELSE STATEMENT

    Used to decide between two courses of action. The syntax of the if-else statement is

    if (expression) statement1; else statement2;

    If the expression is TRUE, statement1 is executed; statement2 is skipped. If the expression is FALSE, statement2 is executed; statement1 is skipped. Some examples

    if (x

  • Write a program in C to check whether a number given by the user is odd or even

    Void main()

    {

    int n;

    printf(enter any number);

    scanf(%d,&n);

    if (n%2 == 0)

    printf(EVEN);

    else

    printf(ODD); }

    START

    PRINT ENTER ANY NUMBER

    INPUT N

    IF N/2 (Integer Division)

    PRINT EVEN

    ELSE

    PRINTF ODD

    STOP

    10/11/2012 136 Prepared By:Swaminarayan Priya, ISTAR

  • Check whether the two given numbers are equal.

    Void main() { int a=2, b=3; if ( a==b) printf(EQUAL); else printf(UNEQUAL); }

    Void main() { int a=2, b=3; if ( a=b) printf(EQUAL); else printf(UNEQUAL); }

    10/11/2012 137 Prepared By:Swaminarayan Priya, ISTAR

  • Multi-way decisions Syntax: if-else-if ladder If (TestExpr1) statement1; else if (TestExpr2) statement2; else if (TestExpr3) statement3; . . else if(TestExprN) statementN; else statementF As soon as a TRUE control expression is found, the statement associated with it is

    executed and the rest of the ladder is bypassed. If no control expressions are found to be TRUE, the final else statement acts as a default.

    Home work: Write a program that determines if a year is leap year

    10/11/2012 138 Prepared By:Swaminarayan Priya, ISTAR

  • For example, consider the following code if (letter == 'a') ++a_count; else if (letter == 'e') ++e_count; else if (letter == 'i') ++i_count; else if (letter == 'o') ++o_count; else if (letter == 'u') ++u_count; else ++const_count;

    10/11/2012 139 Prepared By:Swaminarayan Priya, ISTAR

  • Write a program to check whether a number given by the user is zero, +ve or ve.

    Void main() { int n; printf(enter any n); scanf(%d,&n); if (n>0) printf(n is positive); else if (n

  • Write a program to display grade >= 90 then A

    grade >= 80 and = 70 and = 60 and = 90)

    grade = A;

    else if (score >= 80)

    grade = A;

    else if (score >= 70)

    grade = A;

    else if (score >= 60)

    grade = A;

    else

    grade = F;

    } 10/11/2012 141 Prepared By:Swaminarayan Priya, ISTAR

  • Write a program to find the largest among three numbers using the nested loop.

    Void main()

    {

    int a,b,c;

    printf(enter three numbers);

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

    if (a>b)

    if (a>c)

    printf(%d,a);

    else

    printf(%d,c);

    else

    if (b>c)

    printf(%d,b);

    else

    printf(%d,c);

    } 10/11/2012 142 Prepared By:Swaminarayan Priya, ISTAR

  • What will be the output of the following programs?

    void main()

    {

    printf(Hi);

    if (-1)

    printf(Bye);

    }

    void main()

    {

    printf(Hi);

    if (!1)

    printf(Bye);

    }

    10/11/2012 143 Prepared By:Swaminarayan Priya, ISTAR

    Hi Bye Hi

  • void main() { float x =199.9; if (xc)

    if (c>b)

    printf(%d %d,d,c);

    else if (c>a)

    printf(%d %d,c,d);

    if (c>a)

    if (b

  • The Conditional Operator

    Syntax: expresson1 ? Expression2 : expression3;

    It is equivalent to

    If (expression1) Expression2

    Else Expression3;

    Find out Maximum from given three numbers m,n and p

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 145

    Find our maximum from given four numbers using conditional operator:

    Int a,b,c,d,e; e = a>b ? (a>c?(a>d?a:d):(c>d?c:d)):(b>c?(b>d?b:d):(c>d?c:d));

  • Switch statement

    The switch statement is a better way of writing a program which employs an if-else ladder.

    It is Cs built-in multiple branch decision statement.

    The syntax for the switch statement is as follows: switch (integer expression)

    {

    case constant1: statement1;

    break;

    case constant2: statement2;

    break;

    ...

    default: statement;

    }

    The keyword break should be included at the end of each case statement. In general, whenever a break statement is encountered in C, it interrupts the normal flow of control.

    In the switch statement, it causes an exit from the switch shunt. The default clause is optional. The right brace at the end marks the end of switch statement.

    10/11/2012 146 Prepared By:Swaminarayan Priya, ISTAR

  • The biggest defect in the switch statement is that cases do not break automatically after the execution of the corresponding statement list for the case label. Once the statement list under a case is executed, the flow of control continues down executing all the following cases until a break statement is reached.

    The break statement must be used within each case if one does not want the following cases to execute once one case is selected.

    When the break statement is executed within a switch, C executes the next statement outside the switch statement.

    10/11/2012 147 Prepared By:Swaminarayan Priya, ISTAR

  • Switch (ch)

    {

    case A: printf(You entered an A);

    break;

    case B: printf(You entered an B);

    break;

    default: printf(Illegal entry);

    break;

    }

    Switch (choice)

    {

    case 1: printf(You entered choice #1);

    break;

    case 2: printf(You entered choice #2);

    break;

    default: printf(Illegal entry);

    break;

    } 10/11/2012 148 Prepared By:Swaminarayan Priya, ISTAR

    In case, choice may be integer or character.

  • Switch (donationLevel) { case 1: printf(You donated over Rs. 1000); break; case 2: printf(You donated over Rs. 500); break; case 3: printf(You donated over R5. 250); break; case 4: printf(You donated over R5. 100); break; default: printf(Pls be a little more generous); break; } Switch (number)

    { case 1: case 3: case 5: case 7: case 9: printf( %d is an odd number., number); break; case 2: case 4: case 6: case 8: printf( %d is an odd number., number); break; default: printf(%d is a value not between or including 1 and 9,number); break; }

    A set of statements to execute can be grouped with more than one value of the variable as in the following example.

    10/11/2012 149 Prepared By:Swaminarayan Priya, ISTAR

  • Expression that follows the keyboard switch must evaluate to an integer or character, which is of integer type itself.

    The expression followed by each case must be a constant expression.

    No two case contents can be the same.

    The default is optional.

    Switch statement can include at most one default label. It may be coded anywhere but traditionally coded at the end.

    A C compiler must permit at least 257 case labels for a switch statement.

    10/11/2012 150 Prepared By:Swaminarayan Priya, ISTAR

  • switch (grade)

    {

    default:

    printf("F\n");

    break;

    case 1:

    printf("A\n");

    break;

    case 2:

    printf("B\n");

    break;

    case 3:

    printf("C\n");

    break;

    case 4:

    printf("D\n");

    break;

    }

    10/11/2012 151 Prepared By:Swaminarayan Priya, ISTAR

    Note: The default is optional. It can be anywhere in the switch statement

  • Write a program using a switch statement to check whether a number given by the user is odd or even.

    Void main() { printf(enter the number); scanf(%d,&n); switch (n%2) { case 0: printf(\n EVEN); break; case 1: printf(\n ODD); break; } }

    10/11/2012 152 Prepared By:Swaminarayan Priya, ISTAR

  • Write a program to carry out the arithmetic operations addition, subtraction, multiplication and division between two variables.

    Void main()

    {

    char op;

    float n1,n2;

    printf(Enter two numbers);

    scanf(%f %f %c,&n1,&n2,&op);

    switch(op)

    {

    case +: printf(%f\n,n1+n2);

    break;

    case -: printf(%f\n,n1-n2);

    break;

    case *: printf(%f\n,n1*n2);

    break;

    case /: if (n2 == 0)

    printf(division by zero error);

    else

    printf(%f\n,n1/n2);

    break;

    default: printf(Unknown Operator\n);

    break;

    }

    }

    10/11/2012 153 Prepared By:Swaminarayan Priya, ISTAR

  • Write a program that checks whether a character entered by the user is a vowel or not.

    Void main()

    {

    char ch;

    printf(Enter a character);

    scanf(%c,&ch);

    switch(ch)

    {

    case a:

    case A:

    case e:

    case E:

    case i:

    case I:

    case o:

    case O:

    case u:

    case U: printf(%c is a vowel,ch);

    break;

    default: printf(%c is not a vowel\n);

    }

    } 10/11/2012 154 Prepared By:Swaminarayan Priya, ISTAR

  • What will be the output of following code.

    Char ch=Y;

    Switch (ch)

    {

    case Y: printf(Yes/No);

    case N: printf(No/Yes);

    break;

    default: printf(Other);

    }

    Int ch = 3;

    Switch (ch)

    {

    default: printf(Default);

    case 1: printf(Choice1);

    break;

    case 2: printf(Choice2);

    break;

    }

    10/11/2012 155 Prepared By:Swaminarayan Priya, ISTAR

    Yes/No No/Yes Default

  • Program looping is often desirable in coding in any language to have the ability to repeat a block of statements a number of times.

    In C, there are statements that allow iteration of this type. Specifically, there are two classes of program loops -- unconditional and conditional.

    An unconditional loop is repeated a set number of times.

    In a conditional loop the iterations are halted when a certain condition is true. Thus the actual number of iterations performed can vary each time the loop is executed.

    Iteration and repetitive execution

    10/11/2012 156 Prepared By:Swaminarayan Priya, ISTAR

  • Iteration and repetitive execution

    The for loop is Cs form of an unconditional loop. The basic syntax of the for statement is,

    for (initialization expression; test expr; increment expr)

    program statement;

    Here is an example sum=0;

    for (i=0; i

  • Sample Loop: We can trace the execution of the sample loop as follows

    sum = 10; for (i=0; i

  • 10/11/2012 159 Prepared By:Swaminarayan Priya, ISTAR

  • Flowchart for FOR loop

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 160

  • Some general comments regarding the use of the for statement: Control expressions are separated by ; not ,

    If there are multiple C statements that make up the loop body,

    enclose them in brackets (USE INDENTATION FOR READABILITY) for (x=100; x!=65; x-=5) {

    z=sqrt(x);

    printf("The square root of %d is %f\n",x,z); }

    Control expressions can be any valid expression. Dont necessarily have to perform initialization, testing, and incrementation.

    Any of the control expressions can be omitted (but always need the two semicolons for syntax sake). product=1; for (i=1;i

  • Some general comments regarding the use of the for statement:

    Since test performed at beginning of loop, body may never get executed x=10; for (y=10;y!=x;++y) printf ("%d",y);

    Can string together multiple expressions in the for statement by separating them by commas for (x=1,y=5;x+y

  • Write a program to generate following patterns.

    If input = 3

    Output:

    1

    2 2

    3 3 3

    Void main() { int n,i,j; printf(enter n); scanf(%d,&n); for (i=1;i

  • Write a program to generate following patterns.

    If input = 3

    Output:

    1

    2 3

    4 5 6

    Void main() { int n,i,j,k=1; printf(enter n); scanf(%d,&n); for (i=1;i

  • Write a program to generate following patterns. input n=3 output 1 1 2 1 2 3

    #include

    #include

    void main()

    {

    int i,j,n;

    clrscr();

    printf("enterr n");

    scanf("%d",&n);

    for (i=1;i

  • void main()

    {

    int i,j,n,k=1;

    clrscr();

    printf("enterr n");

    scanf("%d",&n);

    for (i=n;i>=1;i--)

    {

    for (j=1;j

  • void main()

    {

    int i,j,n,k=1;

    clrscr();

    printf("enterr n");

    scanf("%d",&n);

    for (i=n;i>=1;i--)

    {

    k = 1;

    for (j=1;j

  • Input = 3 then Output = A B C D E F

    Input = 3 then Output = A B A C B A

    Input = 4 then Output = z z y z y x z y x w

    Input = 3 then Output = A B C D E F

    Input = 3 then Output =

    1 2 2

    3 3 3

    Input = 3 then

    Output =

    * * *

    * * *

    Input = 4 then Output = * * * * * * * * * * * *

    10/11/2012 168 Prepared By:Swaminarayan Priya, ISTAR

  • Input = 3 then Output = A B C D E F

    void main() { int i,j,k,n; char ch='A'; clrscr(); printf("enmter amu n"); scanf("%d",&n); for (i=1;i

  • Input = 3 then Output = A B A C B A

    void main()

    {

    int i,j,k,n;

    char ch='A',ch1;

    clrscr();

    printf("enmter amu n");

    scanf("%d",&n);

    for (i=1;i

  • Input = 4 then Output = z z y z y x z y x w

    void main()

    {

    int i,j,k,n;

    char ch='z',ch1;

    clrscr();

    printf("enter any number");

    scanf("%d",&n);

    for (i=1;i

  • /* Input = 3 then Output =

    1 2 2

    3 3 3 */

    void main()

    {

    int i,j,k,n,l,sp;

    k = 1;

    clrscr();

    printf("enter any number");

    scanf("%d",&n);

    sp = n;

    for (i=1;i

  • Input = 3 then

    Output =

    * * *

    * * *

    void main()

    {

    int i,j,k,n,l,sp;

    k = 1;

    clrscr();

    printf("enmter amu n");

    scanf("%d",&n);

    sp = n;

    for (i=1;i

  • Input = 4 then Output = * * * * * * * * * * * *

    void main()

    {

    int i,j,k,n,l,sp;

    k = 1;

    clrscr();

    printf("enmter amu n");

    scanf("%d",&n);

    sp = n-2;

    for (i = 1; i

  • while Loop

    The while loop provides a mechanism for repeating C statements while a condition is true.

    Its format is

    while(control expression)

    program statement;

    The while statement works as follows:

    1) Control expression is evaluated (entry condition)

    2) If it is FALSE, skip over the loop.

    3) If it is TRUE, loop body is executed.

    4) Go back to step 1

    10/11/2012 176 Prepared By:Swaminarayan Priya, ISTAR

  • Example while loop i=1; factorial=1; while (i
  • Write a while loop that accepts input from the keyboard until a negative number is entered and find average of all entered

    numbers.

    Void main() { int x = 1; int cnt = 0,sum=0; float avg=0; while ( x>= 0) { scanf(%d,&x); cnt = cnt + 1; sum = sum + x; } avg = sum / cnt; printf(Average value = %f,avg);

    }

    10/11/2012 178 Prepared By:Swaminarayan Priya, ISTAR

  • Write a program to find sum of digits

    Void main()

    {

    int no,r,sum=0;

    printf(enter any number\n);

    scanf(%d,&no);

    while ( no>0)

    {

    r = no % 10;

    sum = sum + r;

    no = no / 10; }

    printf(sum of digits %d,sum);

    }

    10/11/2012 179 Prepared By:Swaminarayan Priya, ISTAR

  • What will be the output of the following code

    Void main()

    {

    int c = 5;

    while (c)

    {

    printf(\t %d,c);

    c--;

    }

    }

    Void main()

    {

    int c = 5;

    while (c)

    {

    printf(\t %d,c);

    c = c - 2;

    }

    } Void main() { while (1) { printf(\t ISTAR); } }

    Void main() { while (0) { printf(\t ISTAR); } }

    10/11/2012 180 Prepared By:Swaminarayan Priya, ISTAR

  • Print the sum of the series 1+2+3+.. Up to n terms

    Void main()

    {

    int c, sum = 0, n;

    printf(enter the no.of terms\n);

    scanf(%d,&n);

    for (c=1;c

  • What will be the output of following code

    Void main()

    {

    int c;

    for (c=0;c++;c++)

    printf(%d,c);

    }

    Void main()

    {

    int c;

    for (c=0;++c;++c)

    printf(%d,c);

    }

    Void main()

    {

    int c;

    for (c=1;c

  • Is there any difference between the following for statements?

    For(x =1; x

  • What would be the output from the given program?

    Void main()

    {

    int i=9;

    for (i--; i--; i--)

    printf(%d,i);

    }

    7 5 3 1

    Void main()

    {

    int i=9;

    for (i--; i--; i--)

    printf(%d,i);

    }

    6 4 2

    10/11/2012 184 Prepared By:Swaminarayan Priya, ISTAR

  • Void main()

    {

    for (;printf(C););

    }

    It is an infinite loop and it will repeatedly print C

    Void main() { int I; for (i=5;--i;) printf(%d,i); }

    4 3 2 1

    10/11/2012 185 Prepared By:Swaminarayan Priya, ISTAR

  • Void main()

    {

    int I =3;

    for (i--; i

  • Do While Statement The do while statement is a variant of the while statement in which the

    condition test is performed at the bottom of the loop. This guarantees that

    the loop is executed at least once.

    The syntax of the do while statement is

    do

    {

    program statement;

    } while (control expression);

    and it works as follows

    1) The body of the loop is executed.

    2) The control expression is evaluated (exit condition).

    3) If it is TRUE, go back to step 1. If it is FALSE, exit loop.

    10/11/2012 187 Prepared By:Swaminarayan Priya, ISTAR

  • Flowchart of Do While statement

    10/11/2012 Prepared By:Swaminarayan Priya, ISTAR 188

  • Void main()

    {

    int c=5;

    while (c

  • Pre-test loop Post-test loop

    Initialization Once Once

    No. of tests N+1 N

    Actions executed N N

    Updating executed N N

    Minimum iteration Not even once At least once

    10/11/2012 190 Prepared By:Swaminarayan Priya, ISTAR

  • How many times will the following while-loop repeat?

    Int i=5;

    While (i-- > 0)

    printf(X);

    How many X are printed by the following code? Int I = 5; While (i-- > 0) printf(X); Printf(X);

    What does the following do-while loop print ? Int I = 0; Char c = 0; Do { putchar(c+i); ++I; } While (I < 5);

    What does the following while loop print ? Float s=1.0; Int a = 4; While (a

  • #define infiniteloop while(1)

    Void main()

    {

    infiniteloop;

    printf(DONE);

    }

    None becoz the infiniteloop in main ends with ;. So loop will reach an end, and DONE will not print

    10/11/2012 192 Prepared By:Swa