Computer Concepts and C Programming Unit 12310CCP13 by Sushma Shetty (Www.vtulife.com).PDF

August 23, 2017 | Author: Divya Shri | Category: Printer (Computing), Computer Hardware, Computer Monitor, Computer Data Storage, Touchscreen
Share Embed Donate


Short Description

basics...

Description

MANGALORE

COMPUTER CONCEPTS AND C PROGRAMMING Prepared by: SUSHMA SHETTY B.E. [email protected]

This notes is been circulated on self risk. Nobody can be held responsible if anything is wrong or any improper information or insufficient information provided in it.

References: Computer concepts and C programming techniques by Padma Reddy, The C Programming Language by Brian Kernighan and Dennis Ritchie, www.tutorialspoint.com, www.programmingsimplified.com, www.programiz.com, www.wikipedia.org.

Visit www.vtulife.com for all vtu notes, syllabus, question papers and placement materials.

1

www.vtulife.com

UNIT 1 INTRODUCTION TO COMPUTER SYSTEMS COMPUTER: A computer is an electronic device that is used to accept the data, process the data and give the desired output in human understandable language. Computer Tasks: Accept the data, Process or manipulate the data, Output the result in the form suitable for human understanding, Stores the input data, instructions and results. Example: PC, Laptop, Desktop, PDA.

FEATURES/ CHARACTERISTICS OF COMPUTERS: 1. Speed: Measured in MIPS (Millions of Instructions Per Second). Present digital computer speed is measured in terms of BIPS (Billions of Instructions Per Second). 2. Accuracy: Computer results are very accurate. 3. Reliability: Computer provides correct and consistent results everytime. 4. Storage Capability: hard disk, USB storage. 5. Versatility: Computers can perform many tasks based on the instructions feeded in it. 6. Diligence: Computers can continuously perform tasks without any break.

EVOLUTION OF COMPUTERS

Prepared By: Sushma Shetty

2

www.vtulife.com

ABACUS/ COUNTING FRAME: Calculating tool used for performing various arithmetic operations such as addition, subtraction, multiplication, division. PASCALINE: Pascal’s device Pascaline is also called as the ‘numerical wheel calculator’ and is one among the world’s first mechanical adding machines that could add/ subtract directly. DIFFERENCE ENGINE: Invented by Charles Babbage. It consists of a number of columns numbered from 1 to N. this is used to perform mathematical operations. ENIAC (Electronic Numerical Integrator And Computer): First electronic digital computer used to solve full range of computing problems. The disadvantage is that instructions were given to this computer by physically connecting the wires and using the switches. EDVAC (Electronic Discrete Variable Automatic Computer): It is used for various calculations in the preparation of hydrogen bomb. Unlike ENIAC, instead of using wires and switches, stored program concept is used i.e storing data and instructions in memory. It does automatic addition, subtraction, multiplication, division with fast memory. Disadvantage is that it uses much power and has a huge size. IBM PERSONAL COMPUTER: IBM (International Business Machine) PC more popularly used by common people. Size of the machine drastically reduced, less power consumption, memory was used for storing data.

BASIC PARTS OF A COMPUTER 1. 2. 3. 4.

Input devices Output devices System unit Storage devices

INPUT DEVICES: These devices allow the user to enter the data, commands, programs into the memory of the computer ie input to the computer. Eg: Keyboard, Mouse, scanner, digital camera etc. OUTPUT DEVICES: These devices are used to display the information generated by the computer to the user in human understandable language. Eg: Monitor, Printer, Speakers etc. STORAGE DEVICES: These are the devices which store the data, instructions and information fed to the computer. These data can be retained even when the computer is turned off. Eg: CD, DVD, floppy disk drive, CD-ROM, RAM, ROM, DVD-ROM etc.

Prepared By: Sushma Shetty

3

www.vtulife.com

SYSTEM UNIT: It is a box like case which consists of a motherboard and other electronic devices. The motherboard consists of two components namely Central Processing Unit (CPU) and memory. All these components which reside inside the system are internal devices. The various units are classified based on the visibility: 1. Units that are visible from the front end. 2. Units that visible from the back end. 3. Units that are inside the system unit. Visible from front end: 1. Power switch: Used to switch on and off the computer. 2. Reset button: Using this we can restart the computer. 3. Lights: Indicates read/write operation being performed on the hard disk. 4. Floppy disk drive: a slit into which floppy disk can be inserted. We can read or write the data into the floppy disk. 5. DVD/CD combo drive: Allows to read the data and write the data into CD. Visible from back end: Components of a computer are connected to the CPU using set of wires. These devices are connected using ports. The interfaces through which data can be sent to or received from the CPU are called as ports. The commponly used ports are: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

Power point: It is not a port but the place where the power plug has to be connected. Mouse port: where the mouse has to be connected. Keyboard port: where the keyboard is connected. USB ports: The devices such as camera, pen drive, printers, memory sticks can be connected. Parallel port: Older printers can be connected. New printers are normally connected to the USB port. Serial port: External modems are connected. Audio output: Used to connect head phones. MIC (Microphone) port TV Port Monitor/Video port: used to connect the monitor. Modem port: used to connect phone line using modem to access internet. Speaker port: To connect home stereo system.

Inside the system unit: 1. Mother board: it contains computer’s basic circuitry and other components of the computer. It contains connectors for attaching additional boards or cards. 2. CPU (Central Processing Unit): Looks like a chip or a mother board. It is called as the brain of the computer and is responsible for processing the data accurately for correct input. It has ALU (Arithmetic and Logic Unit) and Control Unit.

Prepared By: Sushma Shetty

4

www.vtulife.com

3. BIOS (Basic Input Output System): Built in software which is placed in the ROM (Read Only Memory) and is run at the start up for the system boot up. 4. Memory: To store the data and instructions. 5. Secondary memory: The data and instructions which has to be stored permanently. 6. Cards: It is printed circuit board that can be inserted into an expansion slot of a motherboard to give additional capabilities to our computer. Eg: video card, graphic card, network interface card (NIC). 7. SMPS (Switch Mode Power Supply): Converts AC current to DC current. This is essential for running various parts of the computer.

BASIC STRUCTURE OF A COMPUTER A computer can perform the following activities: 1. 2. 3. 4.

Accept data Process or manipulate the data Output the result in the form suitable for human understanding Stores the input data, instructions and results.

The above activities are performed by various units in the computer system. The communication between various units of the computer system is as in figure below: INPUT UNIT: The input devices are the input unit which are connected to the computer system. Eg: keyboard, mouse, scanner etc. Using this the user can perform the following operations: 1. User can enter data/instructions to the computer system. 2. It is the responsibility of the input device to convert the data into a form understandable by the computer. 3. The converted data is stored in the memory in the form of binary and then sent to CPU for further processing. OUTPUT UNIT: Using output unit, the processing unit can output the results in human understandable language. Eg: monitor, printer, speaker etc. MEMORY UNIT: It is divided into primary memory and secondary memory. It is used to:

Prepared By: Sushma Shetty

5

www.vtulife.com

1. Store instructions and data 2. Store intermediate results. CENTRAL PROCESSING UNIT (CPU): It is the brain of the computer. It executes the instructions one after the other with the help of CU and ALU. CONTROL UNIT (CU): It controls and co-ordinates the activities of all the units by issuing proper commands. The functions of the CU are: 1. 2. 3. 4.

Fetching instructions from memory. Decoding the instruction. Executing the instruction. Issue appropriate commands to ALU, memory, input, output devices.

ARITHMETIC LOGIC UNIT (ALU): Performs basic arithmetic operations: addition, subtraction, multiplication, division. It also performs logic operations.

STORED PROGRAM CONCEPT Storing data and instructions in memory as shown in figure below: The CPU then fetches the instructions from the memory and executes them one after the other.

The Von Newman Architecture based on stored program concept is as in figure below: The computer has four functional units: input, output, memory, CPU. If a series of instruction has to be executed without human intervention, the CU must perform the following sequence of operations: 1. FETCH: Obtain data or the next instruction to be executed from the memory. 2. DECODE: Identify the action to be taken, translate it into series of commands. Prepared By: Sushma Shetty

6

www.vtulife.com

3. EXECUTE: Issue the proper command to the ALU to perform the desired operation. 4. STORE: Results obtained after executing the program are stored in memory.

CATEGORIZING COMPUTERS Types of computers: 1. Data handling technique/based on technology a) Digital computers. Eg: PC b) Analog computers. Eg: slide rule, c) Hybrid computers. 2. Computers for individuals a) Desktop computers b) Workstations c) Notebook computers d) Tablet computers e) Handheld PCs f) Smart phones 3. Computers for organizations a) Network servers b) Minicomputers c) Mainframe computers d) Super computers DATA HANDLING DEVICES: Data handling is important in ensuring the integrity of research data since it addresses concerns related to confidentially, security, and preservation/retention of research data. DIGITAL COMPUTERS: Devices capable of solving problems by processing information in discrete form. It operates on data, including magnitudes, letters, and symbols, that are expressed in binary form—i.e., using only the two digits 0 and 1. ANALOG COMPUTERS: An analog computer is a form of computer that uses the continuously changeable aspects of physical phenomena such as electrical, mechanical, or hydraulic quantities to model the problem being solved. Eg: Speedometers, milk and food processing industries,petrol pump, thermostat of fridge HYBRID COMPUTERS: A hybrid computer is a type of computer that is designed to provide the features and functions that are found by both the digital and the analog computers. Eg: ECG monitor of a patient in a hospital. It takes in an analog signal that is the heartbeat of the patient and converts it into the digital format after processing it.

Prepared By: Sushma Shetty

7

www.vtulife.com

COMPUTERS FOR INDIVIDUALS: DESKTOP COMPUTERS: A personal computer in a form intended for regular use at a single location, as opposed to a mobile laptop or portable computer. WORKSTATIONS: A workstation is a high-end microcomputer designed for technical or scientific applications. Intended primarily to be used by one person at a time, they are commonly connected to a local area network and run multi-user operating systems. The term workstation has also been used to refer to a mainframe computer terminal or a PC connected to a network. NOTEBOOK COMPUTERS: It is also called as a laptop. It is a portable personal computer with a clamshell form factor, suitable for mobile use. A laptop has most of the same components as a desktop computer, including a display, a keyboard, a pointing device such as a touchpad (also known as a trackpad) and/or a pointing stick, and speakers into a single unit. TABLET COMPUTERS: Tablet computers or simply tablet, is a one-piece mobile computer. Devices typically have a touchscreen, with finger or stylus gestures replacing the conventional computer mouse. It is often supplemented by physical buttons or input from sensors such as accelerometers. An on-screen, hideablevirtual keyboard is usually used for typing. Tablets differentiate themselves by being larger than smart phones or personal digital assistants. HANDHELD PC: A Handheld PC, or H/PC for short, is a computer built around a form factor which is smaller than any standard laptop computer. It is sometimes referred to as a Palmtop. SMART PHONES: A smartphone is a mobile phone built on a mobile operating system, with more advanced computing capability and connectivity than a feature phone. The first smartphones combined the functions of a personal digital assistant (PDA) with a mobile phone. Later models added the functionality of portable media players, low-end compact digital cameras, pocket video cameras, and GPS navigation units to form one multi-use device. Many modern smartphones also include high resolution touchscreens and web browsers that display standard web pages as well as mobile-optimized sites. COMPUTERS FOR ORGANIZATIONS: NETWORK SERVERS: A network server is a computer designed to process requests and deliver data to other (client) computers over a local network or the Internet. Network servers typically are configured with additional

Prepared By: Sushma Shetty

8

www.vtulife.com

processing, memory and storage capacity to handle the load of servicing clients. Common types of network servers include:    

Web servers proxy servers FTP servers online game servers

MINICOMPUTERS: A minicomputer is a class of smaller computers that evolved in the mid-1960s and sold for much less than mainframe and mid-size computers from IBM and its direct competitors. MAINFRAME COMPUTERS: They are computers used primarily by corporate and governmental organizations for critical applications, bulk data processing such as census, industry and consumer statistics, enterprise resource planning, and transaction processing. SUPER COMPUTERS: A supercomputer is a computer at the frontline of contemporary processing capacity--particularly speed of calculation. Supercomputers play an important role in the field of computational science, and are used for a wide range of computationally intensive tasks in various fields, including quantum mechanics, weather forecasting, climate research, oil and gas exploration, molecular and physical simulations. Throughout their history, they have been essential in the field of counter-cryptography.

DIFFERENCES BETWEEN ANALOG, DIGITAL, HYBRID COMPUTERS: ANALOG

DIGITAL

HYBRID

Process the analog data which is continuous in nature

Process digital data which is binary in nature

Process digital data using analog solution

Data is processed by measuring

Data is processed by counting

Data is processed by combining the methods used in digital and analog computers.

They require very less memory and no memory

They require memory

They require less memory

Process mathematical and scientific data which is continuous in nature

Process mathematical and scientific data which is binary using complex logics

Accept analog data, process mathematical and scientific data and convert into digital data

Prepared By: Sushma Shetty

9

www.vtulife.com

PARTS OF A COMPUTER SYSTEM 1. 2. 3. 4.

hardware software data user

HARDWARE: The physical components which make up the computer system are called hardware. They are categorized as: 1. 2. 3. 4.

Input devices. Eg; keyboard, mouse Output devices. Eg: monitor, printer System unit. Eg: CPU, Video card, Sound card Storage devices. Eg: CD, DVD, RAM, ROM

SOFTWARE: A program is a set of instructions given to the computer to perform a specific task or activity. The set of programs that perform a specific jobs are called as software. DATA: The data is a piece of information that we input to the computer from the input device. The computer manipulates the data into information that we can understand and output the information. USER: The people who use computers are users. They are also part of computer system because they write programs, use it and make it perform the tasks as per their requirement.

THE INFORMATION PROCESSING CYCLE The sequence of events in processing information, which includes (1) input, (2) processing, (3) storage and (4) output. These processes work together and repeat over and over. 1. Input: entering data into the computer. 2. Processing: performing operations on the data. 3. Storage: saving data, programs, or output for future use. 4. Output: presenting the results.

ESSENTIAL COMPUTER HARDWARE Hardware is the term given to the components that make up a computer. This term was derived from the internal components of a computer which consists circuits, electronics, and in short anything that you could touch inside your computer. Hardware can be broken up into four parts:

Prepared By: Sushma Shetty

10

www.vtulife.com

1.

Processor

2.

Memory

3.

Input

4.

Output

PROCESSOR: The processor is the most important piece of hardware within your computer. It is the brain, the very intellect of these electronic machines. The processor, decodes and executes instructions that are sent to in via the many lanes within the motherboard. On a personal computer, the processor is usually a single chip or a set of chips on top on a circuit board. In some powerful computers, such as the super computers, they consists of many chips on a circuit board. Now in general, these chips are referenced to as central processing unit (CPU). MEMORY AND STORAGE DEVICES: MEMORY: There are two types of memory that are very common. Actually, only one is very common the - RAM or also known as the random access memory because of it is a static memory. Static memories are memories that do not store data always (as soon as you switch off the computer) - the memory becomes empty or resets itself. Dynamic memory or volatile memory stores data that is fixed and does not go off even if the computer is switch off. This is read only memory (ROM) which stores critical boot up information of the computer. An example is the BIOS chip which stores a ROM to ensure that it has the proper instructions needed for the computer to operate. STORAGE DEVICES: Storage devices are also known as magnetic storage devices because of the nature of these storage devices. This is the disk drive or the hard disk as it is commonly known. Within these disks are read/write heads like a tiny pin (like the gramaphone) this pin or head is used to read or write data into the disk. There are also other types of storage devices such as optical storage devices. These devices comprises of your DVD-Roms, CD-Roms, VCD, and so on. INPUT AND OUTPUT: These devices are known as input and output or shortly (I/O) because their purpose is to provide either input into the computer system or to provide an output from the computer system. Typical I/O hardware devices are Monitor, Keyboard, Mouse, Speakers, Microphone, Modem, Webcam, Headphones, Printers, Fax Machines, Joystick, Scanner, Touchpad.

DIFFERENCES BETWEEN STORAGE DEVICES AND MEMORY: STORAGE DEVICES

MEMORY

Capacity is more

Storage capacity is less

Contents are retained when computer is turned off

Contents are not stored as permanent memory to be retained after shut down

Accessing of data or programs are slow

It is faster

Prepared By: Sushma Shetty

11

www.vtulife.com

Less expensive

More expensive

Portable

Not portable since it is plugged into motherboard

ESSENTIAL COMPUTER SOFTWARE A program is a set of instructions given to the computer to perform a specific task or activity. The set of programs that perform a specific jobs are called as software. Two types: 1. System software 2. Aoolication software SYSTEM SOFTWARE: System software (or systems software) is computer software designed to operate and control the computer hardware and to provide a platform for running application software. The operating system (prominent examples being Microsoft Windows, Mac OS X and Linux), allows the parts of a computer to work together by performing tasks like transferring data between memory and disks or rendering output onto a display device. It also provides a platform to run high-level system software and application software. APPLICATION SOFTWARE: Application software is all the computer software that causes a computer to perform useful tasks (compare with computer viruses) beyond the running of the computer itself. A specific instance of such software is called a software application, application or app. SYSTEM SOFTWARE Collection of programs that help the user to interact with the hardware components efficiently.

To write such programs, understanding the hardware architecture of the system is needed.

APPLICATION SOFTWARE Collection of programs written for specific application. Application software uses the services of the system software to interact with the hardware components. The programmer need not worry about the hardware architecture.

Directly interact with hardware.

Interact with hardware using system calls.

Development of system software is complex task.

Development of application software is relatively easier.

Eg: compiler, assembler, operating system

Eg: MS-WORD, Paint, ticket reservation etc.

System software control and manage the hardware.

Prepared By: Sushma Shetty

12

www.vtulife.com

INTERACTING WITH COMPUTER INPUT DEVICES 1. Keyboard 2. Pointing devices a) Mouse b) Track ball c) Track pad d) Pointers in the keyboard (Track point) 3. Hand held devices a) Pen b) Touch screen c) Game controllers 4. Optical devices a) Bar code readers b) Scanners and OCR 5. Audiovisual Input devices a) Microphone b) Video input c) Digital cameras KEYBOARD: In computing, a keyboard is a typewriter-style device, which uses an arrangement of buttons or keys, to act as mechanical levers or electronic switches. A keyboard typically has characters engraved or printed on the keys and each press of a key typically corresponds to a single written symbol. However, to produce some symbols requires pressing and holding several keys simultaneously or in sequence. While most keyboard keys produce letters, numbers or signs (characters), other keys or simultaneous key presses can produce actions or execute computer commands. Standard keyboard layout is the QWERTY layout. The other form is DWORAK. The types of keys are: 1. Alphanumeric and character keys : A-Z, 0-9, {,} , tabs, capslock etc. 2. Numeric keypad : when numlock on or off. 3. Modifier keys : shift keys. 4. Cursor movement keys : the arrows for movement of cursor. 5. Function keys : The F1, F2, … F9 keys. 6. Special purpose keys : start key, shortcut key, ESC, Print scrn.

Prepared By: Sushma Shetty

13

www.vtulife.com

POINTING DEVICES: Input devices which can control the movement of cursor on the screen. MOUSE: In computing, a mouse is a pointing device that functions by detecting two-dimensional motion relative to its supporting surface. Physically, a mouse consists of an object held under one of the user's hands, with one or more buttons. The mouse sometimes features other elements, such as "wheels", which allow the user to perform various system-dependent operations, or extra buttons or features that can add more control or dimensional input. The mouse's motion typically translates into the motion of a pointer on a display, which allows for fine control of a graphical user interface. The various actions performed are: 1. 2. 3. 4. 5.

Pointing Clicking Double clicking Dragging Scrolling

VARIANTS OF MOUSE: 1. TRACK BALL: A trackball is a pointing device consisting of a ball held by a socket containing sensors to detect a rotation of the ball about two axes—like an upside-down mouse with an exposed protruding ball. The user rolls the ball with the thumb, fingers, or the palm of the hand to move a pointer. Compared with a mouse, a trackball has no limits on effective travel; at times, a mouse can reach an edge of its working area while the operator still wishes to move the screen pointer farther. With a trackball, the operator just continues rolling, whereas a mouse would have to be lifted and re-positioned. Large trackballs are common on CAD workstations for easy precision. The disadvantage is that dust accumulates in its chamber. 2. TOUCH PAD: It is a pointing device featuring a tactile sensor, a specialized surface that can translate the motion and position of a user's fingers to a relative position on screen. Touchpads are a common feature of laptop computers, and are also used as a substitute for a mouse where desk space is scarce. Because they vary in size, they can also be found on personal digital assistants (PDAs) and some portable media players. Wireless touchpads are also available as detached accessories. 3. TRACK POINT: It is typically mounted in a computer keyboard on a laptop or desktop computer. Movements of the pointing stick are echoed on the screen by movements of the pointer (or cursor) and other visual changes. The pointing stick operates by sensing applied force, by using a pair of resistive strain gauges. The velocity of the pointer depends on the applied force. On a QWERTY keyboard, the stick is typically embedded between the "G", "H" and "B" keys, and the mouse buttons are placed just below the space bar.

Prepared By: Sushma Shetty

14

www.vtulife.com

HAND HELD DEVICES: 1. PEN: Pen computing refers to a computer user-interface using a pen (or stylus) and tablet, rather than devices such as a keyboard, joysticks or a mouse. Pen computing is also used to refer to the usage of mobile devices such as wireless tablet personal computers, PDAs and GPS receivers. The term has been used to refer to the usage of any product allowing for mobile communication. An indication of such a device is a stylus, generally used to press upon a graphics tablet or touchscreen, as opposed to using a more traditional interface such as a keyboard, keypad, mouse or touchpad. 2. TOUCH SCREEN: A touchscreen is an electronic visual display that the user can control through simple or multi-touch gestures by touching the screen with one or more fingers. Some touchscreens can also detect objects such as a stylus or ordinary or specially coated gloves. The user can use the touchscreen to react to what is displayed and to control how it is displayed (for example by zooming the text size). The touchscreen enables the user to interact directly with what is displayed, rather than using a mouse, touchpad, or any other intermediate device (other than a stylus, which is optional for most modern touchscreens). 3. GAME CONTROLLERS: A game controller is a device used with games or entertainment systems to provide input to a video game, typically to control an object or character in the game. A controller is usually connected to a game console or computer by means of a wire or cord, although wireless controllers are also widespread. Input devices that have been classified as game controllers include keyboards, mice, game pads, joysticks, etc. Special purpose devices, such as steering wheels for driving games and light guns for shooting games, are also game controllers. OPTICAL DEVICES (DATA SCANNING DEVICES) The device which uses light as a source of input for detecting or recognizing various things is calles as an optical input device. 1. BAR CODE READERS: A barcode reader (or barcode scanner) is an electronic device for reading printed barcodes. Like a flatbed scanner, it consists of a light source, a lens and a light sensor translating optical impulses into electrical ones. Additionally, nearly all barcode readers contain decoder circuitry analyzing the barcode's image data provided by the sensor and sending the barcode's content to the scanner's output port. 2. SCANNERS: It is a device that optically scans images, printed text, handwriting, or an object, and converts it to a digital image. Common examples found in offices are variations of the desktop (or flatbed) scanner where the document is placed on a glass window for scanning. Hand-held scanners, where the device is moved by hand, have evolved from text scanning "wands" to 3D scanners used for industrial design, reverse engineering, test and measurement, orthotics, gaming and other applications.

Prepared By: Sushma Shetty

15

www.vtulife.com

3. OPTICAL CHARACTER RECOGNITION (OCR): Optical character recognition, usually abbreviated to OCR, is the mechanical or electronic conversion of scanned images of handwritten, typewritten or printed text into machine-encoded text. It is widely used as a form of data entry from some sort of original paper data source, whether documents, sales receipts, mail, or any number of printed records. It is a common method of digitizing printed texts so that they can be electronically searched, stored more compactly, displayed on-line, and used in machine processes such as machine translation, text-to-speech and text mining. OCR is a field of research in pattern recognition, artificial intelligence and computer vision.

4. OPTICAL MARK READER (OMR): The Optical Mark Reader is a device that reads pencil marks on NCS compatible scan forms such as surveys or test answer forms. In this document The Optical Mark Reader will be referred to as the scanner or OMR. The computer test forms designed for the OMR are known as NCS compatible scan forms. Tests and surveys completed on these forms are read in by the scanner, checked, and the results are saved to a file. This data file can be converted into an output file of several different formats, depending on which type of output you desire. AUDIOVISUAL DEVICES 1. AUDIO DEVICES: Audio devices allow you to play or record audio, which can be sounds, music, speech, etc. These devices can be interesting for a forensic investigator, as they can often contain not only audio files, but also text documents, images and so on. 2. MICROPHONE: It is an acoustic-to-electric transducer or sensor that converts sound into an electrical signal. Microphones are used in many applications such as telephones, tape recorders, karaoke systems, hearing aids, motion pictureproduction, live and recorded audio engineering, FRS radios, megaphones, in radio and television broadcasting and in computers for recording voice,speech recognition, VoIP, and for non-acoustic purposes such as ultrasonic checking or knock sensors. 3. VOICE RECOGNITION DEVICES: Ability of a computer, computer software program, or hardware device to decode the human voice into digitized speech that can be interpreted by the computer or hardware device. Voice recognition is commonly used to operate a device, perform commands, or write without having to operate a keyboard, mouse, or press any buttons. Speech recognition (SR) is the translation of spoken words into

Prepared By: Sushma Shetty

16

www.vtulife.com

text. It is also known as automatic speech recognition (ASR) or computer speech recognition, speech to text (STT). 4. VIDEO INPUT DEVICES: Video input is the process of capturing and storing the full-motion recording into the computer. The various video input devices are: 1. VCR 2. Cam corder 3. Web cam 5. DIGITAL CAMERA: A digital camera (or digicam) is a camera that takes video or still photographs by recording images on an electronic image sensor. Most cameras sold today are digital and digital cameras are incorporated into many devices ranging from PDAs and mobile phones (called camera phones) to vehicles.

OUTPUT DEVICES They are electromechanical devices that accept the data from the computer and convert the data into a form that can be readable or understood by people or the user. Classification: 1. Soft copy devices a) Monitors b) Data projectors c) Sound systems 2. Hard copy devices a) Dot matrix printers b) Ink jet printers c) Laser printers d) Plotters SOFTCOPY OUTPUT DEVICES: The electronic version of an output such as a document or a file which is stored on a computer disc such as floppy disc, hard disc, CD or similar medium is called as softcopy. The output devices which can display this information stored in the computer are called softcopy output devices. HARDCOPY OUTPUT DEVICES: The physical form of output is the hardcopy. The devices which are used for creating the hard copy output are called hardcopy output devices.

Prepared By: Sushma Shetty

17

www.vtulife.com

SOFTCOPY

HARDCOPY

To see the output computer must be operating.

Computer is not required to see the output.

Modifications and updates are easier and changes are not visible. Cannot be distributed to people without computer.

Modifications and updates are difficult and changes are visible. Can be distributed to people who don’t have computer.

Requires less storage space.

Requires more storage space.

Searching for a information is easier.

Searching for a piece of information is difficult.

Very easy to duplicate

Difficult to duplicate

Not tangible (cannot be touched)

Tangible.

VIDEO SYSTEMS The devices or systems that produce the output so that we can see it are video systems. Eg: monitors, data projectors.

MONITORS They are the display devices that are housed in a plastic or metal case. A montor along with a keyboard is called video display terminal. Classification: 1. Monochrome monitors 2. Grayscale monitors 3. Color monitors Monochrome Monitors: Such monitors can display the text in only one color (such as white, green etc) with black background. It is cheap and is rarely found these days. Grayscale Monitors: They are capable of displaying multiple shades ranging from very light gray to black against white or partially white background. Color Monitors: It displays the text or images in varying colors. Present day color monitors can display between 16 colors and 16 million colors. They can be set to work in monochrome or grayscale mode. Based on technology monitors are classified as: 1. CRT monitors Prepared By: Sushma Shetty

18

www.vtulife.com

2. Flat panel monitors CRT Monitors: CRT (Cathode Ray Tube) monitor is a TV like display attached to the computer on which the output is displayed. COMPONENTS: 1. Electron gun: It generates a beam of electrons and is situated at the backend of the monitor as in figure. 2. Deflection plates (Magnetic coil): The electron beam is directed towards the screen in front of the tube using the deflection plates. 3. Phosphor: The back of the screen is coated with phosphor, a chemical that glows when it is hit by the electron beam. 4. Screen: The light emitted by the phosphor fades very rapidly and hence it is necessary to redraw the picture rapidly on the screen and thus displaying a continuous image. WORKING: The image is displayed on the screen when the electron gun traverses the screen in a fixed pattern writing on the pixel or not writing on the pixel as in figure. 1. The electrons from electron gun will hit every pixel on the screen starting from topleft corner horizontally. The beam can be turned on or off. This horizontal line of pixels is called as the scan line. 2. When the beam reaches right end of a scan line, the beam is turned off. The electron gun drops down a small distance and moves to the beginning of the new scan line. This is called horizontal trace and start scanning from left to right. 3. The above procedure is repeated for each scan line, till the beam gets to the right end of the last scan line. Now, the beam is turned off and moved to the starting point of the first scan line. This is vertical trace. 4. The above procedure shows one pass of scanning the screen. In case of a color monitor, each pixel in the color monitor has three phosphors- red, blue and green. By varying the intensities of these beams, various colors can be obtained. ADVANTAGES:

Prepared By: Sushma Shetty

19

www.vtulife.com

1. They provide bright and clear pictures. 2. The cost is really less when compared with other types of monitors. DISADVANTAGES: 1. 2. 3. 4.

The size of CRT monitor is big and hence take more desktop space. Heavy and hence not portable. More power to run. The screen is curved and hence diplay is across the curve.

Flat Panel Monitors: It has a flat screen, less weight and about one inch thick. These monitors are commonly used these days. They consume very less power and can be operated with battery built into the computer. These features are used in laptops also. They use a special kind of liquid crystals to display the images on the screen. They are transparent but when charged with electricity they become opaque. ADVANTAGES: 1. They occupy less desktop space. 2. Portable. 3. Require less power and run on battery. DISADVANTAGES: 1. Costlier compared to CRT. 2. Images are difficult to see in bright light. Two categories of LCD’S: 1. Passive matrix LCD monitor 2. Active matrix LCD monitor Passive matrix LCD monitor Each row and column of pixels are controlled by a set of transistors identified by row and column transistors. The color of the pixel is determined by the current coming out of transistor at the end of a row and top of the column.

Active matrix LCD monitor Each pixel has a transistor and can be turned on and off individually. The color of the pixel is determined by the current coming out of that transistor.

Inexpensive

Comparatively expensive

Narrow viewing angle

Wider viewer angle

Refreshing of pixels is slow

Refreshing of pixels is very fast

Prepared By: Sushma Shetty

20

www.vtulife.com

Uses dual scan LCD technology

Uses thin film transistor (TFT) technology

OTHER TYPES OF MONITOR: 1. Paper-white displays 2. Electroluminescent displays 3. Plasma displays MONITOR QUALITY: 1. Size: Monitors available in various sizes such as 14, 15, 17, 19, 21 inches. Larger monitors are relatively costlier. 2. Resolution: This term is associated with sharpness or clarity of the image displayed on the screen. It is determined by the number of pixels on the screen. 3. Refresh Rate: When an electron beam strikes the phosphor, the phosphor emits light resulting in the display of the image only for a fraction of a second. If we want to see the image properly, the screen has to refreshed with same data for atleast 60-70 times per second. This rate is called as the refresh rate. 4. Dot pitch: The distance between the two light colored pixels on the display screen is defined as dot pitch. The smaller the distance, sharper the image.

VIDEO CARD It is also called as video boards or video display boards or graphics card or graphics adapter. It is a physical hardware circuit board which is connected to the motherboard. It acts as a intermediate device between the CPU and monitor. The CPU sends the data or image to be displayed to video card. This device converts the text or image sent by the CPU into equivalent electrical signals. These signals are used by the electron gun to produce stream of electrons which displays the appropriate pixels. Thus, the text or images appear on the screen. The display capabilities of the computer depends on both the logical circuitry provided in the video adapter and the display monitor. By placing video card on the motherboard, the cost of the computer can be reduced. Eg: VGA (Video Graphics Array), Super VGA.

DATA PROJECTORS It is a special device used to display the output obtained from the computers on to a large screen on the wall. The data projectors are first connected to computer. The device projects the video output onto an external surface. They look and weigh like a camera. Usually used in classes, conferences. Two types:

Prepared By: Sushma Shetty

21

www.vtulife.com

1. LCD projectors 2. DLP projectors. LCD Projectors

DLP Projectors

Uses liquid crystal display technology

Uses digital light processing technology

Uses its own light source to display the information on the screen or wall

Uses many mirrors to reflect light

Room should be darkened

Room need not be darkened

SOUND SYSTEMS The devices or systems that produce sound are called sound systems. Eg: microphone and speaker, sound card, CD-ROM or DVD. Uses: 1. 2. 3. 4.

To create multi-media products. To watch video. Listen to music Videoconferencing and distance learning

Working:

1. 2. 3. 4. 5. 6.

Speaker speaks into microphone Microphone sends sound waves as input to sound card inside computer. Sound card converts audio signals into equivalent electric current. Current may be in form of voltage which is applied to electromagnet. The changing magnetic field pushes the magnet back and forth. The speaker attached to magnet moves and creates changes in the air pressure. The air pressure generated by speaker cone is interpreted as sound by brain.

SOUND CARDS It is a physical hardware circuit board which is connected to the motherboard or inserted into one of the computer’s internal expansion slots. This allows computer to produce sounds through speakers.

Prepared By: Sushma Shetty

22

www.vtulife.com

HEADPHONES AND HEADSET: A headphone consists of a pair of speakers which is attached to a strap that can be fitted to the wearer’s head, speakers placed in close proximity to the ears. A headset is a device which includes two speakers and a microphone mounted to a adjustable head strap. It can be used to make phone calls using PC, participate in video conferencing.

PRINTERS It is an output device that is used to print the text and graphical information on a physical medium such as paper. TYPES: 1. Impact printers a) Dot matrix printers b) Line printers c) Band printers 2. Non-impact printers a) Ink jet printers b) Laser printers IMPACT PRINTERS An impact printer works by physically striking an ink ribbon that is placed on the paper.the print head has pins that take the shape of a letter or character and when the hammer strikes the ribbon, the shape of the character is transferred through the inked ribbon onto the paper creating a printed character. ADVANTAGES: 1. 2. 3. 4.

Can create carbon copies Used for bulk printing Less expensive Maintenance is cheap

DISADVANTAGES: 1. Relatively slow 2. Print quality is poor 3. They are noisy NON-IMPACT PRINTERS It is a printer which forms the characters and images without making the physical contact between the printing mechanism and the medium on which the printing takes place. Ink is sprayed on the paper in the form of character.

Prepared By: Sushma Shetty

23

www.vtulife.com

ADVANTAGES: 1. 2. 3. 4. 5.

Produces high quality output. They are noiseless They can handle graphics unlike impact printers They handle wide variety of fonts They are relatively faster

DISADVANTAGES: 1. They are more expensive 2. Maintenance is costly IMPACT/ DOT MATRIX PRINTER

NON IMPACT/ INKJET/ LASER PRINTER

Works by striking an ink ribbon

Striking mechanism is not used. Spraying the ink or by using toner.

Very cheap

Costlier

Slow printing because of moving parts

Fast printing because of fewer moving parts

Carbon copies can be taken

Carbon copies cannot be taken

Noisy because of striking

Noiseless

Quality of print is not good

Good quality print

Prints only text

Prints text and graphics

Only standard text is supported

Varying fonts

Ex: line printer, dot matrix printer

Ex: ink jet, laser printer

DOT MATRIX PRINTER It is a character printer that prints all types of characters and images as a pattern of dots by striking against the ink ribbon. The hammer is a print head consisting of bi-directional pins and works as impact printers. This is the cheapest printer. WORKING: Let the letter ‘T’ has to be printed which is represented as in figure:

Prepared By: Sushma Shetty

24

www.vtulife.com

As the print head moves across the paper only the pins in the first column will strike the ribbon in turn will strike the paper. The sequence is as in figure below:

INKJET PRINTER It is a printer that forms all types of characters and images by spraying small drops of ink on the paper. They are non impact printers. WORKING: The working is similar to that of dot matrix printers. The character is produced by spraying small droplets of ink through tiny nozzles. Instead of print head, the inkjet printer uses ink nozzles. The commonly used ink jet printers are HP, Epson and Canon printers. LASER PRINTER It is a high quality, high speed non impact printer which operates in a manner similar to Xerox (photocopying) machine using laser technology. It uses laser beam to form images and it is transferred to paper electrostatically. WORKING: It has its own CPU and built in memory. The CPU interprets the data received from the computer and to control the laser. 1. The laser beam moves across the drum using the mirror and creates an image on the drum in the form of electrical charge. 2. The electrical charge on the drum attracts the toner particles, thus forming complete image to be printed on the paper. 3. The paper is taken from the tray and passed across the drum and the image is transferred on the paper.

Prepared By: Sushma Shetty

25

www.vtulife.com

4. The toner particles transferred on the paper are imprinted or fused permanently on the paper using heat or pressure. 5. The paper comes out of the printer. 6. After the document is printed, the electrical charge is removed from the drum. It is made ready for the next paper. Dot matrix printer

Laser printer

Impact printer

Non impact printer

Slow printing

Fast printing

Very cheap

Costlier

Carbon copies can be taken

Carbon copies cannot be taken

Produces noise

Don’t produce much noise

Print quality is not good

Print quality is very good

Prints only text

Prints both text and graphics

PLOTTERS A pen plotter similar to a printer is used to draw only continuous lines using a pen. Multicolored plotters use many colored pens to draw different colors. They are used in CAD applications. They are more expensive than printers.

PROCESSING DATA DATA/ INFORMATION Data is a representation of facts or concepts in an organized manner. Information is defined as a collection of data from which conclusions may be drawn. DATA

INFORMATION

Data is collection of facts and figures

Information is the result of processing of data

Data do not convey any meaning

It conveys meaning

Computers work with data

Computers do not work with information

Data is unstructured

Data is correctly organized

Prepared By: Sushma Shetty

26

www.vtulife.com

It is representation of information. So the representation may change

Even if data representation changes, information do not change.

NUMBER SYSTEM AND DATA REPRESENTATION NUMBER SYSTEM When we type some letters or words, the computer translates them in numbers as computers can understand only numbers. DECIMAL NUMBER SYSTEM: Decimal number system has base 10 as it uses 10 digits from 0 to 9. In decimal number system, the successive positions to the left of the decimal point represent units, tens, hundreds, thousands and so on. Each position represents a specific power of the base (10). For example, the decimal number 1234 consists of the digit 4 in the units position, 3 in the tens position, 2 in the hundreds position, and 1 in the thousands position, and its value can be written as (1x1000)+ (2x100)+ (3x10)+ (4xl) =(1x103)+ (2x102)+ (3x101)+ (4xl00) =1000 + 200 + 30 + 4 =1234 BINARY NUMBER SYSTEM: CHARACTERISTICS: 

Uses two digits, 0 and 1.



Also called base 2 number system.



Each position in a binary number represents a 0 power of the base (2).



Example 20. Last position in a binary number represents a x power of the base (2). Example 2x where x represents the last position - 1.

Eg: Binary Number: 101012 . Calculating Decimal Equivalent:

Prepared By: Sushma Shetty

27

www.vtulife.com

DECIMAL TO BINARY: STEPS:    

Step 1 - Divide the decimal number to be converted by the value of the new base. Step 2 - Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 - Divide the quotient of the previous divide by the new base. Step 4 - Record the remainder from Step 3 as the next digit (to the left) of the new base number.

Repeat Steps 3 and 4, getting remainders from right to left, until the quotient becomes zero in Step 3. The last remainder thus obtained will be the most significant digit (MSD) of the new base number. Eg: Decimal Number: 29. Calculating Binary Equivalent:

Binary equivalent: 11101 OCTAL NUMBER SYSTEM: CHARACTERISTICS: 

Uses eight digits, 0,1,2,3,4,5,6,7.



Also called base 8 number system

 

Each position in a octal number represents a 0 power of the base (8). Example 80 Last position in a octal number represents a x power of the base (8). Example 8x where x represents the last position - 1. Eg: Octal Number: 125708 . Calculating Decimal Equivalent:

Prepared By: Sushma Shetty

28

www.vtulife.com

HEXADECIMAL NUMBER SYSTEM: CHARACTERISTICS: 

Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F.



Letters represents numbers starting from 10. A = 10. B = 11, C = 12, D = 13, E = 14, F = 15.



Also called base 16 number system

 

Each position in a hexadecimal number represents a 0 power of the base (16). Example 160 Last position in a hexadecimal number represents a x power of the base (16). Example 16 xwhere x represents the last position - 1. Eg: Hexadecimal Number: 19FDE16 .Calculating Decimal Equivalent:

REPRESENTATION OF DATA The data are represented in the state of electronic switches. A switch with ON state represents 1 and a switch with OFF state represents 0. Letters, digits, sound, pictures are all represented using 0’s and 1’s. Characters have ASCII values wich are digits and they are represented in binary. Values which represent state of a switch is called bit.

Prepared By: Sushma Shetty

29

www.vtulife.com

UNITS OF DATA:

HOW CPU PROCESS DATA The processing of data is performed using following hardware units: 1. Central Processing Unit (CPU) 2. Memory CPU: The CPU is the brain of the computer, which executes instructions one after the other. The execution of each instruction is performed with the help of two basic parts: 1. Control unit 2. Arithmetic Logic Unit CONTRUL UNIT (CU): It controls and co-ordinates the activities of all the units by issuing proper commands. The various responsibilities of the control unit are: 1. 2. 3. 4.

Issue propersignals to the memory to fetch the next instruction to be executed. Decode the instruction. Execute the instruction. Issue proper command to ALU, memory, I/O units to get the job done.

INTERCONNECTION OF UNITS A group of wires connected between various sub-units of a computer to transfer the data/instructions is called PC bus or bus. Two types of PC bus: 1. System bus Prepared By: Sushma Shetty

30

www.vtulife.com

a) Data bus b) Address bus c) Control bus 2. I/O bus a) ISA bus b) PCI bus c) USB bus SYSTEM BUS: It is used to connect the CPU with RAM and cache memory. 1. Data bus: A group of wires used to transfer the data is called data bus. 2. Address bu: A group of wires exclusively used to transfer the address is called address bus. 3. Control bus: A group of wires used to transfer the control signals is called control bus.

THE I/O BUS:. It is used to connect all I/O devices with CPU and RAM. 1. ISA bus: ISA (Industry Standard Architecture) I/O bus was also 8 bit and ran at 4.77MHz. It typically runs much slower. One reason is the fact that the ISA bus clock and CPU clock run asynchronously, resulting in many wasted clock cycles. 2. PCI bus: (Peripheral Component Interface), the performance of PCI is much the same as VLB; it too is 32 bits wide and runs and 33MHz, resulting in a bandwidth of 127MB/sec. Two major advantages of PCI over VLB are the support for bus mastering and for Plug and Play. 3. USB: (Universal Serial Bus), helps to convert various devices such as keyboard, mouse, printer very quickly and easily.

MEMORY Two types: 1. Primary memory 2. Secondary memory

Prepared By: Sushma Shetty

31

www.vtulife.com

PRIMARY MEMORY/MAIN MEMORY: Primary memory holds only those data and instructions on which computer is currently working. It has limited capacity and data get lost when power is switched off. It is generally made up of semiconductor device. These memories are not as fast as registers. The data and instruction required to be processed earlier reside in main memory. It is divided into two subcategories RAM and ROM. Characteristic of Main Memory: 1. These are semiconductor memories. 2. It known as main memory. 3. Usually volatile memory. 4. Data is lost in case power is switch off. 5. It is working memory of the computer. 6. Faster than secondary memories. 7. A computer cannot run without primary memory. SECONDARY MEMORY: This type of memory is also known as external memory or non-volatile. It is slower than main memory. These are used for storing Data/Information permanently. CPU directly does 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 can access it.For example: disk, CD-ROM,DVD etc. Characteristic of Secondary Memory: 1. These are magnetic and optical memories. 2. It is known as backup memory. 3. It is non-volatile memory. 4. Data is permanently stored even if power is switched off. 5. It is used for storage of the data in the computer. 6. Computer may run without secondary memory. 7. Slower than primary memories.

Prepared By: Sushma Shetty

32

www.vtulife.com

CACHE MEMORY: Cache memory is a very high speed semiconductor memory which can speed up CPU. It acts as a buffer between the CPU and main memory. It is used to hold those parts of data and program which are most frequently used by CPU. The parts of data and programs are transferred from disk to cache memory by operating system, from where CPU can access them. ADVANTAGE 1. Cache memory is faster than main memory. 2. It consumes less access time as compared to main memory. 3. It stores the program that can be executed within a short period of time. 4. It stores data for temporary use. DISADVANTAGE: 1. Cache memory has limited capacity. 2. It is very expensive. RAM (Random Access Memory): A RAM constitutes the internal memory of the CPU for storing data, program and program result. It is read/write memory. It is called random access memory (RAM). Since access time in RAM is independent of the address to the word that is, each storage location inside the memory is as easy to reach as other location & takes the same amount of time. We can reach into the memory at random & extremely fast but can also be quite expensive. RAM is volatile, i.e. data stored in it is lost when we switch off the computer or if there is a power failure. 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 is of two types: Static RAM (SRAM), Dynamic RAM (DRAM). ROM (Read Only Memory): ROM stands for Read Only Memory. The memory from which we can only read but cannot write on it. This type of memory is non-volatile. The information is stored permanently in such memories during manufacture. A ROM, stores such instruction as are required to start computer when electricity is first turned on, this operation is referred to as bootstrap. ROM chip are not only used in the computer but also in other electronic items like washing machine and microwave oven.

Prepared By: Sushma Shetty

33

www.vtulife.com

PRIMARY MEMORY VS SECONDARY MEMORY 1. Processor access the primary memory in a random fashion. Unlike primary memory, secondary memory is not directly accessed through CPU. The accessing of the primary memory through CPU is done by making use of address and data buses, whereas input/ output channels are used to access the secondary memory. 2. The primary memory is embedded with two types of memory technologies; they are the RAM (Random Access Memory) and ROM (Read Only Memory). The secondary memory is accessible in the form of Mass storage devices such as hard disk, memory chips, Pen drive, floppy disk storage media, CD and DVD. 3. Primary memory is volatile in nature, while secondary memory is non volatile. The information that is stored in the primary memory cannot be retained when the power is turned off. In case of secondary memory, the information can be retrieved even if the power is turned off because the data will not be destructed until and unless the user erases it. 4. When the data processing speed is compared between the primary and secondary memory, the primary memory is much faster than the secondary memory. 5. In the cost perspective, the primary memory is costlier than the secondary memory devices. Because of this reasons most of the computer users install smaller primary memory and larger secondary memory. 6. As the secondary memory is permanent, all the files and programs are stored in the secondary memory most and as the primary memory interacts very fast with the micro processor, when the computer needs to access the files that are stored in the secondary memory, then such files are first loaded into the primary memory and then accessed by the computer.

MOTHERBOARD The motherboard serves as a single platform to connect all of the parts of a computer together. A motherboard connects CPU, memory, hard drives, optical drives, video card, sound card and other ports and expansion cards directly or via cables. It can be considered as the backbone of a computer. Features: 1. 2. 3. 4.

Motherboard varies greatly in supporting various types of components. Normally a motherboard supports a single type of CPU and few types of memories. Video Cards, Hard disks, Sound Cards have to compatible with motherboard to function properly. Motherboards, cases and power supplies must be compatible to work properly together.

MICROPROCESSOR It is a chip that contains the CPU. The microprocessors control the logic of almost all digital devices. CHARACTERISTICS: 1. Instruction set: set of instructions to be executed.

Prepared By: Sushma Shetty

34

www.vtulife.com

2. Bandwidth: the number of bits processed in one instruction. 3. Clock speed: determines the number of instructions to be executed per second.

MICROPROCESSOR ASSOCIATES The microprocessor is associated with the various components such as clock rate, motherboard, system bus etc. They determine the capacity of the micropreocessor and work with it in achieving a given task. The components are: 1. CLOCK RATE: The rate at which a processor completes its processing is called clock rate. It is measured in cycles per second (Hz). 2. MOTHERBOARD: It is the main circuit of the microcomputer that contains various connectors for attaching additional boards. The motherboard contains CPU, BIOS, memory, mass storage interfaces, serial and parallel ports, expansion slots. 3. SYSTEM BUS: It refers to the bus which connects CPU and memory. 4. CACHE MEMORY: The portion of main memory that a computer processor can access more quickly than a RAM. 5. INSTRUCTION PIPELINING: CPU can process millions or billions of instructions per second. In pipelining technique, when one instruction is being executed, another instruction can be fetched from the memory and decoded, thereby increasing execution speed. 6. HEAT SINK: It is a device that is attached to the microprocessor chip which is used to bring down the temperature of electronic device. The heat sink keeps away the processor from overheating by absorbing its heat and dissipating it in air.

TYPES OF MICROPROCESSOR 1. Complex instruction set computing (CISC) 2. Reduced instruction set computing (RISC) 1. CISC ARCHITECTURE: It is a special instruction set architectur in which each instruction can execute several low-level operations such as load from memory, an arithmetic operations and a memory store, all in a single instruction. Since each instruction is performing two or more primitive operations inside the processor, it is called complex instruction set.

Prepared By: Sushma Shetty

35

www.vtulife.com

CHARACTERISTICS: 1. 2. 3. 4. 5.

Emphasis is on hardware. All instructions are executed in two or more clock cycles. Variable instruction format demanding more decoding locgic and time. Easy to program. Complex data types were handled in hardware.

2. RISC ARCHITECTURE: It utilizes a small, highly optimized set of instructions. The idea here is simplified instructions can provide higher performance by faster execution of each instruction. CHARACTERISTICS: 1. 2. 3. 4. 5.

Emphasis is on software. All instructions are executed in one clock cycle. Uniform instruction format demanding less decoding logic and time. Difficult to program. Few data types in hardware. CISC PROCESSOR

RISC PROCESSOR

Instructions are complex

Instructions are simple

Program code size is smaller

Program code size is lengthier

Increased hardware circuitry and leads to increased processor size

Reduced hardware circuitry and leads to reduced processor size

It is less memory intensive

More memory intensive

Power consumption is more

Power consumption is less

More heat is generated

Less heat is generated

Prepared By: Sushma Shetty

36

www.vtulife.com

UNIT 3 FUNDAMENTALS OF PROBLEM SOLVING INTRODUCTION TO COMPUTER LANGUAGES    

PROGRAM: The set of instructions given to the computer to achieve a specific task. PROGRAMMING: process of providing instructions to solve a specific problem. PROGRAMMER: person who writes the program. PROGRAMMING LANGUAGE: the language that is used to write a program.

TYPES OF LANGUAGES:   

machine level language assembly level language high level language

1. MACHINE LEVEL LANGUAGE   



It is a set of instructions given to a computer in the form of 0’s and 1’s. It is the language of computers. ADVANTAGES: o Faster execution o Translator is not required. Since machine language is the language of computers, it can execute. DISADVANTAGES: o Difficult to remember machine instructions. o Difficult to read and write machine language programs. o Very difficult to debug, correct and modify the program. o Machine dependent and not portable ie its machine dependent program, program written for one machine may not be run in other with a different processor. o It is unstructured language.

2. ASSEMBLY LEVEL LANGUAGE   

Also called as symbolic language. A set of instructions given to a computer in the form of symbolic names or mneumonics. Eg: o ADD R1, R2 // adds values in register R1 and R2 and saved in R1 o MUL R1, R2

Prepared By: Sushma Shetty

37

www.vtulife.com







ADVANTAGES: o Easy to remember symbolic names than machine codes. o Program understanding, modification is easier compared to machine codes. o Simple and easy compared to machine language. o Execution of the same speed as to a equivalent machine language. DISADVANTAGES: o A translator is required. It is called as an assembler for assembly level language. o It is machine dependent. o It is unstructured language. o Difficult to understand and debug compared to high level languages. ASSEMBLER: It’s a translator which translates the program written in assembly language into machine language so that the computer can understand. For each assembly language instruction, corresponding machine instruction is generated.

3. HIGH LEVEL LANGUAGES     



It is written written using symbols and words just like English language. It enables the programmer to write machine independent code. Easy to read, write and maintain. They are portable. ADVANTAGES: o Easy to understand. o Easy to read, write and modify. o Code is compact and self explanatory. o They are machine independent programs. DISADVANTAGES: o Takes more time to execute compared to machine language or assembly language. o Translator is required.

COMPILER:  

It is a translator which accepts the program written in high level language and produces the corresponding machine language program (machine code). The compilation process is shown below

Prepared By: Sushma Shetty

38

www.vtulife.com

  

The compiler after accepting the program written in high level language, checks for the errors introduced by the programmer. Appropriate error messages are displayed. The errors can be corrected and compiled again until there are no errors in the program. Then the program is converted to machine code. Eg: Turbo C, Visual C/C++, gcc

CREATING AND RUNNING PROGRAMS: The steps involved in creating and running programs are: 1. 2. 3. 4.

Writing and editing programs Compiling programs Linking programs Program execution

1. WRITING AND EDITING PROGRAMS  The software used to write programs is called as an editor.  Using a text editor the following operations can be performed: o We can type the program, modify and store the program. o To correct the program we must be able to move the cursor in desired position. Its done using the cursor keys. o We should have familiarity of the complete editor by knowing various commands to modify such a search and replace etc.  The file which is inputto the compiler is the source file.  In Turbo C, the shortcut key is F2. 2. COMPILING A PROGRAM  Once we type a program, after completion we have to convert it into machine codes using a compiler (for a C program).  In Tubo C, the shortcut key is ALT+F9. 3. LINKING A PROGRAM  After compilation, the object program consisting of machine language is created, but cannot be directly executed.  The object code created must be combined to get an executable code.  In our C programs, we use library files, they must be linked before execution.  In Turbo C, the shortcut key is Ctrl+F9.

Prepared By: Sushma Shetty

39

www.vtulife.com

4. PROGRAM EXECUTION  The program can be executed and the result can be displayed on the output screen or a output device.

SYSTEM DEVELOPMENT LIFE CYCLE: 

The model which is commonly used is the waterfall model.



System requirements: In this phase, all the requirements, which are necessary to accomplish the proposed system are identified. The requirements are usually stated in terms that are understood by a user. Analysis: In this phase, the problem stated in the form of requirements is analyzed precisely and completely and we look at different alternatives from system point of view. Design: This phase will determine how the system will be built. The individual functions that make up the system are determined and the solution will be expressed in the form of algorithm or flowchart, etc. Code: In this phase, the algorithm will be converted into programs using any of the programming language. These programs have to be tested by the programmer for his/her satisfaction. System Test: In this phase, all the programs and functions are tested together to make sure the system works as a whole. The results obtained will be compared with the test data that is prepared manually to make sure that system is working as expected by meeting the requirements identified in requirement phase. Maintenance: After the program is implemented, it should be properly maintained, ie taking care of the changing requirements of its users and systems. The program should be regularly updated or enhanced by adding additional capabilities. In any of the above phases, if any errors are identified, it has to be corrected by going back to the previous phase. Otherwise continue to the next phase.

 









Prepared By: Sushma Shetty

40

www.vtulife.com

INTRODUCTION TO C LANGUAGE INTRODUCTION  

C language is a high level language. Reasons for C language to be popular: o C is a structured programming language. o It is a high level language and hence easy to understand. o It has wide variety of operators using which a program can be written easily to solve a given problem. o Helps us to develop efficient programs. o C is machine independent. The program written on one machine will run on other machine also. o C program can be executed on many different hardware platforms.

BACKGROUND/ HISTORY: The C language is derived from various languages as shown below:  ALGOL: It is the first block structured language but never gained wide acceptance in USA.  BCPL (Basic Combined Programming Language) : the introduction of ALGOL gave way to the development of structured programming language designed by Martin Richards.  B: Ken Thomson developed a new language on similar lines of BCPL called B language. The first version of UNIX operating system is developed using B language.  C : Dennis Ritchie developed C language in 1972. It inherited many concepts from ALGOL, BCPL, B. but the concept of data types was newly introduced.  ANSI (American National Standards Institute): introduced standards for C language in 1989. This standard was adopted by ISO in 1990.  C++ : has all the features of C language along with concept of objects, polymorphism, inheritance etc. C is procedure oriented whereas C++ is object oriented.

STEPS TO LEARN C LANGUAGE:  

Learn alphabets of C language. Learn how one or more alphabets can be grouped together to form meaningful words. These meaningful words are tokens.

Prepared By: Sushma Shetty

41

www.vtulife.com





Learn how one or more words are grouped together to form meaningful sentences. These sentences are called instructions or statements. Learn how one or more sentences can be grouped together to form paragraphs. These constitute a complete program.

1. CHARACTER SET (ALPHABETS OF C)  Any symbol that is used while writing a C program is called a character or an alphabet. It can be a letter, digit or a special symbol.  All the characters that are used while writing C programs are called alphabets or character set. o Eg for alphabets:  Lower case letters: a b c …. z  Upper case letters: A B C…. Z  Digits: 0 to 9  Symbols such as ~ tilde, ^ caret, - minus, + plus sign etc…..  White spaces: character such as space, tab(\t), new line (\n), carriage return (\r) etc 2. C TOKENS  A token is a smallest or a basic unit of a C program. One or more characters are grouped in sequence to form meaningful words. These meaningful words are tokens.  Classification: o Keywords: if, for, while, etc o Identifiers: sum, length, i etc o Constants: 10, 10.5, ‘a’, “strng” etc o Operators: +, -, *, / etc o Special symbols: [], {}, () etc  Tokens involving single characters: +, -, *, /  Tokens involving two characters: ++, =  Tokens involving more than two characters: 100, length, 10.5 etc  Using these tokens, meaningful instructions are framed for a program.

KEYWORDS   

The tokens with predefined meaning in C language are called keywords. They are reserved for specific purpose and hence they are called as reserved words. The keywords available are:

Prepared By: Sushma Shetty

42

www.vtulife.com



Rules to be followed while using keywords are: o They should not be used as variable names, function names, array names etc. o The meaning of keywords cannot be changed by the user. o All keywords are written in lower case letters.

IDENTIFIERS 

  

Need for identifiers: o In computer memory, the data and instructions can be stored. Each piece of data or the instructions is stored at unique address in the memory of the computer. So it’s difficult for us to:  Access data or instructions using these addresses.  Manipulate data using these addresses.  Keep track of addresses of data stored in the memory. o These disadvantages are overcome by using identifiers. Identifiers are the names given to various program elements such as variables, constants, function names, array names etc. It is a word consisting of sequence of one or more letters or digits along with “_” (underscore). Some rules to frame identifiers: o First character should be a letter or underscore. o No extra symbols are allowed other than letters, digits, _ o Length can be maximum of 31 charaters. o Reserved words cannot be used as identifiers. o They are case sensitive. SUM is not equal to sum.

Difference between keywords and identifiers: KEYWORDS It has predefined meaning in a language. They are used for specific purpose in a language and hence they are also called as reserved words. They are the instructions given to the compiler.

Prepared By: Sushma Shetty

IDENTIFIERS They do not have pre defined meaning.

They are not instructions given to the compiler.

43

www.vtulife.com

Eg: if, for, while

They are names introduced into a program. Eg: sum, length, I, j, sum_calc

CONSTANTS  

It is a data item that does not change during the execution of a program. They cannot be modified in the program. Classification:

1. INTEGER CONSTANT  An integer is a whole number without any fraction part. No extra characters allowed other than + and – sign.  If + and – are there, they shoud precede the number, indicating a positive or a negative number.  Types: o Decimal : combination of digits from 0 to 9. It is a base 10 number. valid: 1000, 1354, 234, -9877, +65 invalid: 10,000 (no comma), 0.5 (decimal), 10 20 (space), 085 (prefix zero not allowed). o Octal : is a combination of digits from 0 to 7. It is a base 8 number. valid: 010, 0777, -065 invalid: 10,000, 0.5, 10 20, 085 (digit 8), 777 (should have prefix 0). o Hexadecimal : combination of digits from 0 to 9, also alphabets from ‘A’ to ‘F’ or ‘a’ to ‘f’. it is a base 16 number. It must be preceded by ‘0X’ or ‘0x’. valid: 0X12A, 0x13A, 0X a98 invalid: 10,000, 0Xabgh, 0x12c.ab, 0123 2. FLOATING POINT CONSTANT  They are base 10 numbers with fraction part such as 10.5 Prepared By: Sushma Shetty

44

www.vtulife.com

 

No characters other than + and – allowed (only as prefix to indicate positive or negative integer). Types: o Fractional form : integer part followed by a dot and a fractional part. Eg: 0.5, 9.5, 34.09, -122.7623, -9. , +.9 o Scientific notation : represented using scientific notation (exponential notation) has 3 parts:  Mantissa: eg: 9.86  e/E: eg: e, E  exponent: 3 which is equal to 9.86 X 103 the mantissa can be integer or a floating point number. Exponent has to be an integer.

3. CHARATER CONSTANT  a symbol enclosed within a pair of single quotes is called character constant.  Each character is associated with a unique value called an ASCII (American Standard Code for Information Interchange) value. CHARACTER CONSTANT ‘9’ ‘a’ ‘$’ ‘\n’ “9” ‘99’

VALID/INVALID valid Valid Valid valid invalid invalid

REASONS FOR INVALIDITY Escape character Double quotes not allowed Two characters not allowed

4. BACKSLASH CONSTANTS (ESCAPE SEQUENCE CHARACTERS)  An escape sequence character begins with a backslash and is followed by one character.  A backslash(\) along with some characters give rise to special print effects by changing the meaning of some characters.  Since an escape sequence character starts with backslash, they are called backslash constants. CHARACTER Bell Backspace Horizontal tab Vertical tab Newline Form feed Carriage return Quotation mark Apostrophe Question mark

Prepared By: Sushma Shetty

ESCAPE CHARACTER \a \b \t \v \n \f \r \’’ \’ \?

MEANING Beep sound Cursor moves towards left one position Cursor moves right by 8 positions This is usually not supported Cursor moves to the beginning of new line Not supported by some compilers Cursor moves towards beginning of current line Double quote Single quote Question mark

45

www.vtulife.com

Backslash NULL

\\ \0

Back slash Null character

5. STRING CONSTANT  A sequence of characters enclosed within a pair of double quotes is called string constant. The string always ends with NULL character denoted as ‘\0’.  It is enclosed in double quotes. STRING CONSTANT ‘9’ “9” “pace” “\n” ‘pace’ “pace cs” “”

VALID/INVALID Invalid Valid Valid Valid Invalid Valid Valid

REASONS FOR INVALIDITY Must be enclosed within “” Must be enclosed within “” Empty string

CODING CONSTANTS  

The data values that cannot be changed during execution of the program are called constants. The constants can be directly used in the program. Three different ways to code constants: o Literal constants o Defined constants o Memory constants

1. LITERAL CONSTANTS  The constants which do not have any name are called literal constants ie literal is an unnamed constant used to specify the data. ‘A’ 9 3.56 Sum+10 “RAMA”

Character literal Numeric literal Numeric literal 10 is numeric literal String literal

2. DEFINED CONSTANTS  The names that can be used as a substitute for constants such as integer constant or character constant or floating point constant or a string constant are called symbolic constants. They are also called symbolic names.  Since these constants are defined using preprocessor command define, they are also called as defined constants.

Prepared By: Sushma Shetty

46

www.vtulife.com

   

Eg: #define MAX_LENGTH 1024 Define the symbolic constants at the beginning of the program even if we can define it anywhere in between the program. For easy understanding. To distinguish between symbolic constants and other variables, its written in upper case. Eg prog: #include #define PI 3.14 int main() { printf(“pi value is %f”,PI); return 0; }

3. MEMORY CONSTANTS  The values stored in variables that cannot be changed are called memory constants or named constants. The memory constants have to be initialized when defining the variables using the qualifier const.  Eg: const float pi=3.14 o pi value cannot be changed. o The compiler generates necessary machine instructions to allocate 4 bytes of memory space and store the value 3.14 in it. o The qualifier const indicate that the data stored in that memory space cannot be modified. o If compiler encounters a statement trying to modify the value, it results in an error.  Eg: const float pi; pi=3.14 //error OTHER TOKENS  

Operators Special symbols

RANGE OF INTEGER 

Integers are classified into: o Unsigned integer o Signed integer

1. RANGE OF UNSIGNED INTEGER  Consider the table which shows representation of decimal numbers in binary using only 3 bits.

Prepared By: Sushma Shetty

47

www.vtulife.com

BINARY 000 001 010 011 100 101 110 111

DECIMAL 0 1 2 3 4 5 6 7

Minimum number

Maximum number 3 bit unsigned number ranges from 0 to 7 (min to max) =0 to 8-1 =0 to 23-1 So, 3 bit unsigned number range = 0 to 23-1

 

 4 bit unsigned number range= 0 to 24-1  8 bit unsigned number range= 0 to 28-1  In general, n bit unsigned range= 0 to 2n-1 For 16 bit machine, range = 0 to 65535 It can be represented in the form of a circle:

(65535+1)%65536=0 (65535+2)%65536=1 . . 

Eg: unsigned int n=300;

2. RANGE OF SIGNED INTEGER  Positive numbers using 3 bit:

Prepared By: Sushma Shetty

48

www.vtulife.com





o Sign bit( first bit) : 0 represents positive integer. So positive integer range 0 to 3. Negative numbers using 3 bit:

o Sign bit( first bit) : 1 represents negative integer. So range = -4 to -1 Using 3 bits range = -4 to +3 = -23-1 to 23-1-1 Using 4 bits range = 24-1 to 24-1-1 In general, for n bit = 2n-1 to 2n-1-1

BASIC/SIMPLE/PRIMITIVE DATA TYPES   

The data type defines the type of data stored in a memory location. The data type determines how much memory should be allocated for a variable. Various types of data such as integer constant, floating point constant, character constant etc. can be stored in memory during execution of a program. Data types classification: o Primitive data types or fundamental data types. o Derived data types: Derived data types are derived from the fundamental data type. Some of the derived data types are short int, long int, long double etc.

PRIMITIVE DATA TYPES  

The data types that can be manipulated by machine instructions are called primitive data types. Classification: o Char (character value) o Int (integer value) o Float (Floating point value) o Double (Double floating point value) o Void (Valueless)

Prepared By: Sushma Shetty

49

www.vtulife.com

INT 

 

 



In addition, there are a number of qualifiers that can be applied to these basic types. short and long apply to integers: o int a; o short int sh; o long int counter; int will normally be the natural size for a particular machine. short is often 16 bits long, and int either 16 or 32 bits. Each compiler is free to choose appropriate sizes for its own hardware, subject only to the the restriction that shorts and ints are at least 16 bits, longs are at least 32 bits, and short is no longer than int, which is no longer than long. The standard headers and contain symbolic constants for all of these sizes, along with other properties of the machine and compiler. ADVANTAGES: Since integer constants are exact quantities, they are used for o counting. o Indexing. DISADVANTAGES: o Higher range of numbers cannot be represented. o The numbers with fractional part cannot be represented and stored.

FLOAT  It is a keyword used to define floating point numbers in C language. N bit machine 16 bit machine 32 bit machine  

Size of float 4 bytes 8 bytes

Range of float 3.4E-38 to 3.4E38 1.7E-308 to 1.7E308

ADVANTAGES: o The numbers with fractional part or decimal points can be stored. o Higher precision and range when compered to integers. DISADVANTAGES: o They are not exact quantities and hence not used for counting, indexing. o Floating point numbers occupying more that 4 bytes cannot be represented. o Precision of more than 6 digits after the decimal point is not possible. o Floating point numbers are represented approximately by most computers.

DOUBLE  It is a keyword used to define long floating point numbers in C language. It is treated as long floating point number. N bit machine 16 bit machine 32 bit machine 

Size of double 8 bytes 16 bytes

Range of double 1.7E-308 to 1.7E308 3.4E-4932 to 1.1E4932

ADVANTAGES: o Higher precision and range when compared to floating point numbers.

Prepared By: Sushma Shetty

50

www.vtulife.com



DISADVANTAGES: o Not used for counting, indexing. o These numbers are represented approximately by most of the computers.

CHAR  Keyword which is used to define single character or a sequence of characters called string in C language.  This is a group of 8 data bits.  'C' represents either a letter of roman alphabet.  Small integer in the range of 0 through to +255.  To give a named memory area in which a single letter has to be stored  Declaration: char letter;  ADVANTAGES: o Used to represent characters or strings. VOID     

Empty data type. It does not occupy any space in memory. Declare explicitly that a function is not returning a value Declare explicitly that a function has no parameter Create generic pointer 'C' also supports several aggregate types including structure ,union ,enumeration and user defined types.

Prepared By: Sushma Shetty

51

www.vtulife.com

VARIABLES  

A variable is a named data storage location in computers memory. By using a variable name we are referring to the data stored in the location. A value that changes during the execution of the program is called variable. Rules of variables defining in C: o The variable name is a combination of alphabets, digits, underscore etc. o The first character in the variable name must be an alphabet. o A keyword cannot be used as variable name o No comma or blanks are allowed in variable name. o No special symbols ($, #) other than underscore can be used in variable name. o Uppercase & lowercase letters are distinct i.e. case sensitive o A variable name can’t start with digit.

Prepared By: Sushma Shetty

52

www.vtulife.com

o   



   

 

The maximum length of variable name should be 8 characters long in DOS based program & in ANSI C it supports up to 31 characters long. A variable should be defined before it is used in the program Example: data-type var-list; Data type must be valid data type and var-list may be consist of one or more identifier names separated by commas operator. The defining indicates the compiler about the variable names and types of data. It is a method of informing the compiler to reserve the memory space for the data based on the type of the variables. Example : int count; double balance; float amount; int, double,and float are keywords and cannot be used as variable names. Initialising: Values can be assigned to variable using the assignment operator (=). var-name=expression; An expression can be a single constant or combination of variables,operators and constants. Data-type var-name=constant; Eg: int value=250; Int a=58,b=90; char name= “pace” double amount =76.80 Declaring: the variables can be declared without allocating the memory. Its possible by type declaration. Type declaration is a method of informing the compiler about the type of data to be stored in a variable. Using type declaration, the compiler knows that the variables are used in the current file but are defined in some other file. o Syntax:  Extern data_type a1,a2,….an; Where, extern is a keyword. A1,a2,…an are variable names. Data_type is the type of variables such as int, float etc.

TYPES OF VARIABLES:    

Integer variable: if integer value has to be stored in the memory, then define the variable as type int. it occupies 2 bytes of memory in turbo C compiler. Floating point variable Character variable Double variable

DIFFERENCE BETWEEN KEYWORDS AND VARIABLES KEYWORDS They have predefined meaning in a language.used

Prepared By: Sushma Shetty

VARIABLES Do not have predefined meaning in a language.

53

www.vtulife.com

for specific purpose, hence called reserved words. Instructions given to the compiler.

Keywords are not used to store the data. Eg: if,else, while, for

Names given to memory locations. During compilation, compiler determines the size of data to be stored in the variable depending on the data type. Used to store the data. Eg: a, b, length

C PROGRAMS: The structure of C program is shown below:  preprocessor directives: or pre-compiler directives. Begins with a # symbol. eg: #include the preprocessor inserts the contents of file “stdio.h” at that point.  Global declarations: variables defined immediately after pre processor directives. It is visible to all parts of the program.  Main(): every c program must have a main function from where the execution begins. The main function is divided into 2 parts: o Declaration section/ local definitions. o Executable section.  Local definition: the variables used within the main() must be declared.  Executable section: these are building blocks of the program. They represent instructions given to the computer to perform specific task. A C PROGRAM:  In C, the program to print ``hello, world'' is #include main() { printf("hello, world\n"); } 

Just how to run this program depends on the system you are using. As a specific example, on the UNIX operating system you must create the program in a file whose name ends in ``.c'', such as hello.c, then compile it with the command

Prepared By: Sushma Shetty

54

www.vtulife.com





gcc hello.c in the terminal. If you haven't botched anything, such as omitting a character or misspelling something, the compilation will proceed silently, and make an executable file called a.out. If you run a.out by typing the command a.out In turbo C, Save the program, compile by pressing Cntrl+F9 See the output by pressing Alt+F5.

COMMENTS    

Used for documenting the program and are ignored by the compiler during compilation. Comment statements doesn’t compile by the computer. Comments /*……..*/ In C, /* is called opening comment mark and */ is closing comment mark. It helps us to: o Read and understand the logic of the program. o Helps to maintain and modify program easily.

SOFTWARE ENGINEERING AND PROGRAMMING STYLE   



Software engineering is the establishment and use of sound engineering methods and principles to obtain software that is reliable and that works on real machines. This definition, from the first international conference on software engineering in 1969, was proposed 30 years after the first computer was built. During this period, software was more of an art then a science. The following concepts are discussed: o Program documentation o Data naming o Data hiding Program documentation: it is usually done in two levels: o General documentation: it must be present in the beginning of every C program with following information in the order specified:  Each program should start with general description of the program.  Provide the name of the author and the date the program was written.  Change history: it consists of reasons for modifying the earlier program. If no change occurs, then change history wont be there. o Module documentation: this should be present in every C program with the following information:  Include brief description of every block used in the program.  If a block is complex, write a short one/ two line description of the operations being performed. o Data names: The use of data names is another good principle of good structured programming. The guidelines to be followed are:  Use meaningful variable names.

Prepared By: Sushma Shetty

55

www.vtulife.com

 

o

The names should match the terminology of the user. To combine two or more words into a meaningful word, use underscore. eg: sumofmarks can be written as sum_of_marks as a variable.  Do not use variable names that differ by one or two variables. Eg: a1,a2,a3.  Use appropriate abbreviations.  Avoid usage of generic names.  Use symbolic constants for the characters that are difficult to read and understand in a program. eg: #define PI 3.14 Data hiding: the data should not be visible for all the functions used in the program. The data must be hidden to protect the data from accidental destruction. So avoid the usage of global variables in the program.

COMMON ERRORS:         





Forgetting to put a break in a switch statement. Using = instead of == Scanf errors: o Forgetting to put an ampersand(&) on arguments o Using the wrong format for operand. Size of arrays. Integer division Loop errors. Not using prototypes. Not initializing pointers. String Errors o Confusing character and string constants. o Comparing strings with ==. o Not null terminating strings. o Not leaving room for the null terminator. Input /output errors o Using getc(), getchar(), etc. incorrectly. o Using feof() incorrectly. o Leaving characters in the input buffer. Using keywords as identifiers in the program.

INPUT AND OUTPUT FUNCTIONS DEFINITION: 

The input functions accept the data from input devices like the keyboard, mouse and store in memory locations. Eg: scanf(), getch(), getchar(), gets().

Prepared By: Sushma Shetty

56

www.vtulife.com



The output functions receive the data from memory locations and display on the monitor or any other output device. Eg: printf(), putch(), putchar(), puts().



Steps or activities (refer above figure) o Data is entered from keyboard. o The data is stored in temporary memory called keyboard buffer. It holds characters until we press enter. o Keyboard function converts data into appropriate data type and stored in memory locations using variables. o Using output functiuon, it is read from memory and stored in temporary storage area called screen buffer. o This data is then visible on the screen.

TYPES OF INPUT OUTPUT FUNCTIONS



A text stream is a sequence of characters divided into lines; each line consists of zero or more characters followed by a newline character. It is the responsibility of the library to make each input or output stream confirm this model; the C programmer using the library need not worry about how lines are represented outside the program.

Prepared By: Sushma Shetty

57

www.vtulife.com





 





The standard library provides several functions for reading or writing one character at a time, of which getchar and putchar are the simplest. Each time it is called, getchar reads the next input character from a text stream and returns that as its value. That is, after c = getchar(); the variable c contains the next character of input. The function putchar prints a character each time it is called: putchar(c); prints the contents of the integer variable c as a character, usually on the screen. Calls to putchar and printf may be interleaved; the output will appear in the order in which the calls are made. Each source file that refers to an input/output library function must contain the line #include An eg code: #include #include main() /* lower: convert input to lower case*/ { int c while ((c = getchar()) != EOF) putchar(tolower(c)); return 0; } Getch(), getche(), putch(): o Whenever we want to read a character from the keyboard without echo (typed character will not be visible on the screen) we use getch() function. The character will be stored in memory location. o If we want the character to be displayed, use getche(). o To display the character stored in memory location on the screen, use putch() function. Gets() and puts(): o Whenever we want to read a sequence of characters from the keyboard with spaces in between and store them in memory locations, then gets() function is used. o Whenever we want to display a sequence of characters stored in memory locations on the screen, then puts() function is used. o Syntax: gets(str); reads a string of characters from the keyboard till the user presses “enter key”. o Syntax: puts(str); displays the string str on the screen. getchar() getch() getche() gets() putchar()

Reads a character from the keyboard and waits for the user to type ENTER key. Reads a character from the keyboard and does not wait for the user to type ENTER key. Character entered will not be visible. Reads a character from the keyboard and does not wait for the user to type ENTER key. Character entered will be visible. Reads a string from the keyboard and waits for the user to type ENTER key. Displays a character on the screen.

Prepared By: Sushma Shetty

58

www.vtulife.com

putch() puts()

Displays a character on the screen. Displays a string on the screen.

ADVANTAGES AND DISADVANTAGES OF UNFORMATTED I/O 



ADVANTAGES: o Very easy to use unformatted I/O functions. o A single character or a sequence of characters can be easily read into memory or easily be displayed on the screen using unformatted I/O functions. DISADVANTAGES: o It is not possible to read/print any other data except characters ie it is not possible to read/print integer numbers, floating point numbers etc. o It can be overcome using formatted I/O functions such as printf() and scanf().

FORMATTED INPUT FUNCTION scanf()      



Data entered from keyboard will be treated as sequence of characters. Even if we enter integer data such as 1234 or floating point numbers 3.14, they are treated as characters. Thus, they must be converted into appropriate data type and stored in memeory. This is done using scanf(). Syntax: scanf(“format string”,address list); Eg: scanf(“%d%f%c”,&x,&y,&z); %d converts input data to decimal and stores in in address of x. %f converts input data to floating point and stores in in address of y. %f converts input data to character and stores in in address of z. The return value is number of items read from keyboard.

FORMAT SPECIFIERS IN scanf() The format string usually contains conversion specifications, which are used to control conversion of input. The format string may contain:  Blanks or tabs, which are not ignored.  Ordinary characters (not %), which are expected to match the next non-white space character of the input stream.  Conversion specifications, consisting of the character %, an optional assignment suppression character *, an optional number specifying a maximum field width, an optional h, l or L indicating the width of the target, and a conversion character.

Prepared By: Sushma Shetty

59

www.vtulife.com

 





 

The conversion characters d, i, o, u, and x may be preceded by h to indicate that a pointer to short rather than int appears in the argument list, or by l (letter ell) to indicate that a pointer to long appears in the argument list. example, the rudimentary calculator: #include main() /* rudimentary calculator */ { double sum, v; sum = 0; while (scanf("%lf", &v) == 1) printf("\t%.2f\n", sum += v); return 0; } Suppose we want to read input lines that contain dates of the form 25 Dec 1988 The scanf statement is int day, year; char monthname[20]; scanf("%d %s %d", &day, monthname, &year); No & is used with monthname, since an array name is a pointer. Literal characters can appear in the scanf format string; they must match the same characters in the input. So we could read dates of the form mm/dd/yy with the scanf statement: int day, month, year; scanf("%d/%d/%d", &month, &day, &year); scanf ignores blanks and tabs in its format string. Furthermore, it skips over white space (blanks, tabs, newlines, etc.) as it looks for input values. To read input whose format is not fixed, it is often best to read a line at a time, then pick it apart with scanf. A final warning: the arguments to scanf and sscanf must be pointers. By far the most common error is writing

Prepared By: Sushma Shetty

60

www.vtulife.com

scanf("%d", n); instead of scanf("%d", &n); This error is not generally detected at compile time.

THE FORMATTED OUTPUT USING printf()     

The data stored in memory locations (or variables) will be in machine language. They must converted into appropriate data type such as integer or floating point number and then converted into data which has to be displayed on screen for human understanding in proper format. It can be done by printf(). Syntax: printf(“format string”,list of variables); Eg: printf(“%d is a number”,x); The value of x say 8. Then, 8 is a number will be displayed on the screen while execution.

FORMAT SPECIFIERS USED IN printf() The format string contains two types of objects: ordinary characters, which are copied to the output stream, and conversion specifications, each of which causes conversion and printing of the next successive argument to printf. Each conversion specification begins with a % and ends with a conversion character. Between the % and the conversion character there may be, in order:  A minus sign, which specifies left adjustment of the converted argument.  A number that specifies the minimum field width. The converted argument will be printed in a field at least this wide. If necessary it will be padded on the left (or right, if left adjustment is called for) to make up the field width.  A period, which separates the field width from the precision.  A number, the precision, that specifies the maximum number of characters to be printed from a string, or the number of digits after the decimal point of a floating-point value, or the minimum number of digits for an integer.  An h if the integer is to be printed as a short, or l (letter ell) if as a long. Conversion characters are shown in Table. If the character after the % is not a conversion specification, the behavior is undefined.

Prepared By: Sushma Shetty

61

www.vtulife.com



 





A width or precision may be specified as *, in which case the value is computed by converting the next argument (which must be an int). For example, to print at most max characters from a string s, printf("%.*s", max, s); Most of the format conversions have been illustrated in earlier chapters. One exception is the precision as it relates to strings. The following table shows the effect of a variety of specifications in printing ``hello, world'' (12 characters). We have put colons around each field so you can see it extent. :%s: :hello, world: :%10s: :hello, world: :%.10s: :hello, wor: :%-10s: :hello, world: :%.15s: :hello, world: :%-15s: :hello, world : :%15.10s: : hello, wor: :%-15.10s: :hello, wor : A warning: printf uses its first argument to decide how many arguments follow and what their type is. It will get confused, and you will get wrong answers, if there are not enough arguments of if they are the wrong type. You should also be aware of the difference between these two calls: printf(s); /* FAILS if s contains % */ printf("%s", s); /* SAFE */ The function sprintf does the same conversions as printf does, but stores the output in a string: int sprintf(char *string, char *format, arg1, arg2, ...); sprintf formats the arguments in arg1, arg2, etc., according to format as before, but places the result in string instead of the standard output; string must be big enough to receive the result.

Prepared By: Sushma Shetty

62

www.vtulife.com

THE ADDRESS OPERATOR (&) 

The user can obtain address of a variable in the memory. To obtain the address of a variable the address operator denoted by symbol ‘&’ is used.  Eg: p=&a; Where p and a are variables. The address of a will be stored in p when this instruction is executed. let address of variable a be 1002. Then 1002 will be stored in p. when printf(“%d and %d, %d”,a,p,&a); is executed it prints 10 and 1002, 1002 On the output screen.

Prepared By: Sushma Shetty

63

www.vtulife.com

UNIT 4 STRUCTURE OF A C PROGRAM EXPRESSIONS OPERATOR: It is a symbol or a token that specifies the operation to be performed on various types of data. Ex: +, -, * OPERAND: A constant or a variable or a function which returns a value is an operand. An operator may have one or two o three operands. EXPRESSION: A sequence of operands and operators that reduces it to a single value on solving it is an expression. Eg: a+b-c*a/2

CLASSIFICATION OF OPERATORS It is classified based on: 1. The number of operand on operator has. 2. The type of operation being performed. 1. BASED ON NUMBER OF OPERANDS OPERATOR TYPES: 1. 2. 3. 4.

Unary operators: ++, -- etc Binary operators: +, -, *, / etc Ternary operators: ? and : Special operators: comma(,), sizeof() etc

a. UNARY OPERATOR: An operator which acts on only one operand to produce the result. Eg: -10, -a, *b, a++ etc. b. BINARY OPERATOR: An operator which acts on two operands to produce the result. Eg: a+b, a*b. c. TERNARY OPERATOR: An operator which acts on three operands to produce a result. Eg: a?b:c Prepared By: Sushma Shetty

64

www.vtulife.com

2. BASED ON TYPE OF OPERATION TYPES OF OPERATORS: 1. 2. 3. 4. 5. 6. 7. 8.

Arithmetic operators. Eg: +, *, - etc Assignment operators. Eg: =, += etc Increment/Decrement operators. Eg: ++, -Relational operators. Eg: 2 25 6==6 6+2>17 8!=8

Results (True/False) TRUE TRUE FALSE TRUE FALSE FALSE

output 1 1 0 1 0 0

7. LOGICAL OPERATORS: If the data value is 0, it is considered false. Else it is true. The operators that are used to combine two or more relational expressions are called logical operators. Logical operatora are used to combine two or more relational expressions. The output will be either true or false. 1. Unary operator ( ! ) 2. Binary operator ( && , || ) Left to right associativity for both. 1. Logical NOT ( ! ): OPERAND True (1) False (0) 2. Logical AND ( && ): Operand1 true true False false

!OPERAND False (0) True (1)

AND && && && &&

Operand2 true False True false

OR || || || ||

Operand2 False True False true

= = = =

Result True False False False

= = = =

result False True True true

3. Logical OR ( || ): Operand1 false false True true

Prepared By: Sushma Shetty

68

www.vtulife.com

8. ASSIGNMENT OPERATORS: An operator which is used to assign the data or result of an expression into a variable (also called memory location) is called an assignment operator. It is denoted by ‘=’ sign. A statement with assignment operator is called assignment statement or assignment expression. Three types: 1. Simple assignment statement. eg:a=a+10 2. Shorthand assignment statement. Eg: a+=10 3. Multiple assignment statement. Eg: a=b=10 1. SIMPLE ASSIGNMENT STATEMENT: Syntax:

Variable=expression (eg: a=a+10)

(a) The expression can be a constant or a variable or any expression. (b) The single symbol ‘=’ is an assignment operator. (c) The expression on right side of assignment operator is evaluated and the result is converted into type of variable on the left side of assignment operator. (d) The converted data is copied into memory location which is identified by the variable on the LHS of the assignment operator. 2. SHORTHAND ASSIGNMENT OPERATOR ( COMPOUND ASSIGNMENT ): Operators such as +=, -=, *=, /= and %= The expression a+=10 means a=a+10. Similarly others. 3. MULTIPLE ASSIGNMENT STATEMENT: i=10 ; j=10; k=10 can be written as i=j=k=10;

INCREMENT AND DECREMENT OPERATORS 1. INCREMENT OPERATOR: Types: 1. Post increment. Eg: a++ 2. Pre increment. Eg: ++a Both increments value of variable a by 1. 1. POST INCREMENT eg: #include Int main()

Prepared By: Sushma Shetty

69

www.vtulife.com

{ int a=5, b; b=a++; return 0; } The expression b=a++ is evaluated as b=a a++ => a=a+1 i.e value of b is 5. And a is 6. 2.

PRE INCREMENT Eg: #include int main() { int a=5, b; b=++a; return 0; } The expression b=++a is evaluated as ++a => a=a+1 b=a i.e value of b is 6 and a is also 6.

2. DECREMENT OPERATOR: Types: 3. Post decrement. Eg: a++ 4. Pre decrement. Eg: ++a Both decrements value of variable a by 1. 2. POST DECREMENT eg: #include Int main() { int a=5, b; b=a--; return 0;

Prepared By: Sushma Shetty

70

www.vtulife.com

} The expression b=a-- is evaluated as b=a a-- => a=a-1 i.e value of b is 5. And a is 4. 2.

PRE DECREMENT Eg: #include int main() { int a=5, b; b=--a; return 0; } The expression b=--a is evaluated as --a => a=a-1 b=a i.e value of b is 4 and a is also 4.

CONDITIONAL OPERATOR It is also called ternary operator. Eg: (expression 1) ? (expression 2): (expression 3)   

Expression 1 will be evaluated to either true or false. If expression 1 is true, expression 2 is executed. If expression 1 is false, expression 3 is executed.

#include int main() { int a=7, b=8, big; big=(a>b)?a:b; printf(“%d”, big); return 0; } output: 8

Prepared By: Sushma Shetty

71

www.vtulife.com

BITWISE OPERATOR The operators that are used to manipulate the bits of given data are called bitwise operators. Types: 1. 2. 3. 4. 5. 6.

Bit-wise negative (~) Left shift () Bit-wise AND (&) Bit-wise OR (|) Bit-wise XOR (^)

BIT-WISE NEGATIVE/ ONE’S COMPLIMENT: The operator that is used to change every bit from 0 to 1 and from 1 to 0 in the specified operand is called one’s compliment operator. Eg: #include int main() { int a=10; int b=~a; return 0; } Here, a=10 i.e in binary representation 8 bits: 00001010 Its compliment is 11110101 i.e 245 in decimal which is assigned to b. LEFT SHIFT OPERATOR: The operator that is used to shift the data by a specified number of bit positions towards left is called left shift operator. Syntax:

b=a
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF