Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

C notes mca i sem 2011


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

C notes mca i sem 2011

  1. 1. Firmware "The combination of a hardware device and computer instructions and data that reside as read-only software on that device". Firmware is a term used to denote the fixed and small programs that internally control various electronic devices. Typical examples range from end user products such as remote controls or calculators, through computer parts and devices like harddisks, keyboards, TFT screens or memory cards, all the way to scientific instrumentation and industrial robotics. Also more complex consumer devices, such as mobile phones, digital cameras, synthesizers, etc., contain firmware to enable the devices basic operation as well as implementing higher level functions. Simple firmware typically reside in ROM or PROM, while more complex firmware often employ flash memory to allow for updates. Common reasons for updating firmware include fixing bugs or adding features to the device. Origin The term "firmware" was coined by Ascher Opler in a 1967 Datamation article.[1] Originally it meant the microcode contents of a writable control store (a specialized small area of RAM memory), which defined and implemented the machine instruction set of a computers CPU. The firmware could be reloaded if needed to specialize or modify the computers instruction set. As originally used firmware was contrasted with hardware (the CPU itself) and software (programs which ran on the CPU). It was not composed of CPU machine instructions, but of lower-level microcode involved in the implementation of machine instructions. It existed on the boundary of hardware and software, thus the term firmware. Later the term was broadened to include any microcode, whether in RAM or ROM. Still later, the term was again broadened in popular usage to denote anything ROM- resident, including processor machine instructions for BIOS, bootstrap loaders, or specialized applications. Applications Timing and control systems for washing machines. The BIOS found in IBM-compatible Personal Computers The platform code found on Intel-based Mac OS X machines Used in computers from Sun Microsystems, Apple Computer, and Genesi ARCS, used in computers from Silicon Graphics RTAS (Run-Time Abstraction Services), used in computers from IBM EPROM chips used in the Eventide H-3000 series of digital music processors
  2. 2.  The Common Firmware Environment (CFE) Controlling sound and video attributes as well as the channel list in modern TVs Decision table Decision tables are a precise yet compact way to model complicated logic. Decision tables, like if-then-else and switch-case statements, associate conditions with actions to perform. But, unlike the control structures found in traditional programming languages, decision tables can associate many independent conditions with several actions in an elegant way Decision Table Used 1. Show sets of conditions and the actions resulting from them when the logic can be easily expressed in a table format, for example, calculating discount rates 2. Verify completeness and consistency of a process involving different actions under different conditions. Decision Tables work better than Decision Trees for very complex or extensive sets of conditions. Structure The Decision Table is divided into four quadrants. The upper half lists the conditions being tested, the lower half lists the possible actions to be taken. Each column represents a certain type of condition or rule. The Four Quadrants Conditions Condition alternatives Actions Action entries Steps to Develop a Decision Table 1) Draw boxes for the top and bottom left quadrants. 2) List the conditions in the top, left quadrant. When possible, phrase the conditions as questions that can be answered with a Y for yes and an N for no. This type of
  3. 3. Decision Table is known as a limited entry table. When a Decision Table requiresmore than two values for a condition, it is known as an extended entry table.3) List the possible actions in the bottom, left quadrant.4) Count the possible values for each condition and multiply these together todetermine how many unique combinations of conditions are present. Draw onecolumn in the top and bottom right quadrants for each combination.For example, if there are two conditions and the first condition has two possiblevalues while the second has three possible values, draw six (2 * 3) columns.5) Enter all possible combinations of values in the columns in the top, right quadrantof the table.6) For each column (each unique combination of conditions), mark an X in thebottom, right quadrant in the appropriate action row. The X marks the intersectionbetween the required action and each unique combination of condition values.Ensure that the Table is CompleteTo complete Step 5 above, ensuring that no combinations are missed, follow thesesteps:1) Start with the last condition and alternate its possible values across the row. Notehow often the pattern repeats itself. For a condition with two possible values, thepattern repeats itself every two columns. If three values are possible, the patternrepeats itself every three columns.For example, for a table with three conditions each with values Y or N, there areeight (2 * 2 * 2) columns. Complete the third (last) row by entering Y once acrossthe row followed by one N. The pattern repeats itself every two columns.The third row would look like:YNYNYNYN2) Move to the condition in the row above the last condition. Cover each patterngroup with a value for this condition. Note how often the new pattern repeats itself.For example, complete the second row by entering Y across the row two timesfollowed by two entries of N. This pattern repeats itself every four columns. Thesecond row would look like:
  4. 4. YYNNYYNN3) Repeat step 2 until all rows are complete.To complete the first row, enter Y across the row four times followed by four entriesof N. The first row would look like:YYYYNNNNFlag Error ConditionsIf a specific combination of conditions is invalid, then define one action to flag theerror or invalid condition.How to Simplify the Decision TableIf two or more combinations result in the same action, then the table can besimplified. Consider the following example:Condition 1 Y YCondition 2 Y YCondition 3 Y NAction 1 X XThe same action occurs whether condition 3 is true or false. As a result, one columncan be eliminated from the table as follows:Condition 1 YCondition 2 YCondition 3 -Action 1 XExampleCompany X sells merchandise to wholesale and retail outlets. Wholesale customersreceive a two percent discount on all orders. The company also encourages bothwholesale and retail customers to pay cash on delivery by offering a two percentdiscount for this method of payment. Another two percent discount is given onorders of 50 or more units. Each column represents a certain type of order.
  5. 5. Decision Table Less than 50 Units Ordered Y Y Y Y N N N N Cash on Delivery Y Y N N Y Y N N Wholesale Outlet Y N Y N Y N Y N Discount Rate 0% X Discount Rate 2% X X X Discount Rate 4% X X X Discount Rate 6% XThe Decision Table records the conditions for discounts in the top left quadrantalong with the ranges for the conditions in the top right quadrant. The bottom half ofthe table lists the actions taken, i.e., the discount rates that apply, based on theconditions. Each column represents a certain type of order. For example, columntwo represents cash on delivery orders of less than 50 units from retailers. FlowchartsA flowchart is a diagrammatic representation that illustrates the sequence ofoperations to be performed to get the solution of a problem. Flowcharts aregenerally drawn in the early stages of formulating computer solutions. Flowchartsfacilitate communication between programmers and business people. Theseflowcharts play a vital role in the programming of a problem and are quite helpful inunderstanding the logic of complicated and lengthy problems. Once the flowchart isdrawn, it becomes easy to write the program in any high level language. Often wesee how flowcharts are helpful in explaining the program to others. Hence, it iscorrect to say that a flowchart is a must for the better documentation of a complexprogram.Advantages of Using Flowchart1).Communication: Flowcharts are better way of communicating the logic of asystem to all concerned.2).Effective analysis: With the help of flowchart, problem can be analysed in moreeffective way.
  6. 6. 3).Proper documentation: Program flowcharts serve as a good programdocumentation, which is needed for various purposes.4).Efficient Coding: The flowcharts act as a guide or blueprint during the systemsanalysis and program development phase.5).Proper Debugging: The flowchart helps in debugging process.6).Efficient Program Maintenance: The maintenance of operating program becomeseasy with the help of flowchart. It helps the programmer to put efforts moreefficiently on that part.Limitations of Using Flowcharts1).Complex logic: Sometimes, the program logic is quite complicated. In that case,flowchart becomes complex and clumsy.2).Alterations and Modifications: If alterations are required the flowchart may requirere-drawing completely.3).Reproduction: As the flowchart symbols cannot be typed, reproduction offlowchart becomes a problem.4).The essentials of what is done can easily be lost in the technical details of how itis done. Flowchart SymbolsFlowcharts use special shapes to represent different types of actions or steps in aprocess. Lines and arrows show the sequence of the steps, and the relationshipsamong them.Start/EndThe terminator symbol marks the starting or ending point of the system. It usuallycontains the word "Start" or "End."Action or ProcessA box can represent a single step ("add two cups of flour"), or and entire sub-process ("make bread") within a larger process.DocumentA printed document or report.
  7. 7. DecisionA decision or branching point. Lines representing different decisions emerge fromdifferent points of the diamond.Input/OutputRepresents material or information entering or leaving the system, such ascustomer order (input) or a product (output).ConnectorIndicates that the flow continues where a matching symbol (containing the sameletter) has been placed.Flow LineLines indicate the sequence of steps and the direction of flow.DelayIndicates a delay in the process.MergeIndicates a step where two or more sub-lists or sub-processes become one.CollateIndicates a step that orders information into a standard format.Sort Indicates a step that organizes a list of items into a sequence or sets based onsome pre-determined criteria.SubroutineIndicates a sequence of actions that perform a specific task embedded within alarger process. This sequence of actions could be described in more detail on aseparate flowchart.
  8. 8. Manual Loop Indicates a sequence of commands that will continue to repeat until stopped manually. Loop Limit Indicates the point at which a loop should stop. Data storage Indicates a step where data gets stored. Database Indicates a list of information with a standard structure that allows for searching and sorting. Display Indicates a step that displays information. Off Page Indicates that the process continues off page. Top Down ProgrammingA top-down approach is essentially breaking down a system to gain insight into itscompositional sub-systems. In a top-down approach an overview of the system is firstformulated, specifying but not detailing any first-level subsystems. Each subsystem isthen refined in yet greater detail, sometimes in many additional subsystem levels, untilthe entire specification is reduced to base elements. A top-down model is oftenspecified with the assistance of "black boxes", these make it easier to manipulate.However, black boxes may fail to elucidate elementary mechanisms or be detailedenough to realistically validate the model. Bottom Up ProgrammingA bottom-up approach is piecing together systems to give rise to grander systems,thus making the original systems sub-systems of the emergent system. In a bottom-upapproach the individual base elements of the system are first specified in great detail.
  9. 9. These elements are then linked together to form larger subsystems, which then in turn are linked, sometimes in many levels, until a complete top-level system is formed. This strategy often resembles a "seed" model, whereby the beginnings are small but eventually grow in complexity and completeness. However, "organic strategies" may result in a tangle of elements and subsystems, developed in isolation and subject to local optimization as opposed to meeting a global purpose. In a bottom-up approach the individual base elements of the system are first specified in great detail. These elements are then linked together to form larger subsystems, which then in turn are linked, sometimes in many levels, until a complete top-level system is formed. This strategy often resembles a "seed" model, whereby the beginnings are small, but eventually grow in complexity and completeness. Object-oriented programming (OOP) is a programming paradigm that uses "objects" to design applications and computer programs. This bottom-up approach has one weakness. We need to use a lot of intuition to decide the functionality that is to be provided by the module. If a system is to be built from existing system, this approach is more suitable as it starts from some existing modules. Searching Searching is the process of checking for an element in a list. If given element found in the list, this technique determining the location of element. There are two type of searchimg: Linear Search or Sequential Search Binary Search Linear Searching linear search also known as sequential searching a search algorithm, that is suitable for searching a list of data for a particular value. It operates by checking every element of a list one at a time in sequence until a match is found. Linear search can be used to search an unordered list. Unordered lists are easy to implement as arrays or linked lists, and insertion and deletion can be done in constant time. The simplicity of a linearly searched unordered list means it is often the first method chosen when implementing lists which change in size while an application runs. If this later proves to be a bottleneck it can be replaced with a more complicated scheme.
  10. 10. The average performance of linear search can be improved by using it on an orderedlist. In the case of no matching element, the search can terminate at the first elementwhich is greater (lesser) than the unmatched target element, rather than examining theentire list.Linear search is very time consuming particular for large list i.e. for n > 1000.Binary SearchingBinary search algorithm (or binary chop) is a technique for locating a particular value ina sorted list. The method makes progressively better guesses, and closes in on thelocation of the sought value by selecting the middle element in the span (which,because the list is in sorted order, is the median value), comparing its value to thetarget value, and determining if it is greater than, less than, or equal to the target value.A guessed index whose value turns out to be too high becomes the new upper boundof the span, and if its value is too low that index becomes the new lower bound. Onlythe sign of the difference is inspected: there is no attempt at an interpolation searchbased on the size of the difference. Pursuing this strategy iteratively, the methodreduces the search span by a factor of two each time, and soon finds the target valueor else determines that it is not in the list at all.ExampleConsider the unsorted array A ={11, 15, 20, 25, 30, 35, 40}We want to search the element X = 15, In Binary search1).Compared the element value X = 15 with middle element value X = 25.No match found and 15 < 25.2).The middle element is large, so given element may be in the lower half of the list.1).Again compared the element value X = 15 with middle element value X = 15.Now match found and 15 = 15.Hence, the element X = 15 found at position 2. SortingSorting is the process of arranging the elements of array in ascending or descendingorder in a list. There are three type of searching:
  11. 11.  Selection Sort Bubble Sort Insertion Sort Selection Sort Selection Sort is the process of finding the smallest element in a list and placing it at the first position. Second next smallest element is found and place at the second position and so on until left the last element. In this, we require n - 1 passes. Basic steps of selection sort algorithm: 1).Find the minimum element in the list. 2).Swap it with the element in the first position of the list. 3). Repeat the steps above for all remainder elements of the list starting at the second position. Complexity In the first pass, n - 1 comparisons of elements are required. Second pass takes n - 2 comparisons an so on. The total number of comparisons are (n-1)+(n-2)+........+2+1 = n(n-1)/2 = n2/2-n/2 Hence, the number of comparison is O(n2). Bubble Sort Bubble sort puts a list into increasing order by successively comparing adjacent elements, interchanging them if they are in the wrong order. Complexity The bubble sort uses (n-1)n/2 comparisons, so it has (-) (n2) worst-case complexity in terms of the number of comparisons used. Insertion Sort Insertion sort is well suited for sorting small data sets or for the insertion of new elements into a sorted sequence.
  12. 12. Basic steps of selection sort algorithm:1).Let a0, ..., an-1 be the sequence to be sorted. At the beginning and after eachiteration of the algorithm the sequence consists of two parts: the first part a0, ..., ai-1 isalready sorted, the second part ai, ..., an-1 is still unsorted (i element 0, ..., n).2).In order to insert element ai into the sorted part, it is compared with ai-1, ai-2 etc.When an element aj with aj<=ai is found, ai is inserted behind it. If no such element isfound, then ai is inserted at the beginning of the sequence.3).After inserting element ai the length of the sorted part has increased by one. In thenext iteration, ai+1 is inserted into the sorted part etc. While at the beginning the sortedpart consists of element a0 only, at the end it consists of all elements a0, ..., an-1.ComplexityIt has a time complexity of O(n2).ExampleThe following table shows the steps for sorting the sequence 5 7 0 3 4 2 6 1. On theleft side the sorted part of the sequence is shown in red. For each iteration, the numberof positions the inserted element has moved is shown in brackets. Altogether thisamounts to 17 steps. C Character SetThe character set is ser of valid caharcters which are recognized by languagecompiler. A character denotes any alphabet, digit or special symble used to representinformation. The type char is used to stor a single character. All the uppercase letters A
  13. 13. to Z, lowercase letters a to z, the digits 0 to 9 and some special symbols are calledcharacters. A character must be a single value character and should be enclosedbetween two single quotation marks. For example a, b, c, 1, 2, >, ? etc.Upper Case LettersABCDEFGHIJKLMNOPQRSTUVWXYZLower Case LettersabcdefghijklmnopqrstuvwxyzDigits0123456789Special Symbols~`!@#$%^&*()_-=+|{}[];:",.<>/? Unformatted & Formatted I/O Functions in CFormatted and Unformatted Input/OutputUnformatted Input/Output is the most basic form of input/output. Unformattedinput/output transfers the internal binary representation of the data directly betweenmemory and the file. Formatted output converts the internal binary representation ofthe data to ASCII characters which are written to the output file. Formatted input readscharacters from the input file and converts them to internal form. Formatted I/O can beeither "Free" format or "Explicit" format.Advantages and Disadvantages of Unformatted I/OUnformatted input/output is the simplest and most efficient form of input/output. It isusually the most compact way to store data. Unformatted input/output is the leastportable form of input/output. Unformatted data files can only be moved easily to andfrom computers that share the same internal data representation. It should be notedthat XDR (external Data Representation) files, described in Portable UnformattedInput/Output, can be used to produce portable binary data. Unformatted input/output isnot directly human readable, so you cannot type it out on a terminal screen or edit itwith a text editor.
  14. 14. Advantages and Disadvantages of Formatted I/OFormatted input/output is very portable. It is a simple process to move formatted datafiles to various computers, even computers running different operating systems, aslong as they all use the ASCII character set. (ASCII is the American Standard Code forInformation Interchange. It is the character set used by almost all current computers,with the notable exception of large IBM mainframes.) Formatted files are humanreadable and can be typed to the terminal screen or edited with a text editor.However, formatted input/output is more computationally expensive than unformattedinput/output because of the need to convert between internal binary data and ASCIItext. Formatted data requires more space than unformatted to represent the sameinformation. Inaccuracies can result when converting data between text and theinternal representation.Free Format I/OWith free format input/output, IDL uses default rules to format the data.Advantages and Disadvantages of Free Format I/OThe user is free of the chore of deciding how the data should be formatted. Free formatis extremely simple and easy to use. It provides the ability to handle the majority offormatted input/output needs with a minimum of effort. However, the default formatsused are not always exactly what is required. In this case, explicit formatting isnecessary.Explicit Format I/OExplicit format I/O allows you to specify the exact format for input/output.Advantages and Disadvantages of Explicit I/OExplicit formatting allows a great deal of flexibility in specifying exactly how data will beformatted. Formats are specified using a syntax that is similar to that used inFORTRAN format statements. Scientists and engineers already familiar withFORTRAN will find IDL formats easy to write. Commonly used FORTRAN formatcodes are supported. In addition, IDL formats have been extended to provide many ofthe capabilities found in the scanf () and printf () functions commonly found in the Clanguage runtime library.
  15. 15. However, there are some disadvantages to using Explicit I/O. Using explicitly specified formats requires the user to specify more detail—they are, therefore, more complicated to use than free format. Function Prototyping Before using any function in our programme we must have to declare the function along with its return type and number of arguments followed by semicolon. This part is generally declared before main() function in a program. A function declaration consists of four parts: Function Type Function Name Parameter List Semicolon General Form function_type function_name (parameters_list); If we have defined any function before calling the function, then there is no need to declare the function. Scope of Function The place of declaration of a function defines a region in a program in which the function may be used by other functions. This region is called as scope of function. Types of Prototyping Local Prototype: When we place the prototype inside the definition of another function i.e. in local declaration, the prototype is called local prototype. Global Prototype: When we place the prototype above all functions including main() function, the prototype is called global prototype. Operations on Pointers Like other variables pointer variables can be used in expressions. For example if p1 and p2 are properly declared and initialized pointers, then the following statements are valid
  16. 16. y=*p1**p2; sum=sum+*p1; z= 5* - *p2/p1; *p2= *p2 + 10; C allows us to add integers to or subtract integers from pointers as well as to subtract one pointer from the other. We can also use short hand operators with the pointers p1+=; sum+=*p2; etc., we can also compare pointers by using relational operators the expressions such as p1 >p2 , p1==p2 and p1 =p2 are allowed. Example: Program to illustrate the pointer expression and pointer arithmetic. #include< stdio.h > main() { int ptr1,ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 –6; y=6*- *ptr1/ *ptr2 +30; printf(―nAddress of a +%u‖,ptr1); printf(―nAddress of b %u‖,ptr2); printf(―na=%d, b=%d‖,a,b); printf(―nx=%d,y=%d‖,x,y); ptr1=ptr1 + 70; ptr2= ptr2; printf(―na=%d, b=%d‖,a,b); } Files in C C supports a number of functions that have the ability to perform basic file operations, which include: Naming a file Opening a file Reading from a file Writing data into a file Closing a file File operation functions in C are:
  17. 17. Function Name Operation Creates a new file for use or fopen() Opens a new existing file for use fclose() Closes a file which has been opened for use getc() Reads a character from a file putc() Writes a character to a file fprintf() Writes a set of data values to a file fscanf() Reads a set of data values from a file getw() Reads a integer from a file putw() Writes an integer to the file fseek() Sets the position to a desired point in the file ftell() Gives the current position in the file rewind() Sets the position to the begining of the fileOpening a FileBefore write/read information in a file, we must open the file. When we open a file thena link creates between the program and the operatimg system, this is a structure calledFILE which defined in the header file "stdio.h". We give operating system the name offile, data structure and purpose. The general format of the function used for opening afile isFILE *fp;fp=fopen("filename",&mode");The first statement declares the variable fp as a pointer to the data type FILE. Asstated earlier, File is a structure that is defined in the I/O Library. The secondstatement opens the file named filename and assigns an identifier to the FILE typepointer fp. This pointer, which contains all the information about the file, issubsequently used as a communication link between the system and the program.The second statement also specifies the purpose of opening the file. The mode doesthis job.
  18. 18. Consider the following statements:FILE *p1, *p2;p1=fopen("data","r");p2=fopen("results ,"w");In these statements the p1 and p2 are created and assigned to open the files data andresults respectively the file data is opened for reading and result is opened for writing.In case the results file already exists, its contents are deleted and the files are openedas a new file. If data file does not exist error will occur.Closing a FileWhen we have finished reading/writing in the file, we need to close it. For this we usethe function fclose().fclose(fp)A file must be closed as soon as all operations on it have been completed. This wouldclose the file associated with the file pointer.The second statement also specifies the purpose of opening the file. The mode doesthis job.Consider the following statements:….FILE *p1 *p2;p1=fopen (―Input‖,‖w‖);p2=fopen (―Output‖,‖r‖);….…fclose(p1);fclose(p2)The above program opens two files and closes them after all operations on them arecompleted, once a file is closed its file pointer can be reversed on other file.The getc and putc functions are analogous to getchar and putchar functions andhandle one character at a time. The putc function writes the character contained incharacter variable c to the file associated with the pointer fp1. ex putc(c,fp1); similarlygetc function is used to read a character from a file that has been open in read mode.c=getc(fp2).
  19. 19. The program shown below displays use of a file operations. The data enter through the keyboard and the program writes it. Character by character, to the file input. The end of the data is indicated by entering an EOF character, which is control-z. the file input is closed at this signal. #include< stdio.h > main() { file *f1; printf(―Data input output‖); f1=fopen(―Input‖,‖w‖); /*Open the file Input*/ while((c=getchar()) =EOF) /*get a character from key board*/ putc(c,f1); /*write a character to input*/ fclose(f1); /*close the file input*/ printf(―nData outputn‖); f1=fopen(―INPUT‖,‖r‖); /*Reopen the file input*/ while((c=getc(f1)) =EOF) printf(―%c‖,c); fclose(f1); } I/O Operations on Files The stdio.h library has a variety of functions that do some operation on files besides reading and writing. remove function rename function tmpfile function tmpnam function remove function The remove function causes the file whose name is the string pointed to by filename to be no longer accessible by that name. A subsequent attempt to open that file using that name will fail, unless it is created anew. If the file is open, the behavior of the remove function is implementation-defined. The remove function returns zero if the operation succeeds, nonzero if it fails. #include <stdio.h> int remove(const char *filename); rename function
  20. 20. The rename function causes the file whose name is the string pointed to by old_filename to be henceforth known by the name given by the string pointed to by new_filename. The file named old_filename is no longer accessible by that name. If a file named by the string pointed to by new_filename exists prior to the call to the rename function, the behavior is implementation-defined. The rename function returns zero if the operation succeeds, nonzero if it fails, in which case if the file existed previously it is still known by its original name. #include <stdio.h> int rename(const char *old_filename, const char *new_filename); tmpfile function The tmpfile function creates a temporary binary file that will automatically be removed when it is closed or at program termination. If the program terminates abnormally, whether an open temporary file is removed is implementation-defined. The file is opened for update with "wb+" mode. The tmpfile function returns a pointer to the stream of the file that it created. If the file cannot be created, the tmpfile function returns a null pointer. #include <stdio.h> FILE *tmpfile(void); tmpnam function The tmpnam function generates a string that is a valid file name and that is not the name of an existing file. The tmpnam function generates a different string each time it is called, up to TMP_MAX times. (TMP_MAX is a macro defined in stdio.h.) If it is called more than TMP_MAX times, the behavior is implementation-defined. The implementation shall behave as if no library function calls the tmpnam function. #include <stdio.h> char *tmpnam(char *s); Error Handling During I/O Operation We can use following functions for error handling during I/O operation: clearerr function feof function ferror function perror function
  21. 21. The clearerr functionThe clearerr function clears the end-of-file and error indicators for the stream pointed toby stream.#include <stdio.h>void clearerr(FILE *stream);The feof functionThe feof function tests the end-of-file indicator for the stream pointed to by stream andreturns nonzero if and only if the end-of-file indicator is set for stream, otherwise itreturns zero.#include <stdio.h>int feof(FILE *stream);The ferror functionThe ferror function tests the error indicator for the stream pointed to by stream andreturns nonzero if and only if the error indicator is set for stream, otherwise it returnszero.#include <stdio.h>int ferror(FILE *stream);The perror functionThe perror function maps the error number in the integer expression errno to an errormessage. It writes a sequence of characters to the standard error stream thus: first, if sis not a null pointer and the character pointed to by s is not the null character, the stringpointed to by s followed by a colon (:) and a space; then an appropriate error messagestring followed by a new-line character. The contents of the error message are thesame as those returned by the strerror function with the argument errno, which areimplementation-defined.#include <stdio.h>void perror(const char *s);
  22. 22. Random Access to FilesSometimes it is required to access only a particular part of the file, not the completefile. This can be done by using the following function:1 > fseekFseek FunctionThe general format of fseek function is as follows:fseek(file pointer,offset, position);This function is used to move the file position to a desired location within the file. Fileptris a pointer to the file concerned. Offset is a number or variable of type long, andposition in an integer number. Offset specifies the number of positions (bytes) to bemoved from the location specified by the position.The position can take the 3 values: Value Meaning 0 Beginning of the file 1 Current position 2 End of the fileDynamic Memory Allocation:-Pointers provide necessary support for C’s dynamic allocation system. Dynamicallocation is the mean by which a program can obtain memory while it is running.Global variables are allocated storage at compile time. Non-static, local variables usedthe stack. However, neither global nor local variables can be added during programexecution. Yet there will be time when the storage needs of a program can not beknown ahead of time. For example, a program might want to use a dynamic datastructure, such as a linked list or a binary tree. Such structures are inherently dynamic
  23. 23. in nature, growing and shrinking as needed. To implement such a data structurerequires that a program to available to allocate and free memory as needed. Memory allocated by C’s dynamic allocation functions are obtainsfrom the heap. The heap is free memory that is not used by your program, theoperating system, or any other program running into the computer. The size of theheap cannot usually be known in advanced, but it typically contains a fairly largeamount of free memory.The following functions are used in C for dynamic memory allocation: alloc(), malloc(), calloc(), reallloc() and free(). (a) Alloc(): - The alloc() function is used to allocate a region or block of size bytes in length of the heap. The general declaration of the alloc() function is: Char *alloc(size) Unsigned int size;Some C compiler versions fill the allocated area with zeros. All versions returns somesort of error when there is no more space left to allocate, either 0, -1 or printing amessage to the system. (b) Malloc():- The malloc() function is used to allocate heap storage. Its name stands for memory allocation. The allocated region is not filled with zeros. The starting address is returned if the function is successful. A zero is returned if the function attempt to get a block of memory fails. Char *malloc(size) Unsigned int size; (c) Calloc():- The calloc() is used to allocate the continuous memory or element by element basis. The name stands for calculated allocation. It is useful for arrays and array like structure where continuity of memory is required. The starting address of the area is returned if the function is successful. A zero is returned if the function attempt to get a block of memory fails. The general declaration of the calloc() function is: Char *calloc(elements,element_size) Unsigned int elements; Unsigned int element_size;
  24. 24. (d) Realloc():- The realloc() function is used to increase or decrease the size of the block of the heap memory to the size, specific by size while preserving the address and contents of the beginning of the block. The function realloc() can diminish the size of the allocated area. The general declaration of the recalloc() function is: Char *recalloc(old block,size) Char *oldblock; Unsigned int size; The realloc() function returns the address of the newly allocated region which is same as the old block. It returns a zero if an attempt to create a new block is unsuccessful. (e) Free():- The free() function is used to free a portion of storage within the heap previously allocated by alloc(), malloc(), calloc() or realloc(). The storage returns to the heap, making it available for further heap activity. The pointer that is the argument to free() is the starting address for the region allocated. The general declaration of the calloc() function is: Int free(pointer) Char *pointer;Example: - Program to store a character string in a block of memory space created bymalloc() and then modify the same to store a larger string.#include<stdio.h>#include<conio.h>#include<stdlib.h>void main(){char *buffer;clrscr();if( (buffer=(char*) malloc(10) )==NULL){
  25. 25. printf("malloc failedn");exit(0);}printf("Buffer of size %d created", sizeof(buffer) );strcpy(buffer,"MAIMT");printf("nBuffer contains: %s", buffer);if( (buffer=(char*)realloc(buffer,15)) == NULL){printf("Reallocation failed");exit(0);}printf("nBuffer size modifiedn" );printf("Buffer still contains %sn",buffer);strcpy(buffer,"AMIT KUMAR");printf("Buffer now contains %sn",buffer);free(buffer);getch();}Output: -Buffer of size 2 createdBuffer contains: MAIMTBuffer size modifiedBuffer still contains MAIMTBuffer now contains AMIT KUMAR Program to convert decimal number into binary number.
  26. 26. #include<stdio.h>#include<conio.h>void main(){int a[90],n,i=0,l;clrscr();printf("enter any number");scanf("%d",&n);while(n>0){a[i]=n%2;n=n/2;i++;}printf("Binary number isn");for(l=i-1;l>=0;l--)printf("%d",a[l]);getch();}goto statement: - This statement transfers control unconditionally to the statementspecified by the label. The general for this statement is: - goto label;
  27. 27. Label: Goto label: Statement; ---------------- ---------------- ---------------- ---------------- ---------------- ---------------- Label: Goto label: Statement; (backward jump) (forward jump)A label is any valid variable name. Only one statement may be prefixed by a particularlabel. A statement is prefixed by a label in the following manner: - label: statement;A colon separates the label and the labeled statement. The goto statement can usedfor forward jumping and/or backward jumping.Example: - Program to calculate square root of a number (square root is only possiblefor a positive number).#include<stdio.h>#include<conio.h>#include<math.h>void main(){Int number;float result;clrscr();
  28. 28. read:printf(―Enter any number‖);scanf(―%d‖,&number);if(n<0)goto read;elseresult=sqrt(number);printf(―Square root of %d is %f‖,number,result);getch();}Output: -Enter any number 2Square root of 2 is 1.414214Pointers: -LVALUE and RVALUE of a variable: - (i) An ―lvalue‖ of a variable is the value of its address i.e. where it is stored in memory. (ii) An ―rvalue‖ of a variable is the value stored in that variable.Example: - count ptrint count=10, *ptr; 10 65432 65432 3000ptr=&count;In this example, rvalue for count is 10 and lvalue is 65432.And rvalue for ptr is 65432 and lvalue is 3000.Operations on Pointers (Pointer Arithmetic): -The following operations can be performed on a pointer: -
  29. 29. 1. Assignment Operation: - Only pointers of the same type can be assigned to each other. Let P1 and P2 are pointers of the same type, and suppose the values stored in the locations, to which they point, are A and B as shown in figure. P2 P1 A and A The assignment statement P1=P2 implies that P1 and P2 point to the same location as shown below. P1 B P2 A pointer can also be made to point nothing, by assigning the special value NULL to the variable. For example: - P=NULL Where, NULL is a reserved word in C Compiler.2. Comparison: - Pointers can be compared using the relational operators. For example if (p==q) Break; Where, p and q are the pointer variables of the same type.3. Addition of a number to a pointer: - C allows us to add integer to pointers. For example: - int i=3,*p,*q; p=&i; p=p+1; q=p+3;4. Subtraction of a number from a pointer: - C allows us to subtract integer from pointer. For example: - int i=3,*p,*q; p=&i;
  30. 30. p=p-1; q=p-3;5. Subtraction of one pointer from pointer: - One pointer variable can be subtracted from another pointer variable provided both points to the elements of the same data type. For example: - int i=3,j=12,*p,*q; p=&i; q=&j; printf(―%d‖,q-p); We may also used shorthand operators with the pointers p++; --q; x+=*p; The following operations cannot be performed on pointers: - 1. Addition of two pointers 2. Division of a pointer with a constant 3. Multiplication of a pointer with a constant Call By Value Call By Reference 1. The formal and actual 1. The formal and actual parameters are two parameters are same, different variables. though their names may be 2. The formal parameters are different. not declared as pointers. 2. The formal parameters must 3. Changes done to formal be declared as pointers. parameters are not 3. Changes done to formal reflected back to the parameters are reflected actual parameters. back to the actual 4. Actual parameters may be parameters. a constant, a variable, or 4. Actual parameters must be a an expression. variable. 5. Actual parameter is read 5. Actual parameter is read- only. write. 6. int x; 6. int *x;
  31. 31. Program to generate Fibonacci series using Recursion.Recursive Definition of the Fibonacci series f(n) is n if n<=1 f(n)= f(n-1)+f(n-2) if n>1#include<stdio.h>#include<conio.h>void main(){int terms,i;clrscr();printf("Enter the number of terms");scanf("%d",&terms);printf("Fibonacci Series isn");for(i=0;i<terms;i++)printf("%dn",fib(i));getch();}int fib(int n){if(n<=1)return(n);elsereturn( fib(n-1)+fib(n-2) ); }
  32. 32. Output: -Enter the number of terms9Fibonacci Series is01123581321 C PROGRAM DEVELOPMENT STAGESC program is created by following a fixed set of stages. The output of first stage acts asan input to the next stage. The final output after the execution of C program is anexecutable file with .Exe extension. The original program of C is called as SourceCode.PROGRAM DEVELOPMENTThe very first step in developing a program is to study the problem carefully. Youshould understand the given problem and identify the output required by the program.When you will identify the output, you will also discover the number and types of inputsneeded to generate the output. At this step, you will also have to identify some datathat are not clearly visible from inputs and outputs. After this, prepare the algorithm forthe required program. Then implement the algorithm by using C language. Store thesource code file on the hard disk of the computer. Do not skip the step of saving the fileas you may loose it due to some errors in the program.Following are main stages in the development of a C program: - • COMPILING THE PROGRAM
  33. 33. • LINKING THE PROGRAM • EXECUTION & TESTING THE PROGRAM(1) COMPILING THE PROGRAMThe compiling of the source code is required to translate into machine language, sothat it could be processed by the hardware. C compiler is used to generate themachine language code from source program. C has a built-in preprocessor thatprocesses the source code before it is passed to the compiler. The main function of thepreprocessor is to replace the preprocessor directives like #include and #define. Forexample, the preprocessor will replace the statement #include<stdio.h> with theheader file "stdio.h". Actually, the preprocessor directives instruct the preprocessorabout how to process the code. The result of this phase is the code without anypreprocessor directives.This expanded code is taken by C processor and it produces an object code for thesource code. This is done if there are no errors in the source code. This object code issave on the disk with same name and .obj extension. This means, if you have savedthe source fiIe with a name "first.c", a file with a name "first.obj" will be created aftercompilation. This process is called as compilation. In case of syntax errors, the compilernotifies the user about their location in the program. The user has to edit the programin order to execute it. The logical errors are not displayed to the user. The user himselfhas to identify them. When a logical error is discovered in the program, the sourcecode has to be edited to remove the error.(2) LINKING THE PROGRAMWe generally refer many library functions in our C programs. These are the functionsthat are defined in header files. These header files are included in our program with#include statement. The object code of these functions is to be incorporated with theobject code of the rest of the program to produce the executable file. This is done by aprocess called as Linking. So, linking is the process of combining the program files andfunctions that are required by the program. For example, if you have use a functionprintf() in your program, the object code of this function must be brought from the file<stdio.h> and linked to the main program.
  34. 34. If there are no errors in your program, the linking is automatically done by TurboC compiler. After the linking phase, an executable file with the same name as of sourcefile, is generated. This means, if you have saved the source file with a name "first.c", afile with a name ―first.exe" will be created after linking. You can execute this file bytyping the name of the file on DOS prompt.(3) EXECUTION & TESTING THE PROGRAMTesting is the next phase of program development. In this phase, we execute theprogram and supply a possible combination of inputs to get the output. The output iscompared with the known correct outputs and the correctness of the program isverified. For example, if you have created a program to add two numbers and you input7 and 5, the program should generate 12 as output.Following figure illustrate the process discussed before.
  35. 35. C Data TypesThe type associated with the data is called data type. We need data types because it providesus with the following information’s: - (a) Type of value that can be stored in the data. (b) Range (maximum & minimum value that can be stored) of data. (c) Allowed operation on data. (d) Memory required/occupied by the data.C-language provides a rich variety of data types to store all kinds of data. (i) Fundamental/Basic/Primary/Primitive/Built-in data types: - These are the built-in data types.
  36. 36. (a) Integer Data Type Integer Data Type: integer data types are used to store numeric data items. They can store whole numbers. The data types of this categories are integer (int), short integer (short int) and long integer (long int). In addition to these types unsigned int, unsigned short int and unsigned long int data types also fall under this category. Integers occupy one word in the memory. The length of the words may vary and it is typically 16 or 32 bits. Following table describes all the integer data types with their memory size and range of values supported. Data Type Description Range Int store integers -32768 to 32767 Unsigned int store integers 0 to 65535 Short int store integers -128 to 127 Unsigned short int store integers 0 to 255 long int store integers -2,147,483,648 to 2,147,483,6474 Unsigned long int store integers 0 to 4,294,967,295(b) Floating Point Data Type Floating point data types are used to store numbers with fractions. The following table describes all the floating point data types with their memory range of values supported.
  37. 37. Data Type Description Range Bytesfloat Used to store Fractional values 3.4*10-38 to 3.4*1038 4double Used to store Fractional values 3.4*10-308 to 3.4*10308 8 -4932 4932Long double Used to store Fractional values 3.4*10 to 3.4*10 10 Double Data Type: Float data type is not capable of storing very large numeric and floating quantities. For this, double precision data type is used. Double and long double are data types in this category. (c) Character Data Type Character Data Types: Character data types are used to store character data items. The values to be stored in them are enclosed in single quotation marks (‘ ‘). Char and unsigned char are the two character data types. The following table describes all the character data types with their memory size and range of values supported. Data Type Description Range Bytes Char Store character values -128 to 127 1 Unsigned char Store character values 0 to 255 1 (ii) Derived/Secondary/non-primitive/Composite Data Types Derived data types are also called as structured data types. The main difference between fundamental and derived data types is that a variable of derived data type can handle more than one values at a time whereas, a variable of fundamental data types can handle only one value at a time. These are also called secondary data types. The data types is category are arrays, structures and unions. (a) Arrays: - A finite collection of homogeneous data elements stored at contiguous memory locations. Here finite means no. of elements are fixed, homogeneous means all elements are of same type and contiguous memory locations means elements are stored at adjacent/ neighboring places. Array’s can be one-dimensional or multidimensional. (i) One-dimensional array: - An array in which element is referenced by single subscript or index.
  38. 38. Syntax: datatype var-name[size]; Example: char address[90]; (ii) Multi-dimensional array: - An array in which element is referenced by more than one subscript or indexes. Example: Two-dimensional array: - An array in which element is referenced by two subscripts or indexes. Syntax: datatype var-name[rows][cols]; Example: int matrix[9][8]; (b) Structures: - Collection of fields generally of different data type related to a particular record. Example: - Record of a student. Syntax: struct structure_name { Example: Field-1; struct student Field-2; Field-3; { . char name[90]; . . int rollno; Field-n; }; }; (c) Unions: - Collection of fields generally of different data type related to a particular record, which share a common memory.(iii) User defined data types (Enumerated data type): These are the data types that are defined by the user. They contain user specified values. “enum” keyword is used to declare data types of this type. An Enumerated data type consists of an ordered set of distinct constant values defined in a data type in a program. The format of enum is:- enum name { value-1,value-2,value-3,…….,value-4; }; Where,
  39. 39. name is the name of the enumerated data type, also known as tag and value- 1,value-2,value-3,…….,value-n are values that variable of type name can take. Example: - enum fruit { apple,orange,mango,pineapple; }; Once the type fruit has been defined then variable of that type can be defined in the following manner :- fruit a,b;(iv) Pointer data type: - A pointer is a data type that handles the data as per its memory address or in other words a pointer is a data type that is used to store the address of other variables. Pointer are classified into two types: - (a) & (addressof pointer) , (b) * (indirection pointer)(a) & (addressof pointer): -(b) * (indirection pointer) Redefining Data Types with typedef In c, it is possible to redefine the built-in as well as user defined data types. This task is accomplished by the typedef statement. Syntax: - typedef type new_type; Where, typedef is keyword, type is either built-in data type or user-defined data type, and new_type is the new name of the type. Example: - typedef float real; This statement redefines the data types float to real. Then to declare x,y and z of type float, we can also write real x,y,z; The compiler will still recognize the statement float x,y,z; as correct.
  40. 40. User Defined Data Type “ Enumerated Data Type”An Enumerated data type consists of an ordered set of distinct constant values defined in adata type in a program. The syntax of enum is:- enum name { value-1,value-2,value-3,…….,value-4; }; Where, name is the name of the enumerated data type, also known as tag and value-1, value-2,value-3,…….,value-n are values that variable of type name can take.Example (1): - enum fruit { apple,orange,mango,pineapple; }; This declaration states that a variable of type fruit can have any of the four valuesnamely apple, orange, mango and pineapple, but no other value. Once the type fruit has beendefined then variable of that type can be defined in the following manner :- fruit a,b; Now, the variable a and b are of type fruit and can assume value from the list : (apple,orange, mango, pineapple).Example (2): - Part-1 enum days { mon,tue,wed,thu,fri,sat,sun;
  41. 41. }; Part-2 days holiday,wdays; The first part defines an enumeration named days. The second part declares thevariables holiday and wdays to be enumeration variable of type days. Thus each variable canbe assigned any one of the constants mon, tue, wed, thu, fri, sat, sun.The two parts in example-2 can be combined if desired, resulting in enum days { mon,tue,wed,thu,fri,sat,sun; } holiday,wdays; or without the name(tag), simply enum { mon,tue,wed,thu,fri,sat,sun; } holiday,wdays;Enumeration constants are automatically assigned equivalent integer values, beginning with 0for the first constant, with each successive constant increasing by 1. Therefore in example-1,the enumeration constants will represent the following integer values: - Mon 0 Tue 1 Wed 2 Thu 3 Fri 4 Sat 5 Sun 6
  42. 42. These automatic assignments can be overridden by assigning explicit integer values whichdiffer from the default values. Those constants are not assigned explicit values willautomatically be assigned values which increase successively by 1 from the last explicitassignment. enum days { mon=10; tue=11; wed=12; thu=13 fri=20; sat=21; sun=50; };Operations on Enumerated Data Types: - 1. Assignment Example: - holiday=sun; 2. Comparing using Relational OperatorsExample: -Consider the enumerated data types defined in previous example: - expression values sun<tue false mon!=fri true mon<sat satAdvantages of Enumerated Data Types: - 1. Simplifies the Program.
  43. 43. 2. Enhances the readability of the program.3. Help to locate more errors at the compile time.4. Helps us to express a program in a more natural way.