54
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 device's 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 computer's CPU. The firmware could be reloaded if needed to specialize or modify the computer's 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.

C notes mca i sem 2011

Embed Size (px)

Citation preview

Page 1: C notes mca i sem 2011

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 device's 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 computer's CPU. The firmware could be reloaded if needed to specialize or modify the computer's 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

Page 2: C notes mca i sem 2011

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

Page 3: C notes mca i sem 2011

Decision Table is known as a limited entry table. When a Decision Table requires more 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 to determine how many unique combinations of conditions are present. Draw one column in the top and bottom right quadrants for each combination.

For example, if there are two conditions and the first condition has two possible values 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 quadrant of the table.

6) For each column (each unique combination of conditions), mark an X in the bottom, right quadrant in the appropriate action row. The X marks the intersection between the required action and each unique combination of condition values.

Ensure that the Table is Complete

To complete Step 5 above, ensuring that no combinations are missed, follow these steps:

1) Start with the last condition and alternate its possible values across the row. Note how often the pattern repeats itself. For a condition with two possible values, the pattern repeats itself every two columns. If three values are possible, the pattern repeats itself every three columns.

For example, for a table with three conditions each with values Y or N, there are eight (2 * 2 * 2) columns. Complete the third (last) row by entering Y once across the row followed by one N. The pattern repeats itself every two columns.

The third row would look like:

Y N Y N Y N Y N

2) Move to the condition in the row above the last condition. Cover each pattern group 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 times followed by two entries of N. This pattern repeats itself every four columns. The second row would look like:

Page 4: C notes mca i sem 2011

Y Y N N Y Y N N

3) Repeat step 2 until all rows are complete.

To complete the first row, enter Y across the row four times followed by four entries of N. The first row would look like:

Y Y Y Y N N N N

Flag Error Conditions

If a specific combination of conditions is invalid, then define one action to flag the error or invalid condition.

How to Simplify the Decision Table

If two or more combinations result in the same action, then the table can be simplified. Consider the following example:

Condition 1 Y YCondition 2 Y YCondition 3 Y NAction 1 X X

The same action occurs whether condition 3 is true or false. As a result, one column can be eliminated from the table as follows:

Condition 1 YCondition 2 YCondition 3 -Action 1 X

Example

Company X sells merchandise to wholesale and retail outlets. Wholesale customers receive a two percent discount on all orders. The company also encourages both wholesale and retail customers to pay cash on delivery by offering a two percent discount for this method of payment. Another two percent discount is given on orders of 50 or more units. Each column represents a certain type of order.

Page 5: C notes mca i sem 2011

The Decision Table records the conditions for discounts in the top left quadrant along with the ranges for the conditions in the top right quadrant. The bottom half of the table lists the actions taken, i.e., the discount rates that apply, based on the conditions. Each column represents a certain type of order. For example, column two represents cash on delivery orders of less than 50 units from retailers.

FlowchartsA flowchart is a diagrammatic representation that illustrates the sequence of operations to be performed to get the solution of a problem. Flowcharts are generally drawn in the early stages of formulating computer solutions. Flowcharts facilitate communication between programmers and business people. These flowcharts play a vital role in the programming of a problem and are quite helpful in understanding the logic of complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write the program in any high level language. Often we see how flowcharts are helpful in explaining the program to others. Hence, it is correct to say that a flowchart is a must for the better documentation of a complex program.

Advantages of Using Flowchart

1).Communication: Flowcharts are better way of communicating the logic of a system to all concerned.2).Effective analysis: With the help of flowchart, problem can be analysed in more effective way.

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% X

Page 6: C notes mca i sem 2011

3).Proper documentation: Program flowcharts serve as a good program documentation, which is needed for various purposes.4).Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and program development phase.5).Proper Debugging: The flowchart helps in debugging process.6).Efficient Program Maintenance: The maintenance of operating program becomes easy with the help of flowchart. It helps the programmer to put efforts more efficiently on that part.

Limitations of Using Flowcharts

1).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 require re-drawing completely.3).Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.4).The essentials of what is done can easily be lost in the technical details of how it is done.

Flowchart Symbols

Flowcharts use special shapes to represent different types of actions or steps in a process. Lines and arrows show the sequence of the steps, and the relationships among them.

Start/End

The terminator symbol marks the starting or ending point of the system. It usually contains the word "Start" or "End."

Action or Process

A box can represent a single step ("add two cups of flour"), or and entire sub-process ("make bread") within a larger process.

Document

A printed document or report.

Page 7: C notes mca i sem 2011

Decision

A decision or branching point. Lines representing different decisions emerge from different points of the diamond.

Input/Output

Represents material or information entering or leaving the system, such as customer order (input) or a product (output).

Connector

Indicates that the flow continues where a matching symbol (containing the same letter) has been placed.

Flow Line

Lines indicate the sequence of steps and the direction of flow.

Delay

Indicates a delay in the process.

Merge

Indicates a step where two or more sub-lists or sub-processes become one.

Collate

Indicates 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 on some pre-determined criteria.

Subroutine

Indicates a sequence of actions that perform a specific task embedded within a larger process. This sequence of actions could be described in more detail on a separate flowchart.

Page 8: C notes mca i sem 2011

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 Programming

A top-down approach is essentially breaking down a system to gain insight into its compositional sub-systems. In a top-down approach an overview of the system is first formulated, specifying but not detailing any first-level subsystems. Each subsystem is then refined in yet greater detail, sometimes in many additional subsystem levels, until the entire specification is reduced to base elements. A top-down model is often specified with the assistance of "black boxes", these make it easier to manipulate. However, black boxes may fail to elucidate elementary mechanisms or be detailed enough to realistically validate the model.

Bottom Up Programming

A 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-up approach the individual base elements of the system are first specified in great detail.

Page 9: C notes mca i sem 2011

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.

Page 10: C notes mca i sem 2011

The average performance of linear search can be improved by using it on an ordered list. In the case of no matching element, the search can terminate at the first element which is greater (lesser) than the unmatched target element, rather than examining the entire list.

Linear search is very time consuming particular for large list i.e. for n > 1000.

Binary Searching

Binary search algorithm (or binary chop) is a technique for locating a particular value in a sorted list. The method makes progressively better guesses, and closes in on the location 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 the target 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 bound of the span, and if its value is too low that index becomes the new lower bound. Only the sign of the difference is inspected: there is no attempt at an interpolation search based on the size of the difference. Pursuing this strategy iteratively, the method reduces the search span by a factor of two each time, and soon finds the target value or else determines that it is not in the list at all.

Example

Consider the unsorted array A ={11, 15, 20, 25, 30, 35, 40}

We want to search the element X = 15, In Binary search

1).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.

Sorting

Sorting is the process of arranging the elements of array in ascending or descending order in a list. There are three type of searching:

Page 11: C notes mca i sem 2011

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/2Hence, 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.

Page 12: C notes mca i sem 2011

Basic steps of selection sort algorithm:

1).Let a0, ..., an-1 be the sequence to be sorted. At the beginning and after each iteration of the algorithm the sequence consists of two parts: the first part a0, ..., ai-1 is already 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 is found, 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 the next iteration, ai+1 is inserted into the sorted part etc. While at the beginning the sorted part consists of element a0 only, at the end it consists of all elements a0, ..., an-1.

Complexity

It has a time complexity of O(n2).

Example

The following table shows the steps for sorting the sequence 5 7 0 3 4 2 6 1. On the left side the sorted part of the sequence is shown in red. For each iteration, the number of positions the inserted element has moved is shown in brackets. Altogether this amounts to 17 steps.

C Character Set

The character set is ser of valid caharcters which are recognized by language compiler. A character denotes any alphabet, digit or special symble used to represent information. The type char is used to stor a single character. All the uppercase letters A

Page 13: C notes mca i sem 2011

to Z, lowercase letters a to z, the digits 0 to 9 and some special symbols are called characters. A character must be a single value character and should be enclosed between two single quotation marks. For example 'a', 'b', 'c', '1', '2', '>', '?' etc.

Upper Case Letters

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Lower Case Letters

a b c d e f g h i j k l m n o p q r s t u v w x y z

Digits

0 1 2 3 4 5 6 7 8 9

Special Symbols

~ ` ! @ # $ % ^ & * ( ) _ - = + | \ { } [ ] ; : ' " , . < > / ?

Unformatted & Formatted I/O Functions in C

Formatted and Unformatted Input/Output

Unformatted Input/Output is the most basic form of input/output. Unformatted input/output transfers the internal binary representation of the data directly between memory and the file. Formatted output converts the internal binary representation of the data to ASCII characters which are written to the output file. Formatted input reads characters from the input file and converts them to internal form. Formatted I/O can be either "Free" format or "Explicit" format.

Advantages and Disadvantages of Unformatted I/O

Unformatted input/output is the simplest and most efficient form of input/output. It is usually the most compact way to store data. Unformatted input/output is the least portable form of input/output. Unformatted data files can only be moved easily to and from computers that share the same internal data representation. It should be noted that XDR (external Data Representation) files, described in Portable Unformatted Input/Output, can be used to produce portable binary data. Unformatted input/output is not directly human readable, so you cannot type it out on a terminal screen or edit it with a text editor.

Page 14: C notes mca i sem 2011

Advantages and Disadvantages of Formatted I/O

Formatted input/output is very portable. It is a simple process to move formatted data files to various computers, even computers running different operating systems, as long as they all use the ASCII character set. (ASCII is the American Standard Code for Information Interchange. It is the character set used by almost all current computers, with the notable exception of large IBM mainframes.) Formatted files are human readable and can be typed to the terminal screen or edited with a text editor.

However, formatted input/output is more computationally expensive than unformatted input/output because of the need to convert between internal binary data and ASCII text. Formatted data requires more space than unformatted to represent the same information. Inaccuracies can result when converting data between text and the internal representation.

Free Format I/O

With free format input/output, IDL uses default rules to format the data.

Advantages and Disadvantages of Free Format I/O

The user is free of the chore of deciding how the data should be formatted. Free format is extremely simple and easy to use. It provides the ability to handle the majority of formatted input/output needs with a minimum of effort. However, the default formats used are not always exactly what is required. In this case, explicit formatting is necessary.

Explicit Format I/O

Explicit format I/O allows you to specify the exact format for input/output.

Advantages and Disadvantages of Explicit I/O

Explicit formatting allows a great deal of flexibility in specifying exactly how data will be formatted. Formats are specified using a syntax that is similar to that used in FORTRAN format statements. Scientists and engineers already familiar with FORTRAN will find IDL formats easy to write. Commonly used FORTRAN format codes are supported. In addition, IDL formats have been extended to provide many of the capabilities found in the scanf () and printf () functions commonly found in the C language runtime library.

Page 15: C notes mca i sem 2011

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

Page 16: C notes mca i sem 2011

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:

Page 17: C notes mca i sem 2011

Function Name Operation

fopen()Creates a new file for use orOpens 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 file

Opening a File

Before write/read information in a file, we must open the file. When we open a file then a link creates between the program and the operatimg system, this is a structure called FILE which defined in the header file "stdio.h". We give operating system the name of file, data structure and purpose. The general format of the function used for opening a file is

FILE *fp;fp=fopen("filename",&mode");

The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all the information about the file, is subsequently used as a communication link between the system and the program.

The second statement also specifies the purpose of opening the file. The mode does this job.

Page 18: C notes mca i sem 2011

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 and results 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 opened as a new file. If data file does not exist error will occur.

Closing a File

When we have finished reading/writing in the file, we need to close it. For this we use the function fclose().

fclose(fp)

A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer.

The second statement also specifies the purpose of opening the file. The mode does this 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 are completed, 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 and handle one character at a time. The putc function writes the character contained in character variable c to the file associated with the pointer fp1. ex putc(c,fp1); similarly getc function is used to read a character from a file that has been open in read mode.

c=getc(fp2).

Page 19: C notes mca i sem 2011

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 output\n”); 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

Page 20: C notes mca i sem 2011

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

Page 21: C notes mca i sem 2011

The clearerr function

The clearerr function clears the end-of-file and error indicators for the stream pointed to by stream.

#include <stdio.h>void clearerr(FILE *stream);

The feof function

The feof function tests the end-of-file indicator for the stream pointed to by stream and returns nonzero if and only if the end-of-file indicator is set for stream, otherwise it returns zero.

#include <stdio.h>int feof(FILE *stream);

The ferror function

The ferror function tests the error indicator for the stream pointed to by stream and returns nonzero if and only if the error indicator is set for stream, otherwise it returns zero.

#include <stdio.h>int ferror(FILE *stream);

The perror function

The perror function maps the error number in the integer expression errno to an error message. It writes a sequence of characters to the standard error stream thus: first, if s is not a null pointer and the character pointed to by s is not the null character, the string pointed to by s followed by a colon (:) and a space; then an appropriate error message string followed by a new-line character. The contents of the error message are the same as those returned by the strerror function with the argument errno, which are implementation-defined.

#include <stdio.h>void perror(const char *s);

Page 22: C notes mca i sem 2011

Random Access to Files

Sometimes it is required to access only a particular part of the file, not the complete file. This can be done by using the following function:

1 > fseek

Fseek Function

The 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. Fileptr is a pointer to the file concerned. Offset is a number or variable of type long, and position in an integer number. Offset specifies the number of positions (bytes) to be moved from the location specified by the position.

The position can take the 3 values:

Dynamic Memory Allocation:-

Pointers provide necessary support for C’s dynamic allocation system. Dynamic allocation 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 used the stack. However, neither global nor local variables can be added during program execution. Yet there will be time when the storage needs of a program can not be known ahead of time. For example, a program might want to use a dynamic data structure, such as a linked list or a binary tree. Such structures are inherently dynamic

Value

Meaning

0 Beginning of the file

1 Current position

2 End of the file

Page 23: C notes mca i sem 2011

in nature, growing and shrinking as needed. To implement such a data structure requires that a program to available to allocate and free memory as needed.

Memory allocated by C’s dynamic allocation functions are obtains from the heap. The heap is free memory that is not used by your program, the operating system, or any other program running into the computer. The size of the heap cannot usually be known in advanced, but it typically contains a fairly large amount 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 some sort of error when there is no more space left to allocate, either 0, -1 or printing a message 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;

Page 24: C notes mca i sem 2011

(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 by malloc() 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)

{

Page 25: C notes mca i sem 2011

printf("malloc failed\n");

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 modified\n" );

printf("Buffer still contains %s\n",buffer);

strcpy(buffer,"AMIT KUMAR");

printf("Buffer now contains %s\n",buffer);

free(buffer);

getch();

}

Output: -

Buffer of size 2 created

Buffer contains: MAIMT

Buffer size modified

Buffer still contains MAIMT

Buffer now contains AMIT KUMAR

Program to convert decimal number into binary number.

Page 26: C notes mca i sem 2011

#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 is\n");

for(l=i-1;l>=0;l--)

printf("%d",a[l]);

getch();

}

goto statement: - This statement transfers control unconditionally to the statement specified by the label. The general for this statement is: -

goto label;

Page 27: C notes mca i sem 2011

A label is any valid variable name. Only one statement may be prefixed by a particular label. 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 used for forward jumping and/or backward jumping.

Example: - Program to calculate square root of a number (square root is only possible for a positive number).

#include<stdio.h>

#include<conio.h>

#include<math.h>

void main()

{

Int number;

float result;

clrscr();

Goto label:

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

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

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

Label:

Statement;

(forward jump)

Label:

Statement;

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

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

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

Goto label:

(backward jump)

Page 28: C notes mca i sem 2011

read:

printf(“Enter any number”);

scanf(“%d”,&number);

if(n<0)

goto read;

else

result=sqrt(number);

printf(“Square root of %d is %f”,number,result);

getch();

}

Output: -

Enter any number 2

Square root of 2 is 1.414214

Pointers: -

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: -

int count=10, *ptr;

ptr=&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: -

10

count

65432

65432

ptr

3000

Page 29: C notes mca i sem 2011

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.

P1

The assignment statement P1=P2

implies that P1 and P2 point to the same location as shown below.

A pointer can also be made to point nothing, by assigning the special value NULL to the variable.For example: -

P=NULLWhere, 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;

A Aand

B

P1

P2

P2

Page 30: C notes mca i sem 2011

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 pointers2. Division of a pointer with a constant 3. Multiplication of a pointer with a constant

1. The formal and actual parameters are two different variables.

2. The formal parameters are not declared as pointers.

3. Changes done to formal parameters are not reflected back to the actual parameters.

4. Actual parameters may be a constant, a variable, or an expression.

5. Actual parameter is read only.

6. int x;

1. The formal and actual parameters are same, though their names may be different.

2. The formal parameters must be declared as pointers.

3. Changes done to formal parameters are reflected back to the actual parameters.

4. Actual parameters must be a variable.

5. Actual parameter is read-write.

6. int *x;

Call By Value Call By Reference

Page 31: C notes mca i sem 2011

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 is\n");

for(i=0;i<terms;i++)

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

getch();

}

int fib(int n)

{

if(n<=1)

return(n);

else

return( fib(n-1)+fib(n-2) ); }

Page 32: C notes mca i sem 2011

Output: -

Enter the number of terms9

Fibonacci Series is

0

1

1

2

3

5

8

13

21

C PROGRAM DEVELOPMENT STAGES

C program is created by following a fixed set of stages. The output of first stage acts as an input to the next stage. The final output after the execution of C program is an executable file with .Exe extension. The original program of C is called as Source Code.

PROGRAM DEVELOPMENT

The very first step in developing a program is to study the problem carefully. You should 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 inputs needed to generate the output. At this step, you will also have to identify some data that are not clearly visible from inputs and outputs. After this, prepare the algorithm for the required program. Then implement the algorithm by using C language. Store the source code file on the hard disk of the computer. Do not skip the step of saving the file as 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

Page 33: C notes mca i sem 2011

• LINKING THE PROGRAM

• EXECUTION & TESTING THE PROGRAM

(1) COMPILING THE PROGRAM

The compiling of the source code is required to translate into machine language, so that it could be processed by the hardware. C compiler is used to generate the machine language code from source program. C has a built-in preprocessor that processes the source code before it is passed to the compiler. The main function of the preprocessor is to replace the preprocessor directives like #include and #define. For example, the preprocessor will replace the statement #include<stdio.h> with the header file "stdio.h". Actually, the preprocessor directives instruct the preprocessor about how to process the code. The result of this phase is the code without any preprocessor directives.

This expanded code is taken by C processor and it produces an object code for the source code. This is done if there are no errors in the source code. This object code is save on the disk with same name and .obj extension. This means, if you have saved the source fiIe with a name "first.c", a file with a name "first.obj" will be created after compilation.

This process is called as compilation. In case of syntax errors, the compiler notifies the user about their location in the program. The user has to edit the program in order to execute it. The logical errors are not displayed to the user. The user himself has to identify them. When a logical error is discovered in the program, the source code has to be edited to remove the error.

(2) LINKING THE PROGRAM

We generally refer many library functions in our C programs. These are the functions that 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 the object code of the rest of the program to produce the executable file. This is done by a process called as Linking. So, linking is the process of combining the program files and functions that are required by the program. For example, if you have use a function printf() in your program, the object code of this function must be brought from the file <stdio.h> and linked to the main program.

Page 34: C notes mca i sem 2011

If there are no errors in your program, the linking is automatically done by Turbo C compiler. After the linking phase, an executable file with the same name as of source file, is generated. This means, if you have saved the source file with a name "first.c", a file with a name “first.exe" will be created after linking. You can execute this file by typing the name of the file on DOS prompt.

(3) EXECUTION & TESTING THE PROGRAM

Testing is the next phase of program development. In this phase, we execute the program and supply a possible combination of inputs to get the output. The output is compared with the known correct outputs and the correctness of the program is verified. For example, if you have created a program to add two numbers and you input 7 and 5, the program should generate 12 as output.

Following figure illustrate the process discussed before.

C Compiler

Link with System Library

Execute Program CodeExecutable Object Code

System Library

Input Data

Stop

No

Process of Compiling and Running C Program

Page 35: C notes mca i sem 2011

C Data Types

The type associated with the data is called data type. We need data types because it provides us 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.

(a)Integer

Data TypeInteger 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

IntUnsigned int

Short intUnsigned short

intLong int

Unsigned long int

Float Double

Long double

CharUnsigned char

StructureUnionArrays

Page 36: C notes mca i sem 2011

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 RangeInt store integers -32768 to 32767Unsigned int store integers 0 to 65535Short int store integers -128 to 127Unsigned short int store integers 0 to 255long int store integers -2,147,483,648 to 2,147,483,6474Unsigned long int store integers 0 to 4,294,967,295

(b) Floating Point Data TypeFloating 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.

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 8Long double Used to store Fractional values 3.4*10-4932 to 3.4*104932 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 TypeCharacter 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 BytesChar Store character values -128 to 127 1

Page 37: C notes mca i sem 2011

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. 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{Field-1;Field-2;Field-3;..

Example:

struct student

{

char name[90];

int rollno;

};

Page 38: C notes mca i sem 2011

.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, 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)

Page 39: C notes mca i sem 2011

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.

User Defined Data Type

“ Enumerated Data Type”

An Enumerated data type consists of an ordered set of distinct constant values defined in a data 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

Page 40: C notes mca i sem 2011

{

apple,orange,mango,pineapple;

};

This declaration states that a variable of type fruit can have any of the four values namely apple, orange, mango and pineapple, but no other value. Once the type fruit has been defined 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;

};

Part-2 days holiday,wdays;

The first part defines an enumeration named days. The second part declares the variables holiday and wdays to be enumeration variable of type days. Thus each variable can be 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

{

Page 41: C notes mca i sem 2011

mon,tue,wed,thu,fri,sat,sun;

} holiday,wdays;

Enumeration constants are automatically assigned equivalent integer values, beginning with 0 for 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

These automatic assignments can be overridden by assigning explicit integer values which differ from the default values. Those constants are not assigned explicit values will automatically be assigned values which increase successively by 1 from the last explicit assignment. enum days

{

mon=10;

tue=11;

wed=12;

thu=13

fri=20;

sat=21;

sun=50;

};

Operations on Enumerated Data Types: -

Page 42: C notes mca i sem 2011

1. Assignment

Example: - holiday=sun;

2. Comparing using Relational Operators

Example: -

Consider the enumerated data types defined in previous example: -

expression values

sun<tue false

mon!=fri true

mon<sat sat

Advantages of Enumerated Data Types: -

1. Simplifies the Program.

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.