C programing Manual 2015 (Updated)

Embed Size (px)

Citation preview

  • 7/25/2019 C programing Manual 2015 (Updated)

    1/75

    Computer Programming Lab Manual 2014-2015

    ACHARYA INSTITUTE OF TECHNOLOGY

    Soladevanahalli, Bangalore - 560107(Affiliated to Visvesvaraya Technological University, Belgaum)

    DEPARTMENT OF COMPUTER SCIENCE AND

    ENGINEERING

    COMPUTER PROGR MM ING L BOR TORY

    M NU L

    14CPL16/14CPL26

    As per VTU Syllabus 2014

    For

    I / II semester B E

    Compiled By

    Latharani T.R. and Manjunath G.S.

    Assistant Professor

    Dept. of Computer Science & Engineering

    Acharya Institute of Technology

    Bangalore-560107

  • 7/25/2019 C programing Manual 2015 (Updated)

    2/75

    Computer Programming Lab Manual 2014-2015

    COMPUTER PROGRAMMING LABORATORY.

    Subject Code:14CPL16/14CPL26Hours/Week:03

    Total Hours:42

    IA Marks:25Exam. Hours:03

    Exam. Marks:50

    SlNo.

    Program Name PageNo.

    PART A : Demonstration of Personal Computer and its AccessoriesDemonstration and Explanation on Disassembly and Assembly of a Personal Computer bythe faculty-in-charge. Students have to prepare a write-up on the same and include it in theLab record and evaluated.

    1Write-up on Functional block diagram of Computer, CPU, Buses, MotherBoard, Chip sets, Operating System & types of OS, Basics of Networking &Topology and NIC.

    2

    Write-up onRAM, SDRAM, FLASH memory, Hard disks, Optical media, CD-

    ROM/R/RW, DVDs, Flash drives, Keyboard, Mouse, Printers andPlotters.Introduction to flowchart, algorithm and pseudo code.PART B: Problem Solving in C

    1

    Design and develop a flowchart or an algorithm that takes three coefficients(a,b, andc) of a Quadratic equation (ax2+bx+c=0) as input and compute allpossible roots. Implement a C program for the developedflowchart/algorithm and execute the same to output the possible roots for agiven set of coefficients with appropriate messages.

    2

    Design and develop an algorithm to find the reverse of an integer numberNUM and check whether it is PALINDROME or NOT. Implement a C programfor the developed algorithm that takes an integer number as input andoutput the reverse of the same with suitable messages. Ex: Num: 2014,Reverse: 4102, Not a Palindrome.

    3

    a. Design and develop a flowchart to find the square root of a given numberN. Implement a C program for the same and execute for all possible inputswith appropriate messages. Note: Dont use library functionsqrt (n).b. Design and develop a C program to read a year as an input and findwhether it isleap yearor not. Also consider end of the centuries.

    4

    Design and develop an algorithm for evaluating the polynomial f(x) = a4x4+a3x3 +a2x2+a1x+a0 for a given value ofx and its coefficients using Hornersmethod. Implement a C program for the developed algorithm and execute for

    different sets of values of coefficients andx.

    5

    Draw the flowchart and write C Program to compute Sin(x) using Taylorseries approximation given by Sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + .Compare the result with the built- in Library function and print both theresults with appropriate messages.

    6Develop an algorithm, implement and execute a C program that reads Ninteger numbers and arrange them in ascending order usingBubble Sort.

    7Develop, implement and execute a C program that reads two matrices A (m xn) andB (p x q) and Compute the productA andB. Read matrixA in rowmajor order and matrix B in column major order. Print both the input

  • 7/25/2019 C programing Manual 2015 (Updated)

    3/75

    Computer Programming Lab Manual 2014-2015

    matrices and resultant matrix with suitable headings and in matrix format.Program must check the compatibility of orders of the matrices formultiplication. Report appropriate message in case of incompatibility.

    8Develop, implement and execute a C program to search a Name in a list ofnames using Binary searching technique.

    9

    Write and execute a C program thati. Implements string copy operationSTRCOPY (str1, str2) that copies a

    string str1 to another stringstr2 without using library function.ii. Reads asentence and prints frequency of each of the vowels and total

    count of consonants.

    10

    a. Design and develop a C function RightShift(x, n) that takes two integersxand n as input and returns value of the integerx rotated to the right bynpositions. Assume the integers are unsigned. Write a C program that invokesthis function with different values forx andn and tabulate the results withsuitable headings.b. Design and develop a C function isprime (num) that accepts an integerargument and returns 1 if the argument is prime, a 0 otherwise. Write a Cprogram that invokes this function to generate prime numbers between thegiven ranges.

    11

    Draw the flowchart and write arecursive C function to find the factorial of anumber, n!. Defined byfact (n) =1, ifn=0. Otherwisefact (n) =n*fact(n-1).Using this function, write a C program to compute the binomial coefficient C.Tabulate the results for different values ofn and rwith suitable messages.

    12

    Given two university information files studentname.txt and usn.txt thatcontains students Name and USN respectively. Write a C program to create anew file called output.txt and copy the content of files studentname.txtand usn.txt into output file in the sequence shown below. Display the

    contents of output file output.txt on to the screen.S t u d e n t N a m e U S NN a m e 1 U S N 1

    N a m e 2 U S N 2

    .

    .

    .

    .

    .

    .

    13

    Write a C program to maintain a record ofn student details using an arrayof structures with four fields (Roll number, Name, Marks, and Grade). Eachfield is of an appropriate data type. Print the marks of the student given

    student name as input.

    14Write a C program using pointers to compute the sum, mean and standarddeviation of all elements stored in an array ofn real numbers.

    Viva-Voce Questions

    Reference Book :

    ReemaThareja, Computer Fundamentals and Programming in C ,Oxford Press, 2012.

  • 7/25/2019 C programing Manual 2015 (Updated)

    4/75

    Computer Programming Lab Manual 2014-2015

    Practical Examination Procedure:1. All laboratory experiments (Fourteen) are to be included for practical examination.2. Students are allowed to pick one experiment from the lot.3. Strictly follow the instructions as printed on the cover page of answer script for

    breakup of marks.4. Change of experiment is allowed only once and 15% Marks allotted to the procedure

    part to be made zero.

    Sl. No. Activity Max Marks

    1 Writing the assigned program along with Algorithm and Flowchart 10

    2 Execution of the program and displaying the output ina proper format 30

    3 Viva-Voce 10

    4 Total Maximum Marks 50

    5 Minimum passing Marks (40% of Total Maximum Marks) 20

  • 7/25/2019 C programing Manual 2015 (Updated)

    5/75

    Computer Programming Lab Manual 2014-2015

    A DIGITAL COMPUTER

    Computer programs may be written in High level languages like Pascal, FORTRAN andCOBOL etc., some programmer also writes assembly language to carry out the desired task.Hardware is the tangible parts of a computer like the keyboards, printers, disk drives and

    the monitor among others. Software is the intangible part of the computer that providesinstructions for the hardware to perform and it includes the operating system, utilities,word processor, database management systems and the spreadsheets.

    Hardware of a computer system refers to any physical, electrical, electro-mechanicalcomponents of the computer which we can touch and see. For example keyboard, mouse,cabinet of computer is considered as hardware.Software is a set of programs, which are designed to perform a well-defined function. Aprogram is a sequence of instructions written to solve a particular problem.There are two types of system software:

    System Software Application Software

    System Software

    The system software is a collection of programs designed to operate, control and extendthe processing capabilities of the computer itself. System software is generally prepared bycomputer manufacturers.This software comprise of programs written in low level languages which interact with thehardware at a very basic level. System software serves as the interface between hardwareand the end users.

    Some examples of system software are Operating System, Compilers, Interpreter,Assemblers, linkers, loaders etc.

    Features of System Software are the following: Close to system. Fast in speed. Difficult to design. Difficult to understand. Less interactive. Smaller in size. Difficult to manipulate. Generally written in low-level language.

  • 7/25/2019 C programing Manual 2015 (Updated)

    6/75

    Computer Programming Lab Manual 2014-2015

    Application Software

    Application software is the software that is designed to satisfy a particular need of aparticular environment. All software prepared by us in the computer lab can come underthe category of Application Software.Application software may consist of a single program, such as a Microsoft's notepad forwriting and editing simple text. It may also consist of a collection of programs, often calleda software package, which work together to accomplish a task, such as a spreadsheetpackage.Examples of Application software are the following:Payroll Software Income Tax SoftwareStudent Record Software Railways Reservation SoftwareInventory Management Software Microsoft Office

    Features of Application Software

    It is close to user. It is easy to design. More interactive. Slow in speed.

    Generally written in high-level language. Easy to understand. Easy to manipulate and use. Bigger in size and requires large storage space.

    Hardware represents the physical and tangible components of the computer, i.e., thecomponents that can be seen and touched.

  • 7/25/2019 C programing Manual 2015 (Updated)

    7/75

    Computer Programming Lab Manual 2014-2015

    Examples of Hardware are following: Input devices -- keyboard, mouse, etc. Output devices -- printer, monitor, etc. Secondary storage devices -- Hard disk, CD, DVD, etc. Internal components -- CPU, motherboard, RAM, etc.

    Relationship between Hardware and Software

    Mutually dependent. Both of them must work together to make computer produce auseful output.

    Software cannot be utilized without supporting hardware. Hardware without set of programs to operate upon cannot be utilized and is useless. To get a particular job done on the computer, relevant software should be loaded into

    the hardware. Hardware is a one-time expense. Software development is very expensive and is a continuing expense. Different software can be loaded on hardware to run different jobs. Software acts as an interface between the user and the hardware. If hardware is the 'heart' of a computer system, then software is its 'soul'. Both are

    complimentary to each other.

    Information Processing Life cycle

    All types of computer follows a same basic logical structure and perform the following fivebasic operations for converting raw input data into information useful to their users

    Sl. No. Operation Description

    1 Receive Input The process of entering data and instructions into the computersystem through input devices like key board, mouse etc.

    2ProcessingData

    Performing arithmetic, logical operations on data in order toconvert them into useful information in the CPU.

    3OutputInformation

    The process of producing useful information or results for the user,such as a printed report or visual display on an output devices likemonitor, printer etc.

    4 Store DataSaving data and instructions in the memory so that they areavailable for processing as and when required.

    5 Control theworkflow

    Direct the manner and sequence in which all of the aboveoperations are performed.

    CPU

    Consists of the following features: CPU is considered as the brain of the computer. CPU performs all types of data processing operations. It stores data, intermediate results and instructions (program).

  • 7/25/2019 C programing Manual 2015 (Updated)

    8/75

    Computer Programming Lab Manual 2014-2015

    It controls the operation of all parts of computer.CPU itself has following three components.

    Memory Or Storage Unit Control Unit ALU(Arithmetic Logic Unit)

    ALU (Arithmetic Logic Unit)

    This unit consists of two subsections namely Arithmetic section Logic Section

    Arithmetic section

    Function of Arithmetic section is to perform arithmetic operations like addition,subtraction, multiplication and division. All complex operations are done by makingrepetitive use of above operations.Logic section

    Function of logic section is to perform logic operations such as comparing, selecting,matching and merging of data.

    Basic units of a computer

    Memory or Storage Unit

    A memory is just like a human brain. It is used to store data and instruction. Computermemory is the storage space in computer where data is to be processed and instructionsrequired for processing are stored. The memory is divided into large number of small parts.Each part is called cell. Each location or cell has a unique address which varies from zero tomemory size minus one. For example if computer has 64k words, then this memory unithas 64 * 1024=65536 memory location. The address of these locations varies from 0 to65535. This unit can store instruction, data and intermediate results. This unit suppliesinformation to the other units of the computer when needed.Function of Memory Unit is

    It stores all the data to be processed and the instructions required for processing.

  • 7/25/2019 C programing Manual 2015 (Updated)

    9/75

    Computer Programming Lab Manual 2014-2015

    It stores intermediate results of processing. It stores final results of processing before these results are released to an output

    device. All inputs and outputs are transmitted through main memory.

    Memory is primarily of three types Cache Memory Primary Memory/Main Memory Secondary Memory

    Cache Memory

    Cache memory is a very high speed semiconductor memory which can speed up CPU. It actsas a buffer between the CPU and main memory. It is used to hold those parts of data andprogram which are most frequently used by CPU. The parts of data and programs aretransferred from disk to cache memory by operating system, from where CPU can access

    them.Advantage Cache memory is faster than main memory. It consumes less access time as compared to main memory. It stores the program that can be executed within a short period of time. It stores data for temporary use.

    Disadvantage

    Cache memory has limited capacity. It is very expensive.

    Primary Memory (Main Memory)

    Primary memory holds only those data and instructions on which computer is currentlyworking. It has limited capacity and data get lost when power is switched off. It is generallymade up of semiconductor device. These memories are not as fast as registers. The dataand instruction required to be processed earlier reside in main memory. It is divided intotwo subcategories RAM and ROM. Characteristic of Main Memory are

    These are semiconductor memories. It is known as main memory. Usually volatile memory. Data is lost in case power is switch off. It is working memory of the computer. Faster than secondary memories. A computer cannot run without primary memory.

    A RAM constitutes the internal memory of the CPU for storing data, program and programresult. It is read/write memory. It is called random access memory (RAM). Since accesstime in RAM is independent of the address to the word that is, each storage location insidethe memory is as easy to reach as other location & takes the same amount of time. We can

  • 7/25/2019 C programing Manual 2015 (Updated)

    10/75

    Computer Programming Lab Manual 2014-2015

    reach into the memory at random & extremely fast but can also be quite expensive. RAM isvolatile, i.e. data stored in it is lost when we switch off the computer or if there is a powerfailure. Hence a backup uninterruptible power system (UPS) is often used with computers.RAM is small, both in terms of its physical size and in the amount of data it can hold. RAM isof two types

    Static RAM (SRAM) Dynamic RAM (DRAM)

    Static RAM (SRAM)

    SRAM Chip

    The word static indicates that the memory retains its contents as long as power remainsapplied. However, data is lost when the power gets down due to volatile nature. SRAMchips use a matrix of 6-transistors and no capacitors. Transistors do not require power toprevent leakage, so SRAM need not have to be refreshed on a regular basis. Because of theextra space in the matrix, SRAM uses more chips than DRAM for the same amount ofstorage space, thus making the manufacturing costs higher. Static RAM is used as cachememory needs to be very fast and small. Characteristic of the Static RAM

    It has long data lifetime There is no need to refresh Faster Used as cache memory Large size Expensive High power consumption

    Dynamic RAM (DRAM)

    DRAM, unlike SRAM, must be continually refreshed in order for it to maintain the data.This is done by placing the memory on a refresh circuit that rewrites the data severalhundred times per second. DRAM is used for most system memory because it is cheap andsmall. All DRAMs are made up of memory cells. These cells are composed of one capacitorand one transistor. Characteristic of the Dynamic RAM

    It has short data lifetime Need to refresh continuously Slower as compared to SRAM Used as RAM

  • 7/25/2019 C programing Manual 2015 (Updated)

    11/75

    Computer Programming Lab Manual 2014-2015

    lesser in size Less expensive Less power consumption

    Read Only Memory (ROM)

    ROM stands for Read Only Memory, the memory from which we can only read but cannotwrite on it. This type of memory is non-volatile. The information is stored permanently insuch memories during manufacture. A ROM, stores such instruction as are required to startcomputer when electricity is first turned on, this operation is referred to as bootstrap. ROMchip are not only used in the computer but also in other electronic items like washingmachine and microwave oven.Following are the various types of ROM

    MROM (Masked ROM)

    The very first ROMs were hard-wired devices that contained a pre-programmed set of dataor instructions. These kinds of ROMs are known as masked ROMs. It is inexpensive ROM.

    PROM (Programmable Read only Memory)

    PROM is read-only memory that can be modified only once by a user. The user buys ablank PROM and enters the desired contents using a PROM programmer. Inside the PROMchip there are small fuses which are burnt open during programming. It can beprogrammed only once and is not erasable.

    EPROM (Erasable and Programmable Read Only Memory)

    The EPROM can be erased by exposing it to ultra-violet light for a duration of up to 40minutes. Usually, a EPROM eraser achieves this function. During programming an electrical

    charge is trapped in an insulated gate region. The charge is retained for more than tenyears because the charge has no leakage path. For erasing this charge, ultra-violet light ispassed through a quartz crystal window (lid). This exposure to ultra-violet light dissipatesthe charge. During normal use the quartz lid is sealed with a sticker.

    EEPROM (Electrically Erasable and Programmable Read Only Memory)

    The EEPROM is programmed and erased electrically by burning some fusible links. It canbe erased and reprogrammed about ten thousand times. Both erasing and programmingtake about 4 to 10 ms (milli second). In EEPROM, any location can be selectively erased and

  • 7/25/2019 C programing Manual 2015 (Updated)

    12/75

    Computer Programming Lab Manual 2014-2015

    programmed. EEPROMs can be erased one byte at a time, rather than erasing the entirechip. Hence, the process of re-programming is flexible but slow.Advantages of ROM

    Non-volatile in nature These cannot be accidentally changed

    Cheaper than RAMs Easy to test More Reliable than RAMs These are static and do not require refreshing Its contents are always known and can be verified

    Secondary Memory

    This type of memory is also known as external memory or non-volatile. It is slower thanmain memory. These are used for storing Data/Information permanently. CPU directlydoes not access these memories instead they are accessed via input-output routines.

    Contents of secondary memories are first transferred to main memory, and then CPU canaccess it. For example: disk, CD-ROM, DVD etc. Characteristic of Secondary Memory These are magnetic and optical memories. It is known as backup memory. It is non-volatile memory. Data is permanently stored even if power is switched off. It is used for storage of the data in the computer. Computer may run without secondary memory. Slower than primary memories.

    Control Unit

    This unit controls the operations of all parts of computer. It does not carry out any actualdata processing operations. Functions of this unit are

    It is responsible for controlling the transfer of data and instructions among otherunits of a computer.

    It manages and coordinates all the units of the computer. It obtains the instructions from the memory, interprets them and directs the

    operation of the computer. It communicates with input/output devices for transfer of data or results from

    storage. It does not process or store data.

    Input unit

    The input device is used to enter data and information into a computer. The devices like keyboard, mouse and scanner are commonly used as input devices. A keyboard is used to enter alphanumeric characters and symbols. The mouse is used to pick or select a command from the monitor screen. A scanner is used to scan an image or read a barcode and so on.

  • 7/25/2019 C programing Manual 2015 (Updated)

    13/75

    Computer Programming Lab Manual 2014-2015

    Central Processing Unit

    The processing unit comprises a processor which interprets the programinstructions in memory, controls the flow of data and performs arithmetic andlogical operations.

    The program instructions are processed one at a time along with the necessary data. The results are sent to memory and the next instruction is processed. This method is repeated until the program is executed.

    Arithmetic and Logic unit:

    The arithmetic-logic unit (ALU) is the unit of the computer that performs arithmeticand logical operations on the data.

    This section of the machine can be relatively small consisting of circuits andregisters which perform arithmetic (+, -, *, /) and logic (>,

  • 7/25/2019 C programing Manual 2015 (Updated)

    14/75

    Computer Programming Lab Manual 2014-2015

    Microprocessor has some key components which work closely with it. In case of anydamage, the component can be replaced. They are

    Clock rate

    Defines the rate at which a processor completes its operation.

    MotherboardIt is the main circuit board of a computer in which a processor is inserted. It contains otherchipsets, controllers and expansion slots used to enhance the processor speed in computersystem.System Bus

    Placed between CPU and memory on the mother board to transfer address and data.Cache memory

    Portion of main memory that a microprocessor can access more quickly than RAM.Improves overall system speed.Instruction Pipelining

    Method to increase the capability of a CPU. It is technique where the microprocessor beginsexecuting the second instruction before the first has already been executed.Heat sink

    Attached to microprocessor chip to bring down its temperature. It keeps away theprocessor from overheating by absorbing its heat and dissipating it in air. There are twotypes of heat sink.

    Active Heat sink

    Comes along with the fan and attached at the top of the plain metal surface of microprocessor. It enables direct cooling of the processor.Passive heat sink

    Comes without fan. It consists of the metal plate attached to the surface of the processorand consists of the fins, which streams the air to cool it.Types of Microprocessors

    Instruction Set: It is a group of instructions that can be given to the computer. Theseinstructions direct the computer in terms of data manipulation. A typical instructionconsists of two parts: Opcode and Operand.Opcode or operational code is the instruction applied. It can be loading data, storing dataetc.Operand is the memory register or data upon which instruction is applied.CISC Approach

    Single instructions can execute several low-level operations. The entire task of multiplyingtwo numbers can be completed with one instruction:MULT 1A6F, 1A80

    MULT is what is known as a "complex instruction." It operates directly on the computer'smemory banks and does not require the programmer to explicitly call any loading orstoring functions. It closely resembles a command in a higher level language. For instance,if we let "a" represent the value of 6 and "b" represent the value of 8, then this command isidentical to the statement "a = a * b."One of the primary advantages of this system is that the compiler has to do very little workto translate a high-level language statement into assembly. Because the length of the code

  • 7/25/2019 C programing Manual 2015 (Updated)

    15/75

    Computer Programming Lab Manual 2014-2015

    is relatively short, very little RAM is required to store instructions. The emphasis is put onbuilding complex instructions directly into the hardware.The RISC Approach

    RISC processors only use simple instructions that can be executed within one clock cycle.Thus, the "MULT" command described above could be divided into three separatecommands: "LOAD," which moves data from the memory bank to a register, "PROD," whichfinds the product of two operands located within the registers, and "STORE," which movesdata from a register to the memory banks. In order to perform the exact series of stepsdescribed in the CISC approach, a programmer would need to code four lines of assembly:LOAD 1A6F, 1A80LOAD B, 8PROD A, BSTORE F000, ABuses

    These are collection of wires which transfer information between different parts of thecomputer. There are two types of buses.

    1. System Bus2. I/O Bus

    System Bus

    The system bus is a cable which carries data communication between the majorcomponents of the computer, including the microprocessor. Not all of the communicationthat uses the bus involves the CPU, although naturally the examples used in this tutorialwill centre on such instances.The system bus consists of three different groups of wiring, called the data bus, control bus

    and address bus. These all have separate responsibilities and characteristics, which can beoutlined as follows:

    Control Bus

    The control bus carries the signals relating to the control and co-ordination of the variousactivities across the computer, which can be sent from the control unitwithin the CPU.Different architectures result in differing number of lines of wire within the control bus, aseach line is used to perform a specific task. For instance, different, specific lines are usedfor each of read, write and reset requests.

  • 7/25/2019 C programing Manual 2015 (Updated)

    16/75

    Computer Programming Lab Manual 2014-2015

    Data Bus

    This is used for the exchange of data between the processor, memory and peripherals, andis bi-directional so that it allows data flow in both directions along the wires. Again, thenumber of wires used in the data bus (sometimes known as the 'width') can differ. Eachwire is used for the transfer of signals corresponding to a single bit of binary data. As such,a greater width allows greater amounts of data to be transferred at the same time.

    Address Bus

    The address bus contains the connections between the microprocessor and memory thatcarry the signals relating to the addresses which the CPU is processing at that time, such asthe locations that the CPU is reading from or writing to. The width of the address buscorresponds to the maximum addressing capacity of the bus, or the largest address withinmemory that the bus can work with. The addresses are transferred in binary format, witheach line of the address bus carrying a single binary digit. Therefore the maximum addresscapacity is equal to two to the power of the number of lines present (2^lines).

    I/O BusA personal computer may transfer data from disk to CPU, from CPU to memory, or frommemory to the display adapter. I/O buses connect all I/O devices with the CPU and RAM. Inmodern Pentium driven PC, there are two or three different I/O Buses.

    The ISA (Industry Standard Architecture) Bus - oldest, simplest and slowest bus.ISA is a type of bus used in PCs for adding expansion cards. For example, an ISA slotmay be used to add a video card, a network card, or an extra serial port.

    The PCI (Peripheral Component Interconnect) Bus Fastest and presently mostpowerful bus. PCI is an interconnection system between a microprocessor andattached devices in which expansion slots are spaced closely for high speed

    operation. Using PCI, a computer can support both new PCI cards while continuingto support Industry Standard Architecture (ISA) expansion cards, an olderstandard.

    The USB (Universal Serial Bus) newest bus. It is most used on Personalcomputers. USB is also used on other devices such as the PlayStation 2, PlayStation3 and the Xbox 360. USB connects different devices using a standard interface.

    Most people use USB for computer mice, keyboards, scanners, printers, digital cameras,and USB flash drives. The standard was made to improve plug and play devices. This meansthat a device can simply be plugged into a free socket. The computer will then recognize it.

    Operating systems and its functions: An operating system is a program that acts as an interface between the software and

    the computer hardware. It is an integration set of specialized programs that are used to manage overall

    resources and operations of the computer. It is specialized software that controls and monitors the execution of all other

    programs that reside in the computer, including application programs and othersystem software.

  • 7/25/2019 C programing Manual 2015 (Updated)

    17/75

    Computer Programming Lab Manual 2014-2015

    Objectives of Operating System Making a computer system convenient to use in an efficient manner. To hide the details of the hardware resources from the users. To provide users a convenient interface to use the computer system. To act as an intermediary between the hardware and its users and making it easier

    for the users to access and use other resources. Manage the resources of a computer system. Keep track of who is using which resource, granting resource requests, according for

    resource using and mediating conflicting requests from different programs and users. The efficient and fair sharing of resources among users and programs.

    Characteristics of Operating System Memory Management-- It keeps track of primary memory, i.e., what parts of it are

    in use by whom, what parts are not in use, etc. Allocates the memory when theprocess or program requests it.

    Processor Management-- Allocates the processor (CPU) to a process. Deallocateprocessor when processor is no longer required.

    Device Management-- Keeps tracks of all devices. This is also called I/O controller.Decides which process gets the device when and for how much time.

    File Management-- Allocates the resources. Deallocates the resource. Decides whogets the resources.

    Security -- By means of passwords & similar other techniques, preventingunauthorized access to programs & data.

    Job accounting -- Keeping track of time & resources used by various jobs and/orusers.

  • 7/25/2019 C programing Manual 2015 (Updated)

    18/75

    Computer Programming Lab Manual 2014-2015

    Control over system performance -- Recording delays between requests for aservice & from the system.

    Interaction with the operators -- The interaction may take place via the console ofthe computer in the form of instructions. Operating System acknowledges the same,do the corresponding action and inform the operation by a display screen.

    Error-detecting aids -- Production of dumps, traces, error messages and otherdebugging and error-detecting methods. Coordination between other software and users -- Coordination and assignment

    of compilers, interpreters, assemblers and other software to the various users of thecomputer systems.

    We know operating system is a collection of programs and it is the interface between userand the computer. An operating system is a program which connects the user and theelectronic hardware in a computer. It is a set of programs which supervise the activities ofa computer and activate the operations of the hardware components such as CPU, mainmemory, disk drives, keyboard, monitor and printer and so on. Some of the startup

    programs initially loaded to RAM are stored in ROM, mainly the BIOS programs which arerecorded by the manufacturers of the computer system. Service programs available inoperating system for operating system for operations like copying a file, deleting a file,formatting a disk, printing a file and so on are usually stored in the disk. Error messages aredisplayed on the screen if there is any malfunctioning of hardware.There are many operating system used in computers. Commonly used operating systemsare MS-DOS (Microsoft Disk operating System), Windows 95/98/2000, Windows NT, UNIXand so on. Nowadays Windows 2000 operating system is widely used in personalcomputers, and UNIX is used in Mainframes, Servers, Graphic Workstations and alsopersonal computers. Linux is one of the most popular free operating system.

    Operating system will display instruction on the monitor screen and the user caninteract with the computer. It loads the application programs such as MS Word, AutoCAD and so on from disk to

    the computer memory. It manages the information stored on disk and retrieves the same whenever required. It supervises and coordinates the activities of the hardware and peripherals such as

    CPU, keyboard, mouse, monitor, printer, RAM, disk drives and so on. It utilizes the power of the CPU for multitasking and timesharing.

    In general operating systems performs many task which includeMemory managementProcess managementI/O managementDevice management

    Multitasking

    It is the ability of the computer to handle several application programs concurrently.Printing a document, executing a program and any other operation can be donesimultaneously to reduce the idle time of the processor. The multi task capability of the

  • 7/25/2019 C programing Manual 2015 (Updated)

    19/75

    Computer Programming Lab Manual 2014-2015

    operating system will utilize the processor efficiently, the reducing the user time. Anothersimple example is hearing audio songs and typing programs same time.

    Timesharing

    It is the ability of the CPU to serve many users connected to it through a network. The

    operating system will assign each user a slice of processor time or time quantum in around-robin fashion. Since the CPU has high processing speed, it can process information ofmany users.

    Specific features of DOS and UNIX:

    MS-DOS is a single user operating system developed by Microsoft Corporation. Anoperating system has a collection of program. When the computer is switched on, the fileCOMMAND.COM is loaded to the RAM and after the successful start of the computer, theDOS prompt or command prompt will be displayed. The DOS prompt displays the letterassociated with the disk drive followed by a> symbol. For floppy disk drive, A> or A :> isdisplayed and for hard disk drive C> or C:\> is displayed. It indicates the operating system

    is ready to take commands from the user. MS-DOS is one of the popular operating systemfor desktop computers. DOS operating system consists of three parts in it, namely residentpart, initialization and the transient part. Most of the command programs are located inthe resident part. While booting, the number of files and buffers to open are contained inthe initialization part and transient part is flexible part of the operating system. Thecommands are not case sensitive.

    File:

    A file is a collection of related information. For example, like the contents of a file folder in adesk drawer. Files on the disk can contain letters, memos and executable programs.

    Program:

    Programs are special types of files. These are series of instructions written in computerlanguages. This program instructs the computer to perform the task.

    Directory:

    DOS uses a filing system to store its files. The filing system uses storage areas calleddirectories. A directory is nothing more than an expandable file folder that can hold otherexpandable file folders. These file folders hold the data files. A directory is a table ofcontents for a disk. It contains the names of files, their sizes, and the dates they were last

    modified. All of the different directories are stored under one master directory. Thisdirectory is called the root directory.In addition to directories, it uses an area on a disk called the File Allocation Table (FAT).The FAT is similar to our contents page in our book. It holds the information where the fileis stored in the disk.

    Multilevel directories:

    When there are two or more users who share a computer, when you are working onseveral different projects, the number of files in the directory can become a large and

  • 7/25/2019 C programing Manual 2015 (Updated)

    20/75

    Computer Programming Lab Manual 2014-2015

    unwieldy. Using directories is one way that we can divide our files into convenient groups.Any one directory can contain many files. This directory may also contain other directoriesor sub directories. This organized file structure is called a hierarchical directory system.

    Specific features of UNIX:

    The commands in UNIX are considered to case sensitive. It means, lower case a anduppercase A are considered differently.

    Multitasking:

    It refers to performing a number of tasks simultaneously. For example when a document isprinted, you may run another program to sort large data and at the same time you may edita document in the foreground screen. UNIX switches between the tasks and executes themone by one at small interval of time. This process of sharing the CPU to perform varioustasks simultaneously is called time-sharing. The more number of the tasks are submittedthen we end up with slower response from the computer.

    Multi-user capability:

    UNIX allows the computer to be used by several users through several terminal connectedto a powerful computer. A terminal will have a keyboard and a monitor. The computer towhich terminals are connected is called as the host computer or server. Any user on theterminal can run various programs, read file information or print a document at the sametime. Multi user computer, are economical and efficient compared to stand-alonecomputers.

    Portability:

    One of the outstanding features of UNIX is its ability to port itself to another installation.

    For example, an application program developed in UNIX environment can be used in adifferent platform.

    Security

    UNIX provides a good security for users. The users are required to authenticate before theyuse the system. The password is encrypted.

    File system

    UNIX identifies three types of users, owner, group and others. For each group it providespermission on the files like to read, write and execute operation.

    We know, in information technology era, sharing of resources and easy communication areacting as a backbone of any network. Popular example is our Internet. With the help ofinternet we are able to exchange information and share resources. Hence in this chapter westudy different advantages of the network and different forms of the network and theirfeatures.

    Networking of computers and its advantages.

    Computer network is defined as an interconnection of autonomous computer. Hereautonomous means, there is no master and slave relationship. All computers are equal.

  • 7/25/2019 C programing Manual 2015 (Updated)

    21/75

    Computer Programming Lab Manual 2014-2015

    Computer network enables to share the resources. Computer networking also refers toconnecting computers to share data, application software and hardware devices. Networksallow sharing of information among various computers and permit users to share files. Forexample a students accesses compilers sitting at one place, where compiler may be storedon the other machine. The students takes printout with the help of one printer connectedto the network. The printer can be shared among many students.

    Network offers the opportunity to communicate more efficiently with others throughelectronic mail. Networks allow companies to share software and peripherals such asprinters, plotters, scanners and so on. With networking all the computers in an office canbe connected to a single printer and scanner. It also helps in using storage devicesefficiently. Computer network acts as a very powerful communication medium. It meanspeople exchange their information. When compared to mainframe computers, network ofcomputers saves money.

    Types of networks

    Depending the nature of the distances, protocols (the set of rules used for communication)the network can be classified into LAN (Local Area Network), MAN (Metropolitan AreaNetwork) and WAN (Wide Area Network).

    Local Area Network(LAN)A LAN (local area network) is a group of computers and network devices connectedtogether, usually within the same building. By definition, the connections must be high-speed and relatively inexpensive (e.g., token ring or Ethernet). They function to linkcomputers together and provide shared access to printers, file servers, and other services.Any individual computer connected to a network is called workstation. A workstation may

    not need a floppy disk or hard disk. A LAN or local area network connects computers andperipherals in a limited area. LAN requires cables to connect workstations. For exampleLAN is used in a hall or within a building. Figure 5.1 shows Local Area Network , wherevarious departments are connected.

    Fig: Local Area Network

    Metropolitan Area Network (MAN)

    A MAN (Metropolitan Area Network) is used to connect computers to cover the city ortown. The range may be approximately 50 Kilometers. Normally cables and fiber opticcables are used to connect computers. The routing of the messages is fast. Normally centrallibrary in a city may be connected by a MAN, so users can access the information. Figure 5.2shows a typical view of Metropolitan Area Network.

  • 7/25/2019 C programing Manual 2015 (Updated)

    22/75

    Computer Programming Lab Manual 2014-2015

    Wide Area Network (WAN)

    A WAN (Wide Area Network) covers large distance like state, country or continents.The WAN uses the fiber optics, cables and even satellites also. Here communication circuitsare connected with the help of hardware device called routers. Routers forward smallpieces of information called packets from one to another. Internet is the popular onecomes under WAN. Some of the examples makes use of internet are reservation of airplanetickets, railway tickets and even cinema tickets. Another facility called e-commerce, wherebusiness is carried out through internet. Here people can buy books, articles and so onthrough registering their wants through the internet. Figure 5.3 shows a typical view ofWide Area Network.

    Fig: Wide Area Network

    Internet

    The internet is a massive wide area network, connecting thousands of computer networksaround the world. The internet is a worldwide network of networks. It is a collection ofthousands of smaller networks in different countries around the world. It links thousandsof academic government, military and public computers, enabling millions of people toshare information and other resources.

    Internet pathways are used to exchange digitized computer data. The basic services thatform the foundation of the internet are e-mail, telnet and FTP. With internet we can easilyexchange electronic mail with friends and family anywhere in the world.

    Telnet allows you to connect to a remote computer. We can access any of the publicservices or tools and library databases at the remote site. FTP (File Transfer Protocol)provides for transferring files from one computer to another across the internet.

    Internet has many uses. For individuals, the most important uses of internet are e-mail andsurfing the Web. One can read the topics of interest like sports, a hobby, a country or any

    place of interest.

    E-mail:

    The e-mail stands for electronic mail. One of the major features of computer networking isthat messages can be sent electronically to various terminals on the network. The messagesare sent very quickly and accurately. E-mail uses the concept of Storing and forwardingmessages. It saves a lot of money for the users. Here user registers his/her account withone of the providers. The e-mail account normally contains username and the provider

  • 7/25/2019 C programing Manual 2015 (Updated)

    23/75

    Computer Programming Lab Manual 2014-2015

    name. For example abc @ yahoo.com, represents abc is the name of the user, who isregistered in yahoo provider.

    Internet

    Internet is a world-wide/global system of interconnected computer networks.

    Internet uses the standard Internet Protocol (TCP/IP) Every computer in internet is identified by a unique IP address. IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a

    computer location. A special computer DNS (Domain Name Server) is used to give name to the IP

    Address so that user can locate a computer by a name. For example, a DNS server will resolve a name http://www.tutorialspoint.comto a

    particular IP address to uniquely identify the computer on which this website ishosted.

    Internet is accessible to every user all over the world.

    Intranet

    Intranet is system in which multiple PCs are networked to be connected to each other. PCs in intranet are not available to the world outside of the intranet. Usually each company or organization has their own Intranet network and

    members/employees of that company can access the computers in their intranet. Each computer in Intranet is also identified by a IP Address, which is unique among

    the computers in that Intranet.

  • 7/25/2019 C programing Manual 2015 (Updated)

    24/75

    Computer Programming Lab Manual 2014-2015

    Similarities in Internet & Intranet

    Intranet uses the internet protocols such as TCP/IP and FTP. Intranet sites are accessible via web browser in similar way as websites in internet.

    But only members of Intranet network can access intranet hosted sites. In Intranet, own instant messengers can be used as similar to yahoo messenger/gtalk

    over the internet.Differences in Internet & Intranet

    Internet is general to PCs all over the world where Intranet is specific to few PCs. Internet is wider access and provides a better access to websites to large population

    whereas Intranet is restricted. Internet is not as safe as Intranet as Intranet can be safely privatized as per the need.

    Memory

    RAM is considered as Computer Memory as performance of a computer is directlyproportional to its memory and processor.

    Today's software and operating systems require high memory. Today, commonly used RAM is DDR3, which operates at 1066Mhz As per window 7, 1 GB is the minimum RAM required to function properly. Recommended - 4 GB.

    Hard Drive

    Hard disk is used for storage purpose. Higher the capacity, more data you can save init.

    Nowadays, computers are equipped with 500GB, which can be extended to 2TB. Most hard drives in desktop operate at the standard performance speed of 7200RPM.

  • 7/25/2019 C programing Manual 2015 (Updated)

    25/75

    Computer Programming Lab Manual 2014-2015

    Recommended - 500GB.

    CPU

    Frequency (GHz) - This determines speed of the processor. More the speed, betterthe CPU.

    Cores - Today's CPUs come with more than one core, which is like having more thanone CPU in the computer. Programs, which can take advantage of multi-coreenvironment, will run faster on such machines.

    Brand - Intel or AMD. Both are equivalent. Intel is in lead. Cache - Higher the L1, L2 cache, better the CPU performance. Recommended - Intel Core i3 i3-3225 3.30 GHz Processor.

    Input Devices

    Following are few of the important input devices which are used in Computer Systems

    Keyboard Light pen Graphic Tablet Optical Character Reader (OCR)Mouse Track Ball Microphone Bar Code Reader

    Joy Stick Scanner Magnetic Ink CardReader (MICR)

    Optical Mark Reader

    Keyboard

    Most common and very popular input device is keyboard. The keyboard helps in inputtingthe data to the computer. The layout of the keyboard is like that of traditional typewriter,although there are some additional keys provided for performing some additionalfunctions.

  • 7/25/2019 C programing Manual 2015 (Updated)

    26/75

    Computer Programming Lab Manual 2014-2015

    Keyboard is of two sizes 84 keys or 101/102 keys, but now 104 keys or 108 keys keyboardis also available for Windows and Internet.The keys are followingKeys Description

    1. Typing Keys These keys include the letter keys (A-Z) and digits keys (0-9)

    which are generally give same layout as that of typewriters.2. Numeric Keypad It is used to enter numeric data or cursor movement. Generally, it

    consists of a set of 17 keys that are laid out in the sameconfiguration used by most adding machine and calculators.

    3. Function Keys The twelve functions keys are present on the keyboard. Theseare arranged in a row along the top of the keyboard. Eachfunction key has unique meaning and is used for some specificpurpose.

    4. Control keys These keys provides cursor and screen control. It includes fourdirectional arrow key. Control keys also include Home, End,

    Insert, Delete, Page Up, Page Down, Control(Ctrl), Alternate(Alt),Escape(Esc).

    5. Special Purpose Keys Keyboard also contains some special purpose keys such as Enter,Shift, Caps Lock, Num Lock, Space bar, Tab, and Print Screen.

    Summary:

    Computer network is defined as a interconnection of autonomous computers. Computer networking enables us to connect computers to share data, application

    software and hardware devices. Networks allow sharing of information among various computers and permit users to

    share files. A LAN or local area network connects computers and peripherals in a limited area. A MAN covers the city or town. A Wide Area Network covers a large area.

    The internet is a massive wide area network, connecting thousands of computer networksaround the world.

    E-mail is a cost effective communication

  • 7/25/2019 C programing Manual 2015 (Updated)

    27/75

    Computer Programming Lab Manual 2014-2015

    Quiz questions

    1. Computer network defined as a interconnection of ---------- computers2. Computer network allows user to ----- the resources3. -------- network confined to hall or building.4. ------- is one example of WAN.

    5. ------ business is carried out through internet.6. Small piece of information called ---- are forwarded by router in Internet.Answers1. Autonomous2. share3. Local area4. Internet 5. E-commerce6. packets

    Exercise

    1. What is a computer network? What are the advantages of computer network?2. Briefly explain the Local area network, Metropolitan area network and wide area

    network.3. What e-mail? How e-mail works?4. What are the uses of Internet?

    Summary:

    A computer is an electronic device which takes information and process informationaccording to the program and produces the output.

    A computer system has five basic functional units. The Central Processing Unit is the brain of the computer. The arithmetic-logic unit (ALU) is the unit of the computer that performs arithmetic

    and logical operations on the data. The control unit controls the overall activities of the components of the computer. The memory unit is the unit where all the input data and results stored. Stored program concept uses the memory unit to store both instruction or operation

    code and data or operands.

    NIC

    Short for Network Interface Card, a NIC is also commonly referred to as an Ethernetcard and network adapter and is an expansion card that enables a computer to connect toa network such as a home network or the Internet using an Ethernet cable. A NetworkInterface Card (NIC) is a computer hardware component that allows a computer to connectto a network. NICs may be used for both wired and wireless connections.A NIC is also known as a Network Interface Controllers (NIC), Network Interface ControllerCard, expansion card, computer circuit board, network card or LAN cardEvery computer on a network, both clients and servers, requires a network interface card(or NIC) in order to access the network. A NIC is usually a separate adapter card that slides

  • 7/25/2019 C programing Manual 2015 (Updated)

    28/75

    Computer Programming Lab Manual 2014-2015

    into one of the server's motherboard expansion slots. However, most new computers havethe NIC built into the motherboard, so a separate card isn't needed.What is a Computer Network?A computer network is a system in which multiple computers are connected to each otherto share information and resources.

    Characteristics Share Resources from one computer to another Create files and store them in one computer, access those files from the other

    computer(s) connected over the network Connect a printer, scanner or a fax machine to one computer within the network and

    let other computers of the network use the machines available over network.Following is the list of hardwares required to set up a computer network:

    Network Cables Distributors Router Internal Network Cards External Network Cards Network Cables Network cables are used to connect computers. The most commonly used cable are

    Category 5 cable RJ-45.

  • 7/25/2019 C programing Manual 2015 (Updated)

    29/75

    Computer Programming Lab Manual 2014-2015

    Distributors

    Each and every computer can be connected to another one via a serial port, but if weneed to connect many computers to produce a network, this serial connection will notwork. The solution is to use a central body to which other computers, printers,scanners, etc., can be connected and then this body will manage or distribute networktraffic.

    Router

    A router is a type of device, which acts as the central point among computers andother devices that are part of a network.

    A router is equipped with holes called ports. Computers and other devices are connected to a router using network cables. Nowadays, router comes in wireless modes using which computers can be connected

    without any physical cable.

  • 7/25/2019 C programing Manual 2015 (Updated)

    30/75

    Computer Programming Lab Manual 2014-2015

    Network Interface Card (NIC)

    Network card is a necessary component of a computer without which a computercannot be connected over a network.

    Also known as network adapter or Network Interface Card (NIC). Most of branded computers have network card pre-installed. Network cards are of two types: Internal and External Network Cards

    Internal Network Cards Motherboard has a slot for internal network card where it is to be inserted. Internal network cards are of two types: First type uses Peripheral Component Interconnect (PCI) connection. Second type uses Industry Standard Architecture (ISA). Network cables are required to provide network access.

    External Network Cards Comes in two flavors: Wireless and USB based. Wireless network card needs to be inserted into the motherboard but no network

    cable is required to connect to network.

  • 7/25/2019 C programing Manual 2015 (Updated)

    31/75

    Computer Programming Lab Manual 2014-2015

    USB cards are easy to use and connect via USB port. Computer automatically detects USB card and can install the drivers required to

    support the USB network card automatically.

    What is Flash Memory?

    Overview and tutorial about the basics of what is semiconductor Flash memory, how it

    works, its performance, variants, applications & types of flash memory.Flash memory of a form of semiconductor memory is widely used for many electronics datastorage applications.Although first developed in the 1980s, the use of flash memory has grown rapidly in recentyears as forms the basis of many memory products.Flash memory can be seen in many forms today including flash memory USB memorysticks digital camera memory cards in the form of compact flash or secure digital, SDmemory. In addition to this flash memory storage is used in many other items from MP3players to mobile phones, and in many other applicationsThere are also different flash memory types and these different types are each suited to

    their own applications.

    What Is Flash memory?

    Flash memory storage is a form of non-volatile memory that was born out of a combinationof the traditional EPROM and E2PROM.In essence it uses the same method of programming as the standard EPROM and theerasure method of the E2PROM.One of the main advantages that flash memory has when compared to EPROM is its abilityto be erased electrically. However it is not possible to erase each cell in a flash memory

  • 7/25/2019 C programing Manual 2015 (Updated)

    32/75

    Computer Programming Lab Manual 2014-2015

    individually unless a large amount of additional circuitry is added into the chip. This wouldadd significantly to the cost and accordingly most manufacturers dropped this approach infavour of a system whereby the whole chip, or a large part of it is block or flash erased -hence the name.

    Today most flash memory chips have selective erasure, allowing parts or sectors of theflash memory to be erased. However any erasure still means that a significant section of thechip has to be erased.

    Flash memory history

    Flash memory dates back to around 1980 when the concept was developed at Toshiba byDr. FujioMasuoka. It was then later presented at the 1984 IEEE International ElectronDevices Meeting, IEDM held in San Francisco, California.The basic laboratory concept took a few years to develop into a product that could belaunched commercially. Intel introduced the first commercial chips onto the market in1988 - these neither were NOR based types.The NOR flash memories had relatively long erase and write times. Toshiba againdeveloped their technology further and were able to announce NAND technology at the1987 IEDM. This technology, though, still needed further development to take it through tocommercial launch.The advantage of NAND flash was that it had reduced erase and write times and it had agreater storage density.

    Flash memory advantages & disadvantages

    As with any technology there are various advantages and disadvantages. It is necessary toconsider all of these when determining the optimum type of memory to be used.

    FLASH MEMORYADVANTAGES

    FLASH MEMORYDISADVANTAGES

    Non-volatile memory Easily portable (e.g. USB memory

    sticks) Mechanically robust

    Higher cost per bit than hard drives Slower than other forms of memory Limited number of write / erase cycles Data must be erased before new data can

    be written Data typically erased and written in

    blocks

  • 7/25/2019 C programing Manual 2015 (Updated)

    33/75

    Computer Programming Lab Manual 2014-2015

    Flash memory typesThere are two basic types of Flash memory. Although they use the same basic technology,the way they are addressed for reading and writing is slightly different. They two flashmemory types are:

    1. NAND Flash memory: NAND Flash memories have a different structure to NORmemories. This type of flash memory is accessed much like block devices such as harddisks. When NAND Flash memories are to be read, the contents must first be pagedinto memory-mapped RAM. This makes the presence of a memory management unitessential.

    2. NOR Flash memory: NOR Flash memory is able to read individual flash memory cells,and as such it behaves like a traditional ROM in this mode. For the erase and writefunctions, commands are written to the first page of the mapped memory, as definedin "common flash interface" created by Intel.

    NAND / NOR tradeoff: NAND Flash memories and NOR Flash memories can be used fordifferent applications. However some systems will use a combination of both types of Flash

    memory. The NOR memory type is used as ROM and the NAND memory is partitioned witha file system and used as a random access storage area.Flash memory is a particularly important form of semiconductor memory. It is now widelyused and is possibly one of the most important forms of medium term storage. Asmentioned earlier Flash memory can be seen in a variety of forms and uses ranging fromFlash memory USB sticks to Compact Flash cards used for cameras. In addition to this manyother items of electronics can be seen using Flash memory ranging from mobile phones toMP3 players and many more. In view of its current importance, Flash memory will be seenin widespread use for many years to come.We store and transfer all kinds of files on our computers -- digital photographs, music files,word processing documents, PDFs and countless other forms of media. But sometimes yourcomputer's hard drive isn't exactly where you want your information. Whether you want tomake backup copies of files that live off of your systems or if you worry about yoursecurity, portable storage devices that use a type of electronic memory called flashmemory may be the right solution.Electronic memory comes in a variety of forms to serve a variety of purposes. Flashmemory is used for easy and fast information storage in computers, digital cameras andhome video game consoles. It is used more like a hard drive than as RAM. In fact, flashmemory is known as a solid state storage device, meaning there are no moving parts --everything is electronic instead of mechanical.Here are a few examples of flash memory:

    Your computer's BIOS chip Compact Flash (most often found in digital cameras) Smart Media (most often found in digital cameras) Memory Stick (most often found in digital cameras) PCMCIA Type I and Type II memory cards (used as solid-state disks in laptops) Memory cards for video game consoles

  • 7/25/2019 C programing Manual 2015 (Updated)

    34/75

    Computer Programming Lab Manual 2014-2015

    Flash memory is a type ofEEPROM chip, which stands for Electronically ErasableProgrammable Read Only Memory. It has a grid of columns and rows with a cell that hastwo transistors at each intersection (see image below).

    Flash Memory Operation & Technology

    Flash memory is an effective form of semiconductor memory.Flash memory operation is very similar to that of the older EPROM and EEPROMtechnologies.Flash memory operation is based around methods including Fowler-Nordheim tunnellingand hot electron injection.

    Flash memory operation basics

    Flash memory is a high density form of semiconductor memory. This is brought about bythe fact that each Flash memory cell is made up from a single field effect transistor and it isvery similar in structure to the ordinary EPROM.Each Flash memory cell consists of the basic channel with the source and drain electrodesseparated by the channel about 1 m long. Above the channel in the Flash memory cellthere is a floating gate which is separated from the channel by an exceedingly thin oxidelayer which is typically only 100 thick. It is the quality of this layer which is crucial to thereliable operation of the memory.

    Flash memory cell structure

    Above the floating gate there is the control gate. This is used to charge up the gatecapacitance during the write cycle.In the case of traditional EPROMs, these memory chips are erased by the application of UVlight. To accommodate these memory devices have a translucent window which can beexposed to the UV light. However this process takes upwards of twenty minutes. It alsorequires the memory chip to be removed from its circuit and placed in a special eraserwhere the UV light can be contained.

    The Flash memory cell functions by storing charge on the floating gate. The presence ofcharge will then determine whether the channel will conduct or not. During the read cycle a"1" at the output corresponds to the channel being in its low resistance or ON state.Programming the Flash memory cell is a little more complicated, and involves a processknown as hot-electron injection. When programming the control gate is connected to a"programming voltage". The drain will then see a voltage of around half this value while thesource is at ground. The voltage on the control gate is coupled to the floating gate throughthe dielectric, raising the floating gate to the programming voltage and inverting the

  • 7/25/2019 C programing Manual 2015 (Updated)

    35/75

    Computer Programming Lab Manual 2014-2015

    channel underneath. This results in the channel electrons having a higher drift velocity andincreased kinetic energy.Collisions between the energetic electrons and the crystal lattice dissipate heat whichraises the temperature of the silicon. At the programming voltage it is found that theelectrons cannot transfer their kinetic energy to the surrounding atoms fast enough andthey become "hotter" and scatter further afield, many towards the oxide layer. Theseelectrons overcome the 3.1 eV (electron volts) needed to overcome the barrier and theyaccumulate on the floating gate. As there is no way of escape they remain there until theyare removed by an erase cycle.The erase cycle for Flash memory uses a process called Fowler-Nordheimtunnelling. Theprocess is initiated by routing the programming voltage to the source, grounding thecontrol gate and leaving the drain floating. In this condition electrons are attracted towardsthe source and they tunnel off the floating gate, passing through the thin oxide layer. Thisleaves the floating gate devoid of charge.Generally the erase process is only made to last a few milliseconds. When complete eachFlash memory cell in the block is checked to ensure it has been completely erased. If not a

    second erase cycle is initiated.

    Programming Flash memoryIn the early days of flash memories one of the limiting factors in their uptake was the topicof programming Flash memory because they had a limited number of erase programmecycles. This was caused by the destructive breakdown of the thin gate oxide layer. Some ofthe early examples of flash memories only had a few hundred cycles. Now Flash memorytechnology is vastly improved and manufacturers quote figures that mean the Flashmemory life is no longer a concern.Most of this improvement in Flash memory has been brought about by improving thequality of the oxide layer. When samples of flash memory chips are found to have a lowerlifetime it is usually caused by the manufacturing process not being optimized for the oxidegrowth. Now programming Flash memory is not a problem and when using Flash memorythe chips are, within reason, not treated as items with a limited life.

    Flash memory access

    Flash memory is different to most other types of electronic memory in that while readingdata can be performed on individual addresses on certain types of flash memory, erase andwrite activities may only be performed on a block of a Flash memory. A typical block sizewill be 64, 128, or 256 kB. In order to accommodate this, the low level control softwareused to drive Flash memories, needs to take account of this if the read and write operations

    are to be performed correctly.Flash Memory Wear, Reliability & LifeOne of the issues with flash memory is that it has a finite lifetime and can only support afinite number of programme / write cycles. This process is known as flash memory wear.It is important to incorporate the flash memory wear and lifetime into any decisions aboutthe use of flash memory.Also when using flash memory, it is necessary to be aware of the lifetime and wearlimitations so that data is not lost.

  • 7/25/2019 C programing Manual 2015 (Updated)

    36/75

    Computer Programming Lab Manual 2014-2015

    Flash memory wear basics

    Significant improvements have been made in terms of flash memory wear since the firstflash devices were introduced. Originally the flash memory lifetime was measured in termsof a few thousand programme- erase cycles.Today most commercially available flash memory is guaranteed to withstand 100 000 ormore programme-erase cycles with some manufacturers guaranteeing a life of over 1 000000 cycles.

    Flash memories wear out mechanism

    The flash memory wear out mechanism results from the structure of the device.A typical device structure is seen below, and from this it can be seen that there are variouslayers and areas to the device.

    Flash memory cell structure

    The wear-out mechanism for flash devices occurs as a result of usage causing the tunneloxide layer to degrade. Although there are other mechanisms that can cause the device tofail, it is the tunnel oxide layer degradation that causes the flash memory wear issue.

    Flash memory uses a process called channel hot-electron injection for programming eachcell and Fowler-Nordheimtunnelling for the erase cycle. However it is found that electronscan become trapped within the oxide layer, and this electron trapping in the tunnel oxidereduces electric field during erase operations. In turn this gives rise to a in gradualdegradation of the erase characteristics and closure of memory cell threshold window.As a result charge trapping / de-trapping technology is key to the improvement of the flashmemory wear characteristics.

    Wear levelling

    In order to gain the maximum use from a flash memory, a process called wear levelling is

    used. The wear levelling technique is one that can be used in a variety of forms of memory,e.g. hard drives, etc., but is also very applicable to flash memories where it is widely used.The aim of the flash memory wear levelling functionality is to track which blocks have beenused, and to distribute the programme and erase cycles are distributed evenly across theavailable memory. By using the wear levelling techniques, no block should be used greatlymore than any other and therefore no single block prematurely fails due to a highernumber of programme-erase cycles.To achieve this, one block within the flash memory is designed to have an extendedlifetime, so that it can be used to track the usage and control the wear levelling.There are three main types of wear levelling mechanism that are used:

  • 7/25/2019 C programing Manual 2015 (Updated)

    37/75

    Computer Programming Lab Manual 2014-2015

    No wear leveling: The simplest option is not to use wear levelling. This approachmight be acceptable in circumstances where little use is expected and a reduction incomplexity is of paramount importance. Under these circumstances the Flashmemory controller permanently assigns the logical addresses from the operatingsystem to the physical addresses of the Flash memory. When a location is changed,the contents of that block must be erased and then re-programmed without any

    intelligence to reduce the number of programme-erase cycles. This is not only moretime consuming, but it also does nothing to reduce the flash memory wear.

    Dynamic wear leveling: Dynamic wear levelling uses a map to link Logical BlockAddresses, LBAs generated by the operating system, OS, to the physical Flash memorylocations. Each time the operating system writes new data, the map is updated so theoriginal physical block is marked as invalid data. A new block is then linked to thatmap entry. Each time a block of data is re-written to the Flash memory it is written toa new location.

    There is still a problem with this type of flash memory wear levelling with blocks of

    data that never get replaced. They remain with no additional wear.

    The name for this type of wear leveling comes from the fact that only the dynamicdata, i.e. data that is changed, is recycled. The memory may last longer than one withno wear leveling, but there will still be blocks of data that remain operable as a resultof low usage, long after the memory as a whole is inoperable as some areas haveexceeded the number of programme-erase cycles.

    Static wear leveling: This form of wear leveling is the most sophisticated andeffective. Static wear leveling also uses a map to link the Logical Block Addresses tophysical memory addresses.Static wear leveling works the same as dynamic wear leveling but with the addition

    that blocks of static data, i.e. data that does not change, are periodically moved so thatthese low usage cells are used by other data. By moving even static data periodically itlevels the usage and hence levels the wear across the whole memory.

    The various forms of wear leveling ensure that the maximum life is achieved for a flashmemory. The wear leveling algorithms combined with improved semiconductor lifetimes,means that flash memory is an effective form of solid state memory.

    Introduction:

    Flash memory or a flash RAM is a type of nonvolatile semiconductor memory device wherestored data exists even when memory device is not electrically powered. It's an improved

    version of electrically erasable programmable read-only memory (EEPROM). Thedifference between Flash Memory and EEPROM are, EEPROM erases and rewrite itscontent one byte at a time or in other words, at byte level. Whereas Flash memory erases orwrites its data in entire blocks, which makes it a very fast memory compared to EEPROM.Flash memory can't replace DRAM and SRAM because the speed at which the DRAM/SRAMcan access data and also their ability to address at byte level can't be matched by Flash.The flash memory is also termed as Solid-state Storage Device (SSD) due to the absence ofmoving parts in comparison to traditional computer hard disk drive.

  • 7/25/2019 C programing Manual 2015 (Updated)

    38/75

    Computer Programming Lab Manual 2014-2015

    Flash memory types:

    The two main types of flash memory are the NOR Flash & NAND Flash. Intel is the firstcompany to introduce commercial (NOR type) flash chip in 1988 and Toshiba releasedworld's first NAND-flash in 1989.

    NOR-flash is slower in erase-operation and write-operation compared to NAND-flash. Thatmeans the NAND-flash has faster erase and write times. More over NAND has smaller eraseunits. So fewer erases are needed. NOR-flash can read data slightly faster than NAND.NOR offers complete address and data buses to randomly access any of its memory location(addressable to every byte). This makes it a suitable replacement for older ROMBIOS/firmware chips, which rarely needs to be updated. Its endurance is 10,000 to1,000,000 erase cycles. NOR is highly suitable for storing code in embedded systems. Mostof the today's microcontrollers comes with built in flash memory.

    NAND-flash occupies smaller chip area per cell. This maker NAND available in greaterstorage densities and at lower costs per bit than NOR-flash. It also has up to ten times the

    endurance of NOR-flash. NAND is more fit as storage media for large files including videoand audio. The USB thumb drives, SD cards and MMC cards are of NAND type.NAND-flash does not provide a random-access external address bus so the data must beread on a block-wise basis (also known as page access), where each block holds hundredsto thousands of bits, resembling to a kind of sequential data access. This is one of the mainreasons why the NAND-flash is unsuitable to replace the ROM, because most of themicroprocessors and microcontrollers require byte-level random access.A write operation in any type of flash device can only be performed on an empty or erasedunit. So in most cases write operation must be preceded by an erase operation. The eraseoperation is fairly straightforward in the case of NAND-flash devices. But for a NOR-flash, it

    is mandatory that all bytes in the target block should be written with zeros before they canbe erased.The size of an erase-block in NOR-flash ranges from 64 to 128 Kbytes. Here a write/eraseoperation can take up to 5 s. But the NAND-flash has erase blocks 8 to 32 Kbytes in size. Soit is obvious that the NAND performs the identical operation in a lesser time duration.INOR-flash interface resembles closely to a SRAM memory interface, which has enoughaddress pins to map its entire media, allowing for easy access to every byte contained in it,whereas the NAND-flash go for serially accessed complicated I/O mapped interface. Herethe same pins are used for control, address & data.In traditional single-level cell flash devices, each cell stores only one bit of information.Later, many developers have developed a new form of flash memory known as multi-level

    cell flash that can store/hold more than one bits rather than a single bit in each memorycell, thus doubling the capacity of memory.

    QUIZ QUESTIONS

    1) A Computer consists of --- units.a) 3 b) 4 c) 5 d) 6

    2) Keyboard is an example of ------ unit.a) Memory b) Input c) Output d) ALU

    3) ALU stands for -------

  • 7/25/2019 C programing Manual 2015 (Updated)

    39/75

    Computer Programming Lab Manual 2014-2015

    a) Arithmetic Logic Unit b) Arithmetic Lower Unit c) Add Logical Unitd) None of the above4) RAM is considered as a ----------

    a) Volatile Memory b) Nonvolatile Memory c) Permanentd) None of the above

    5) ------ contains the program during the manufacturing itself.a) RAM b) ROM c) Both a and b d) None of the above

    6) ------- unit is used to store information.a) Input b) Output c) Control d) Memory

    7) In Stored program concept ---- and --- are stored in the same memory.a) Data and Instruction b) Data and Operands c) Instruction and operation coded) None of the above

    8) Microprocessor is the heart of ------ computer.a) Digital b) Analog c) Both a and b d) None of the above

    Answers:

    1 c 2 b 3 a 4 a 5 b 6 d 7 a 8 a

    Exercises

    1. Mention the basic functional units of a computer?2. With a neat diagram explain the working organization of a computer?3. What is stored program concept or John Von Neumann concept?4. What is microprocessor?5. What are the differences between RAM and ROM?

  • 7/25/2019 C programing Manual 2015 (Updated)

    40/75

    Computer Programming Lab Manual 2014-2015

    PART B

    Program 1: Design and develop a flowchart or an algorithm that takes threecoefficients (a,b, andc) of a Quadratic equation (ax2+bx+c=0) as input and compute

    all possible roots. Implement a C program for the developed flowchart/algorithmand execute the same to output the possible roots for a given set of coefficients with

    appropriate messages.

    Algorithm

    Step 1. Start.Step 2. Input co-efficient of equation a, b, c.Step 3. IF any or all the coefficients are zero

    Print Invalid inputELSE

    d b2-4acr |d|

    IF d > 0

    r1 (-b +r)/ (2a)r2 (-b -r)/ (2a)Print Roots are REAL and

    DISTINCT

    Print r1, r2ELSE IF d < 0

    r1 -b/ (2a)r2 r/ (2a)Print Roots are COMPLEXPrint r1 +i r2, r1 - i r2

    ELSEr1 -b/ (2a)Print Roots are EQUAL

    Print r1, r1END IFEND IFEND IF.

    Step 4. Stop

    Flowchart

  • 7/25/2019 C programing Manual 2015 (Updated)

    41/75

    Computer Programming Lab Manual 2014-2015

    /* C Program Find the Roots of Quadratic Equation */

    #include #include #include

    void main ( ){

    int a, b, c;float d, x1, x2, r;

    clrscr ( );printf("Enter the three co-efficients:\n"); / * Accept three co-efficients * /scanf("%d%d%d", &a, &b, &c);if (a* b* c == 0) / * Check for zero co-efficients * /{

    printf("\n Invalid Input ");}else{

    d = b * b - 4 * a * c;r=sqrt(fabs(d));

    if (d > 0){

    x1 = (-b +r) / (2.0*a);x2 = (-b -r) / (2.0*a);

    printf("\n The roots are real and distinct\n");printf("\n The roots are \n 1) x1=%f\t\t \n 2) x2=%f",x1,x2);

    }else if (d == 0){

    x1 = x2 = -b/(2.0*a);printf("\n The roots are real and equal\n");printf("\n The roots are: \n 1) x1=x2=%f",x1);

    }else{

    x1 = -b / (2.0 * a);x2 =r / (2.0*a);printf("\n The roots are real and imaginary\n");printf("\n The roots are:\n 1) %f +i %f \t\t\n 2) %f i %f

    ",x1,x2,x1,x2);}

    }

  • 7/25/2019 C programing Manual 2015 (Updated)

    42/75

    Computer Programming Lab Manual 2014-2015

    getch( );}

    Sample Output

    First Run

    Enter the three co-efficients:1 4 4The roots are real and equal

    The roots are:X1=X2=2.0000

    Second Run

    Enter the three co-efficients:1 -5 6The roots are real and distinctThe roots are:X1=3.0000X2=2.0000

    Third Run

    Enter the three co-efficients:2 3 4The roots are real and imaginary

    The roots are:1) -0.750000 +i 1.1989582) -0.750000 - i 1.198958

    Fourth Run

    Enter the three co-efficients:1 0 5Invalid Input

  • 7/25/2019 C programing Manual 2015 (Updated)

    43/75

    Computer Programming Lab Manual 2014-2015

    Program 2: Design and develop an algorithm to find thereverse of an integer numberNUM and check whether it is PALINDROME or NOT. Implement a C program for the

    developed algorithm that takes an integer number as input and output the reverse of

    the same with suitable messages. Ex: Num: 2014, Reverse: 4102, Not a Palindrome.

    Algorithm

    Step 1. StartStep 2. Input nStep 3. Initialize num n, rev 0, rem 0.Step 4.Repeat until n NOT EQUAL TO 0

    Compute rem n % 10Compute rev rev *10 + rem.Compute n n / 10.

    END until

    Step 5. Print revsStep 6. Check IF num EQUAL TO rev

    Print Palindrome.ELSE

    Print Not a Palindrome.Step 7. Stop.

    FLOW CHART

  • 7/25/2019 C programing Manual 2015 (Updated)

    44/75

    Computer Programming Lab Manual 2014-2015

    /* C Program to reverse a given integer number and check whether it is apalindrome or not. */

    #include

    #include

    void main( ){

    int n, rev=0, rem, num;

    clrscr ( );printf("Enter a number : ");scanf("%d", &n);num = n;while(n != 0){

    rem=n%10;rev= rev*10+rem;n = n / 10;

    }

    Printf(The reverse of %d is %d, num, rev);if(num==rev)printf("\n The given Number %d is Palindrome", num);elseprintf("\n The given Number %d is not Palindrome", num);

    getch( );}

    Sample Output

    First Run

    Enter a number:2018

    The reverse of 2018 is 8102The Number 2018 is not Palindrome

    Second Run

    Enter a number:5665

    The reverse of 5665 is 5665The Number is Palindrome

  • 7/25/2019 C programing Manual 2015 (Updated)

    45/75

    Computer Programming Lab Manual 2014-2015

    Program 3: a) Design and develop a flowchart to find the square root of a givennumberN. Implement a C program for the same and execute for all possible inputs

    with appropriate messages. Note: Dont use library functionsqrt (n).

    Algorithm

    1) Start

    2) Read num3) If num=0

    print error4) Otherwise for i=0 to num repeat step 5

    5) If i*i >num

    i=i*jbreak

    end if6) Print i as square root value7) End if8) Stop

    //Program to find the square root of a number without using library function#include #include #include int main( ){

    float n, temp=0.0, s;clrscr ( );printf("ENTER ANY NUMBER : ");scanf("%f", &n);s = n/2;while (s != temp){

    temp = s;s = (n/s+s)/2;

    }printf("\nSQRT = %.3f, s");printf(\nSQRT by built-in function = %.3f, sqrt(n));getch ( );return 0;

    }

    Sample OutputRun 1

    ENTER ANY NUMBER: 4

    SQRT = 2.000SQRT by built-in function = 2.000

    Run 2

    ENTER ANY NUMBER: 2

    SQRT = 1.414SQRT by built-in function = 1.414

  • 7/25/2019 C programing Manual 2015 (Updated)

    46/75

    Computer Programming Lab Manual 2014-2015

    Program 3: b) Design and develop a C program to read ayear as an input and findwhether it is leap yearor not. Also consider end of the centuries.

    Algorithm

    1) Start2) Read year

    3) If year%4=0 and year % 100=0 or year%400=0

    Print Leap year4) Otherwise

    Print Not a Leap Year5) Stop

    Flowchart

    /* C program to check whether a year is leap year or not using if else statement.*/

    #include int main( ){

    int year;clrscr( );printf("Enter a year: ");scanf("%d",&year);if(year%4 == 0 && year%100 != 0 || year % 400 = = 0){

    printf("\n%d is a leap year.\n", year);}

    elseprintf("\n%d is not a leap year.\n", year);

    return 0;}

    Sample Output

    Run1

    Enter a year: 20002000 is a leap year

    Run 2

    Enter a year: 19001900 is not a leap year

    Run 3

    Enter a year: 20142014 is not a leap year

  • 7/25/2019 C programing Manual 2015 (Updated)

    47/75

    Computer Programming Lab Manual 2014-2015

    Program 4: Design and develop an algorithm for evaluating the polynomial f(x) =a4x4+ a3x3 +a2x2+a1x+a0 for a given value of x and its coefficients using Horners

    method. Implement a C program for the developed algorithm and execute for

    different sets of values of coefficients andx.

    Method: Evaluating a polynomial means, finding the value of f(x), given the value of x and

    the co-efficient a0, a1, a2, . . . . . , anIn general the polynomial can be of the form

    (a0 + x ( a1+ X ( a2 + X (a3 +. . .+ X( an-1 + x. an)))))In nested parenthesis expression, innermost parenthesis is evaluated first. So, sum (i.ef(x)) is initialized to a[n]*x. then from (n-1)th term to I term, sum is repeatedly calculated bythe expression sum= sum + a[i])*x. at last, 0 th term is added to sum.

    Algorithm

    Step 1. Start.Step 2. Read the value of number of co-efficients and store in n.Step 3. FOR i 0 to n in steps of 1Read the co-efficients and store in array a[ i]

    END FORStep 4. Read the value of x.

    Step 5.Compute sum a[n] * xStep 6. FOR i n - 1 to 0 in steps of 1

    Computesum = (sum + a[ i] ) * x;Compute sum = sum + a[0];END FOR.

    Step 7. Print the value of sum.Step 8. Stop.

    FLOW CHART

    Stop

  • 7/25/2019 C programing Manual 2015 (Updated)

    48/75

    Computer Programming Lab Manual 2014-2015

    / * C Program to evaluate the given polynomial using Horners method.* /

    #include #include void main( ){

    int n, i, x, a[10], sum=0;clrscr ( );printf("\n Enter the degree of the polynomial : ");scanf("%d", &n);printf("\n Enter the %d coefficients\n",n+1);for(i = 0 ; i 0 ; i - -){

    sum = (sum + a[i] ) * x;sum = sum + a[0];

    }printf("\n The sum of polynomial = %d", sum);getch( ) ;

    }

    Sample Output

    Enter the degree of the polynomial: 4Enter the 5 coefficients1 2 3 4 5Enter the value of x:2The sum of polynomial = 129

  • 7/25/2019 C programing Manual 2015 (Updated)

    49/75

    Computer Programming Lab Manual 2014-2015

    Program 5: Write C Program to compute Sin(x) using Taylor series approximationgiven by Sin(x) = x - (x3/3!) + (x5/5!) - (x7/7!) + . Compare the result with the

    built- in Library function and print both the results.

    Algorithm

    1) Start

    2) Read n3) Read degree4) Convert degree to ra