CS
CS
CS
1.1 Introduction
We should keep in mind that a computer is a programmable machine. The two main characteristics of a computer are: (i) it responds to a specific set of instructions in a well-defined manner. (ii) It can execute a pre-recorded list of instructions (a program). Modern computers are electronic and digital. The actual machinery - wires, transistors and circuits is called hardware; the instructions and data are called software. All general purpose computers require the following hardware components: (i) (ii) (iii) (iv) (v) Central Processing Unit (CPU): The brain of the computer, the component that actually executes instructions. Memory : It enables a computer to store, at least temporarily, data and programs. Input device : Usually a keyboard or mouse is used to read data and programs into the computer. Output device: A display screen, printer, etc. that lets you see what the computer has accomplished. Mass storage device: It allows a computer to permanently store large amounts of data. Common mass storage devices include disk drive and tape drive.
In addition to these components, many others make it possible for the basic components of a computer to work together efficiently.
1.2 Objectives
After going through this lesson, you will be in a position to: identify the basic components of a computer and their working explain the importance of various units of a computer learn how these units work together to accomplish a given job
Central Processing Unit (CPU) This part of the computer that executes program instructions is known as the processor or Central Processing Unit (CPU). In a microcomputer, the CPU is based on a single electronic component, the microprocessor chip, within the system unit or system cabinet. The system unit also includes circuit boards, memory chips, ports and other components. A microcomputers system cabinet will also house disk drives, hard disks, etc., but these are considered separate from the CPU. The CPU has two parts The Control Unit (CU) and the Arithmetic Logic Unit (ALU). In a microcomputer, both are on a single microprocessor chip. Control Unit (CU) The control unit tells the rest of the computer system how to carry out a programs instructions. It directs the movement of electronic signals between memory which temporarily holds data, instructions and processes information - and the ALU. It also directs these control signals between the CPU and input/output devices. Arithmetic - Logic Unit (ALU) Arithmetic Logic Unit, usually called the ALU, performs two types of operations - arithmetical and logical. Arithmetical operations are the fundamental
mathematical operations consisting of addition, subtraction, multiplication and division. Logical operations consist of comparisons. That is two pieces of data are compared to see whether one is equal to, less than, or greater than the other. Memory Memory - also known as the primary storage or main memory - is a part of the microcomputer that holds data and instructions. Part of the contents of the memory is held only temporarily, that is, it is stored only as long as the microcomputer is turned on. When you turn the machine off, the contents are lost. The capacity of the memory to hold data and program instructions varies in different computers. The original IBM PC could hold approximately several thousand characters of data or instructions only. But modern microcomputers can hold millions or even billions of characters in their memory. Registers Computers also have several additional storage locations called registers. These appear in the Control Unit and ALU and make processing more efficient. Registers are a sort of special hi-speed storage areas that hold data and instructions temporarily during processing. They are parts of the Control Unit and ALU rather than the memory. Their contents can, therefore be handled much faster than the contents of the memory. Addresses To locate the characters of data or instructions in the main memory, the computer stores them in locations known as addresses. A unique number designates each address. Addresses can be compared to post office mailboxes. Their numbers remain the same, but contents continuously change. How the CPU and Memory work The working of the CPU and memory is shown in Fig. 1.2. Various steps involved for multiplying two numbers is shown in that figure and explained below. 1. The control unit recognizes that the program has been loaded into the memory. It begins to execute the first step in the program.
2. 3.
The program tells the user, "Enter 1st Number". The user types the number 100 on the keyboard. An electronic signal is sent to the CPU. The control unit recognizes this signal and routes the signal to an address in memory - say address 7. After completing the above instruction, the next instruction tells the user, "Enter 2nd Number." The user types the number 4 on the keyboard. An electronic signal is sent to the CPU. The control unit recognizes this signal and routes it to memory address 8. The next program instruction is executed - "Multiply 1st and 2nd Numbers." To execute this instruction, the control unit informs the ALU that two numbers are coming and the ALU is to multiply them. The control unit next sends to the ALU a copy of the contents of address 7 (100) and address 8(4). ALU performs the multiplication : 100 4 = 400 The control unit sends a copy of the multiplied result (400:) back to memory to store it in address 9. The next program instruction is executed : "Print the Result." To execute this instruction, the control unit sends the contents of the address 9 (400) to the monitor. Monitor displays the value 400. Final instruction is executed: "End". The program is complete.
4.
5.
6.
7.
8.
9.
10. 11.
12. 13.
14. 15.
Fig. 1.2 is a simplified version of the actual processing activity. The actual working of the CPU and memory is much more complicated. For example, there are actually many more memory addresses - thousands to millions that cannot be shown here. Moreover, the addresses are in a form the computer can interpret - electronic signals rather than the numbers and letters shown here.
1.4.7 Scanner
Scanner is an input device that can read text or illustrations printed on paper and translate the information into a form that the computer can use. A scanner works by digitizing an image - dividing it into a grid of boxes and representing each box with either a zero or a one, depending on whether the box is filled in. The resulting matrix of bits, called a bit map, can then be stored in a file, displayed on a screen and manipulated by programs. Optical scanners do not distinguish text from illustrations, they represent all images as bit maps. Therefore, you cannot directly edit text that has been scanned. To edit text read by an optical scanner, you need an optical character recognition (OCR) system to translate the image into ASCII characters. Most optical scanners sold today come with OCR packages.
1.4.8 Mouse
Mouse is a device that controls the movement of the cursor or pointer on a display screen. It is a small object you can roll along a hard and flat surface. As you move the mouse, the pointer on the display screen moves in the same direction. Mouse contains at least one button and sometimes as many as three, which have different functions depending on what program is running.
The ALU and CU are jointly knows as (i) RAM (ii) ROM (iii) CPU (iv) none of the above
(c)
The process of producing results from the data for getting useful information is called. (i) output (ii) input (iii) processing (iv) storage
producing output in binary form and finally again converts the output to decimal form. The primary memory as you know in the computer is in the form of IC's (Integrated Circuits). These circuits are called Random Access Memory (RAM). Each of RAM's location stores one byte of information. (One byte is equal to 8 bits). A bit is an acronym for binary digit, which stands for one binary piece of information. This can be either 0 or 1. You will know more about RAM later. The Primary or internal storage unit is made up of several small storage locations called cells. Each of these cells can store a fixed number of bits called word length. Each cell has a unique number assigned to it called the address of the cell and it is used to identify the cells. The address starts at 0 and goes up to (N-1). You should know that the memory is like a large cabinet containing as many drawers as there are addresses son memory. Each drawer contains a word and the address is written on outside of the drawer.
(b)
Read Only Memory (ROM) : There is another memory in computer, which is called Read Only Memory (ROM). Again it is the ICs inside the PC that form the ROM. The storage of program and data in the ROM is permanent. The ROM stores some standard processing programs supplied by the manufacturers to operate the personal computer. The ROM can only be read by the CPU but it cannot be changed. The basic input/output program is stored in the ROM that examines and initializes various equipment attached to the PC when the switch is turned ON. The memories, which do not loose their content on failure of power supply, are known as non-volatile memories. ROM is non-volatile memory. PROM : There is another type of primary memory in computer, which is called Programmable Read Only Memory (PROM). You know that it is not possible to modify or erase programs stored in ROM, but it is possible for you to store your program in PROM chip. Once the programs are written it cannot be changed and remain intact even if power is switched off. Therefore, programs or instructions written in PROM or ROM cannot be erased or changed. EPROM : This stands for Erasable Programmable Read Only Memory, which overcome the problem of PROM and ROM. EPROM chip can be programmed time and again by erasing the information stored earlier in it. Information stored in EPROM can be erased by exposing it to ultraviolet light. This memory can be reprogrammed using a special programming facility. When the EPROM is in use, information can only be read. EAPROM : This stands for Electrically Alterable Programmable Read Only Memory. This concept is same as that of EPROM. The only difference is that the memory can be altered using electrical signals. The whole of the memory need not be erased. Cache Memory : The speed of CPU is extremely high compared to the access time of main memory. Therefore, the performance of CPU decreases due to the slow speed of main memory. The decreases the mismatch in operating speed, a small memory chip is attached between CPU and Main memory whose access time is very close to the processing speed of CPU. It is called CACHE memory. CACHE memories are
(c)
(d)
(e)
(f)
accessed much faster than conventional RAM. It is used to store programs or data currently being executed or temporary data frequently used by the CPU. It is also very expensive to have bigger size of cache memory. Its size is therefore, normally kept small. (g) Registers : The CPU processes data and instruction with high speed. There is also movement of data between various units of the computer. It is necessary to transfer the processed data with high speed. So the computer uses a number of special memory units called registers. They are not par of the main memory but they store data or information temporarily and pass it on as directed by the control unit.
In this type of memory the cost per bit of storage is low. However, the operating speed is slower than that of the primary memory. Huge volume of data are stored here on permanent basis and transferred to the primary storage as and when required. Most widely used secondary storage devices are magnetic tapes, magnetic disks and floppy disks.
Advantages of Magnetic Tape Compact : A 10-inch diameter reel of tape is 2400 feet long and is able to hold 800, 1600 or 6250 characters in each inch of its length. The maximum capacity of such type is 180 million characters. Thus data are stored much more compact on tape
Economical : The cost of storing characters on tape is very less as compared to other storage devices. Fast : Copying of data is easier and fast. Long term Storage and Re-usability : Magnetic tapes can be used for long term storage and a tape can be used repeatedly with out loss of data.
(ii)
(iii)
then be stored in the memory or retained in the arithmetic unit for further calculations.
The user's program provides the basic control instructions. Conceptually, the control unit fetches instructions from the memory, decodes them and directs the various units to perform the specified functions.
1.9.2 Printer
Printer is a device that prints text or illustrations on paper and in may cases on
transparencies and other media. There are many different types of printers. In terms of the technology utilised, printer fall into the following categories. (i) Ink-jet Printer
Ink-jet printers work by spraying ionized ink on a sheet of paper. Magnetized plates in the ink's path direct the ink onto the paper in the desired shapes. Inkjet printers are capable of producing high quality print approaching to that produced by laser printers. A typical ink-jet printer provides a resolution of 300 dots per inch, although some newer models offer higher resolutions. In general, the price of ink-jet printers is lower than that of laser printers. However, they are also considerably slower. Another drawback of ink-jet printers is that they require a special type of ink that is apt to smudge on inexpensive copier paper. Because ink-jet printers require smaller mechanical parts than laser printers, they are specially popular as portable printers. In addition, colour ink-jet printers provide an inexpensive way to print full-colour documents.
(ii)
Laser Printer
Laser Printer utilizes a laser beam to produce an image on a drum. The light of the laser alters the electrical charge on the drum wherever it hits. The drum is then rolled through a reservoir of toner, which is picked up by the charged portions of the drum. Finally, the toner is transferred to the paper through a combination of heat and pressure. This is also the way copy machines work.
Because an entire page is transmitted to a drum before the toner is applied, laser printers are sometimes called page printers. There are two other types of page printers that fall under the category of laser printers even though they do not use lasers at all. One uses an array of LEDs to expose the drum, and the other uses LCDs. Once the drum is charged, however, they both operate like a real laser printer. One of the chief characteristics of laser printers is their resolution - how many dots per inch (dpi) they lay down. The available resolutions range from 300 dpi at the low end to 1,200 dpi at the high end. By comparison, offset printing usually prints at 1,200 or 2,400 dpi. Some laser printers achieve higher resolutions with special techniques known generally as resolution enhancement. In addition to text, laser printers are very adept at printing graphics. However, you need significant amounts of memory in the printer to print high-resolution graphics. To print a full-page graphic at 300 dpi, for example, you need at least 1 MB (megabyte) of printer RAM. For a 600-dpi graphic, you need at least 4 MB RAM. The speed of laser printers ranges from about 4 to 20 pages of text per minute (ppm). A typical rate of 6 ppm is equivalent to about 40 characters per second (cps). (iii) Line Printer
Line printers are high-speed printers capable of printing an entire line at one time. A fast line printer can print as many as 3,000 lines per minute. The disadvantages of line printers are that they can print only one font, they cannot print graphics, the print quality is low, and they are very noisy. (iv) Thermal printer
Thermal printers are printers that produce images by pushing electrically heated pins against special heat-sensitive paper. Thermal printers are inexpensive and are used in most calculators and many fax machines. They produce low-quality print, and the paper tends to curl and fade after a few weeks or months.
1.9.3 Plotter
Plotter is a device that draws pictures on paper based on commands from a computer. Plotters differ from printers in that they draw lines using a pen. As a result, they can produce continuous lines, whereas printers can only simulate lines by printing a closely spaced series of dots. Multicolour plotters use different-coloured pens to draw different colours.
In general, plotters are considerably more expensive than printers. They are used in engineering applications where precision is mandatory.
1.9.5 3D-Audio
3D audio is a technique for giving more depth to traditional stereo sound. Typically, 3D sound, or 3D audio, is produced by placing a device in a room with stereo speakers. The device dynamically analyses the sound coming from the speakers and sends feedback to the sound system so that it can readjust the sound to give the impression that the speakers are further apart. 3D audio devices are particularly popular for improving computer audio where the speakers tend to be small and close together. There are a number of 3D audio devices that can be attached to a computers sound card.
Fill in the blanks: (a) (b) (c) .................. unit coordinates the activities of all the other units in the system. The standard size of display screen is .............. lines by ........... characters. ....................... printer utilizes a laser beam to produce an image on a drum.
(d)
......................... audio is a technique for giving more depth to traditional stereo sound.
Scanner is an input device that can read text or illustration printed on paper
and translate the information into a form that the computer can use 3. (a) ALU (b) CPU (c) processing
In-Text Question 1.2 1. A bit is an acronym for binary digit, which stands for one binary piece of information. This can be either 0 or 1. Byte consists of 8 bits. Each of RAM's location stores one byte of information. The memories, which loose their content on failure of power supply, are known as volatile memories. RAM is a volatile memory. On the other hand ROM is a non-volatile memory because it does not loose its contents on failure of power supply. (a) True (b) False (c) False (d) False (e) True
2.
3.
In-Text Questions 1.3 1. (a) ALU is used to perform all the arithmetic and logic operations such as addition, subtruction multiplication, comparison, etc. Ink-jet printers work by spraying ionized ink at a sheet of paper. These printers are capable of producing high quality print nearer to that produced by laser printers. Plotter is a device that draws pictures on paper based on commands from a computer. Control (b) 24, 80 (c) Laser (d) 3D
(b)
(c)
2.
(a)
2.1 Introduction
Each organisation, regardless of its size or purpose, generates data to keep a record of events and transactions that take place within the business. Generating and organising this data in a useful way is called data processing. In this lesson, we shall discuss about various terms such as data, information, data processing and data processing system.
2.2 Objectives
After going through this lesson, you will be in a position to define the concepts of data, information and data processing explain various data processing activities utilise data processing cycle explain data elements, records, files and databases.
2.3 Data
The word "data" is the plural of datum, which means fact, observation, assumption or occurrence. More precisely, data are representations of facts pertaining to
people, things, ideas and events. Data are represented by symbols such as letters of the alphabets, numerals or other special symbols.
2.5 Information
Information, thus can be defined as data that has been transformed into a meaningful and useful form for specific purposes. In some cases data may not require any processing before constituting information. However, generally, data is not useful unless it is subjected to a process through which it is manipulated and organised, its contents analyzed and evaluated. Only then data becomes information. There is no hard and fast rule for determining when data becomes information. A set of letters and numbers may be meaningful to one person, but may have no meaning to another. Information is identified and defined by its users. For example, when you purchase something in a departmental store, a number of data items are put together, such as your name, address articles you bought, the number of items purchased, the price, the tax and the amount you paid. Separately, these are all data items but if you put these items together, they represent information about a business transaction.
certain tools to help him in processing data. These include manual tools such as pencil and paper, mechanical tools such as filing cabinets, electromechanical tools such as adding machines and typewriters, and electronic tools such as calculators and computers. Many people immediately associate data processing with computers. As stated above, a computer is not the only tool used for data processing, it can be done without computers also. However, computers have outperformed people for certain tasks. There are some other tasks for which computer is a poor substitute for human skill and intelligence. Regardless to the type of equipment used, various functions and activities which need to be performed for data processing can be grouped under five basic categories as shown in Fig. 2.1
Collection Originating Measuring Recording Comparing Conversion Coding Classifying Verifying Transforming Manipulation Sorting Calculating Summarizing Comparing
Fig. 2.2 The source document for a payroll application is the weekly time sheet
(a)
Collection Data originates in the form of events transaction or some observations. This data is then recorded in some usable form. Data may be initially recorded on paper source documents 2.2 and then converted into a machine usable form for processing. Alternatively, they may be recorded by a direct input device in a paperless, machine-readable form. Data collection is also termed as data capture.
(b)
Conversion Once the data is collected, it is converted from its source documents to a form that is more suitable for processing. The data is first codified by assigning identification codes. A code comprises of numbers, letters, special characters, or a combination of these. For example, an employee may be allotted a code as 52-53-162, his category as A class, etc. It is useful to codify data, when data requires classification. To classify means to categorize, i.e., data with similar characteristics are placed in similar categories or groups. For example, one may like to arrange accounts data according to account number or date. Hence a balance sheet can easily be prepared. After classification of data, it is verified or checked to ensure the accuracy before processing starts. After verification, the data is transcribed from one data medium to another. For example, in case data processing is done using a computer, the data may be transformed from source documents to machine sensible form using magnetic tape or a disk.
(c)
Manipulation Once data is collected and converted, it is ready for the manipulation function which converts data into information. Manipulation consists of following activities: Sorting It involves the arrangement of data items in a desired sequence. Usually, it is easier to work with data if it is arranged in a logical sequence. Most
often, the data are arranged in alphabetical sequence. Sometimes sorting itself will transform data into information. For example, a simple act of sorting the names in alphabetical order gives meaning to a telephone directory. The directory will be practically worthless without sorting. Business data processing extensively utilises sorting technique. Virtually all the records in business files are maintained in some logical sequence. Numeric sorting is common in computer-based processing systems because it is usually faster than alphabetical sorting. Calculating Arithmetic manipulation of data is called calculating. Items of recorded data can be added to one another, subtracted, divided or multiplied to create new data as shown in fig. 2.2(a). Calculation is an integral part of data processing. For example, in calculating an employee's pay, the hours worked multiplied by the hourly wage rate gives the gross pay. Based on total earning, income-tax deductions are computed and subtracted from gross-pay to arrive at net pay.
Weekly Payroll Summary Report 07/07/2005 Dept. 2 Employee Name Pankaj Rekha Param Rajesh Sanju Savini Hari Om Vimla Dinesh Upma Arunima Ritwik Hours Worked 34 32 20 36 45 25 192 33 40 73 38 40 32 40 150 415 Pay Rate 10.00 9.00 5.00 8.00 9.00 3.00 7.75 9.25 7.00 9.45 8.50 8.00 Gross Wages 340.00 288.00 100.00 288.00 405.00 75.00 1496.00 255.75 370.00 625.75 266.00 390.00 272.00 320.00 1,248.00 3,369.75
Number 170 175 158 160 165 159 Department 2 Total 4 110 115 Department 4 Total 8 150 155 156 157 Department 8 Total Company Total
Summarizing To summarize is to condense or reduce masses of data to a more usable and concise form as shown in fig. 2.2(b). For example, you may summarize a lecture attended in a class by writing small notes in one or two pages. When the data involved is numbers, you summarize by counting or accumulating the totals of the data in a classification or by selecting strategic data from the mass of data being processed. For example, the summarizing activity may provide a general manager with sales-totals by major product line, the sales manager with sales totals by individual salesman as well as by the product line and a salesman with sales data by customer as well as by product line. Department Payroll Summary for Week of 07-07-2005
Department 2 4 8 Company Total Hours 192 73 150 415 Gross Wages 1,496.00 625.75 1,248.00 3,369.75
Comparing To compare data is to perform an evaluation in relation to some known measure. For example, business managers compare data to discover how well their compaines are doing. They many compare current sales figures with those for last year to analyze the performance of the company in the current month. (d) Managing the Output Results Once data has been captured and manipulated following activities may be carried out : Storing To store is to hold data for continued or later use. Storage is essential for any organised method of processing and re-using data. The storage
mechanisms for data processing systems are file cabinets in a manual system, and electronic devices such as magnetic disks/magnetic tapes in case of computer based system. The storing activity involves storing data and information in organised manner in order to facilitate the retrieval activity. Of course, data should be stored only if the value of having them in future exceeds the storage cost. Retrieving To retrieve means to recover or find again the stored data or information. Retrieval techniques use data storage devices. Thus data, whether in file cabinets or in computers can be recalled for further processing. Retrieval and comparison of old data gives meaning to current information. (e) Communication Communication is the process of sharing information. Unless the information is made available to the users who need it, it is worthless. Thus, communication involves the transfer of data and information produced by the data processing system to the prospective users of such information or to another data processing system. As a result, reports and documents are prepared and delivered to the users. In electronic data processing, results are communicated through display units or terminals. (f) Reproduction
To reproduce is to copy or duplicate data or information. This reproduction activity may be done by hand or by machine.
The term input refers to the activities required to record data and to make it available for processing. The input can also include the steps necessary to check, verify and validate data contents.
Output Communicate and Reproduce Processing Sorting Calculating Summarizing Comparing Input Collection Conversion
Da ta
(ii)
Processing
The term processing denotes the actual data manipulation techniques such as classifying, sorting, calculating, summarizing, comparing, etc. that convert data into information. (iii) Output
It is a communication function which transmits the information, generated after processing of data, to persons who need the information. Sometimes output also includes decoding activity which converts the electronically generated information into human-readable form.
(iv)
Storage
It involves the filing of data and information for future use. The above mentioned four basic functions are performed in a logical sequence as shown in Fig. 2.3 in all data processing systems.
There are many kinds of data processing systems. A manual data processing system is one that utilizes tools like pens, and filing cabinets. A mechanical data processing system uses devices such as typewriters, calculating machines and book-keeping machines. Finally, electronic data processing uses computers to automatically process data.
Hence, it is a fixed field. In contrast, since customer's name vary considerably from one customer to another, a variable amount of space must be available to store this element. This can be called as variable field. Record A record is a collection of related data items or fields. Each record normally corresponds to a specific unit of information. For example, various fields in the record, illustrated in Fig. 2.4 are employee number, employee's name, basic salary and house rent allowance. This is the data used to produce the payroll register report. The first record contains all the data concerning the employee PANKAJ. The second record contains all the data concerning the employee REKHA. Each subsequent record contains all the data for a given employee. It can be seen how each related item is grouped together to form a record.
File The collection of records is called a file. A file contains all the related records for an application. Therefore, the payroll file shown in Fig. 2.5 contains all records required to produce the payroll register report. Files are stored on some medium, such as floppy disk, magnetic tape or magnetic disk. Database The collection of related files is called a database. A database contains all the related files for a particular application.
600 bytes File with Variable Length Records Record A 120 bytes Record B 130 bytes Record C 200 bytes Record D 160 bytes
590 bytes
Fig. 2.5 Fixed and variable length records.
Fixed Length Records In this case, all the records in a file have the same number of bytes. Such a file is called a flat file. If all the records are expected to contain essentially the same quantity of data, then fixed length records are used. Variable Length Records In this case, records vary in length. Use of variable length records conserves storage space when the quantity of information, of various records in a file, differs significantly.
be located in different physical records or several logical records may be located in one physical record. For example, in case of magnetic tape, number of logical records are stored in the form of a block to increase the data transfer speed and this block is referred to as a physical record as shown in Fig. 2.6
Physical Record
R1 R2 R3 R4 R5 R6 R7 R8
Physical Record
R9 R10 R11 R12 R13 R14 R15
Physical Record
R16 R17 R18 R19 R20 R21 R22
Physical Record
R23 R24 R25 R26 R27 R28 R29
IBG
IBG
IBG
(b)
2.
(a) (b)
Intext Questions 2.2 1. Data processing activities are grouped under following five basic categories. (i) (ii) (iii) (iv) (v) 2. Collection Conversion Manipulation Storage and retrieval Communication
The various steps involved in data processing cycle are as follows: (i) (ii) (iii) (iv) Data input Data processing Output Storage
3 Computer Software
3.1 Introduction
If you want to get something done by a persons, you will tell him what to do in a language that he understands. Similarly, if you want to get some work done by the computer, you have to tell the computer in a language that the computer understands, i.e., machine language. The machine language consists of only binary digits, i.e. 0 and 1. It was felt quite difficult and tedious for human beings to thinks in binary numbers. For communicating with the computer, it was thought that it is advisable to develop a third language, a programming language, that can be understood by both human beings and the computer. Thus a programming language is a set of rules that provides a way of instructing the computer to perform certain operations. Programming languages are said to be lower or higher, depending on whether they are closer to the language the computer itself uses (lower, which means 0s and 1s) or to the language that people use (higher, which means more English like).
3.2 Objectives
After going through this lesson you will be in a position to: identify various levels (or generations) of language such as machine language, assembly language, high-level language
Computer Language/Software :: 39
explain the concept of software distinguish between system software and application software distinguish between compiler and interpreter define operating system and its various functions
run, all the switches had to be set - sometimes as many as 6,000 switches for a single program. Then for the next program, the switches had to be reset, a process that might take weeks. Since those days, machine switches have been replaced by machine programming, programs with statements consisting of 0s and 1s that electrically set the switches, with 0 representing off and 1 responding on. This has made changing from one program to another considerably easier. Still, programming directly in machine language - the lowest level of programming language, in which instruction is represented as 0s and 1s - is very tedious and time consuming. A programmer must keep track of a tremendous amount of detail. Moreover, he/she must understand the technical operations of the computer. For example, consider a hypothetical line from a program segment, which multiplies two numbers. 11110010 01110011 11010010 00010000 01110000 00101011
Clearly, working with this kind of code is not for everybody. Programming in machine code has one advantage over programming at other language levels - its execution is very fast and efficient because the computer can accept the machine code as it is. However, in addition to the complexity involved in working at this level, there is a severe disadvantage to machine language - there is no one standard machine language. Machine language differs from machine to machine. The languages are machine-dependent, and the programs written in machine language for one computer model will not, in all likelihood, run on a computer of different model. Although many programs or subroutines in machine language for a particular computer is supplied by the manufacturer, still few applications programs are written by users in machine language. Assembly Languages From the above discussion it was felt that working with 0s and 1s could turn people themselves into ciphers. In the 1950s, to reduce programming complexity and provide some standardization, assembly languages were developed. Assembly languages, also known as symbolic languages use
Computer Language/Software :: 41
abbreviations or memonic code - codes more easily memorized to replace the 0s and 1s of machine languages. The hypothetical machine language segment we saw above is as follows: 11110010 01110011 11010010 00010000 01110000 00101011
This could be expressed in assembly language statement as : PACK 210 (8, 13), 02B (4,7) Actually, assembly languages do not replace machine languages. In fact, for an assembly language program to be executed, it must be converted to machine code. The assembly language program is referred to as a 'source program' whereas, the machine language program is an 'object program'. Assembly language code is very similar in form to machine language code. In fact, assembly languages had a one-to-one correspondence which means that 15 assembly statements, would be translated into 15 machine language statements. This one-to-one correspondence was still laborious. However, assembly language instructions (called macro instructions) were devised, which executed batches of one-to-one instructions. Assembly languages offer several advantages: They are more standardized and easier to use than machine languages. They operate very efficiently, although not as efficient as the machine languages. They are easier to debug. However, there are still some disadvantages: Assembly language programs are usually very long and difficult to debug. Though less abstract than machine languages, assembly language programs are still complex. Though more standardized than machine languages, assembly languages are still machine dependent.
High Level Languages High Level Languages helped programmers by reducing further the number of computer operations details they had to specify, so that they could concentrate more on the logic needed to solve the problem. The following example gives you a code segment in which the same instruction - " Calculate gross pay" - is expressed in three different languages: machine, assembly and COBOL. Machine Language: 11110010 11110010 11111100 11110000 11110011 011100011 011100011 01010010 01000101 01000011 1101 001000010000 1101 000100001000 1101 001000010010 1101 001000010011 0111 0111 000001010000 000001010100 0111 0111 1101 0000 1101 000000101011 000000101111 001000011101 000000111110 001000010100
210 (8, 13), 02B (4,7) 218 (8, 13), 02F (4,7) 212 (G, 13), 21D (3, 13) 213 (5, 13), 03E (0), 5
Computer Language/Software :: 43
Problem-oriented Languages and Application Generators Third-generation languages, such as BASIC or Pascal, require you to instruct the computer in step-by-step fashion. Fourth-generation languages, also known as problem-oriented languages, are high-level languages designed to solve specific problems or develop specific applications by enabling you to describe what you want rather than step-by-step procedures for getting there. Fourth- generation languages may be categorized into several kinds of application development tools: Personal computer applications software Query languages and report generators Decision support systems and financial planning languages. Application generators Personal Computer applications software You may be knowing about various application softwares for PCs, but the ones we are particularly concerned with here are word processors, spreadsheets, database management, business graphics and integrated packages. Knowledge of spread sheet, Foxpro or Power Point can help you develop your own applications. Query languages and report generators Query languages allow people who are not programmers to search a database using certain selection commands. Query languages, for example, are used by airline or railway reservation personnel needing ticket information. Report generators are designed for people needing to prepare reports easily and quickly. Examples of query languages and report generators include QBE, SQL, RPG, etc. Decision support systems and financial planning languages Decision support systems are interactive software designed to help managers make decisions. Financial planning languages are particular kinds of decision support systems that are employed for mathematical, statistical and forecasting modelling. Both types of languages find applications in developing complicated business model hypothetical representations of management problems.
Computer Language/Software :: 45
Application generators An application generator consists of a software system with number of program modules, preprogrammed for various functions, so that the programmer or user can simply state which function is needed for a particular application, and the system will select the appropriate module and run a program to meet the user's needs. Table 3.1 summarizes some of the major difference between third-generation languages (3GLs) and fourth-generation languages (4GLs.). Table 3.1 Difference between 3 GLs and 4 GLs Third-generation Languages Intended for use by professional programmers. Requires specification of how to perform task. All alternatives must be specified. Require large number of procedural instructions. Code may be difficult to read, understand and maintain. Language developed for batch operations. Can be difficult to learn. Difficult to debug. Typically file-oriented. Fourth-generation Languages May be used by a non-programming personnel as well as a professional programmer. Requires specification of what task is to be performed (system determines how to perform the task). Default alternatives are built in; an end user need not specify these alternatives Require fewer instructions. Code is easy to understand and maintain because of English-like commands. Language developed primarily for on-line use. Easy to learn. Easy to debug. Typically database-oriented.
Natural Languages Natural languages are still in the developmental stages, but they promise to have profound effect, particularly in the areas of artificial intelligence and export systems. Natural languages have two characteristics: They are designed to make the connections that humans have with computers more natural - more humanlike. They are designed to allow the computer to become "smarter" - to actually simulate the learning process by remembering and improving upon earlier information. Two popular natural languages are LISP and PROLOG.
Computer Language/Software :: 47
hand, interpreted languages do not need to create object code and so are usually easier to develop and test.
(d) (e)
(i) (ii)
The first objective is realized by that component of system software which is commonly known as operating system. System Software is a set of instruction to the machine to interpret and execute application software, for example, language translators (called compilers and interpreters), operating systems, utilities and special purpose software. Language Translator A language translator is a system software which translates a computer program written by a user into a machine understandable form. The most elemental form of programming uses only the binary digits 0 and 1, which is directly understood by the electronic circuits. A program that have only binary digits is called a machine language program. It is difficult to write or understand machine language programs, as these consist of 0s and 1s. Assembly language provides a significant improvement over machine language, Assembly language programs are written using memonic codes like ADD, STORE, etc., rather than their machine language representations in binary digits. Therefore, programming in assembly language is easier. For its execution, it needs to be translated into machine language code. This translation is done by an assembler. Both machine language and assembly language programs are machine dependant.
Computer Language/Software :: 49
A program written in a high level language needs to be translated into machine language code before execution. This translation is done either through a complier or through an interpreter. A compiler is a translator program which reads an entire program written in a high level language and converts it into machine language code. An interpreter on the other hand, is a translator which converts one statement of the program into machine code, execute it and then goes on to perform the same for the next statement, and it continues doing so till the end of the program or on error occurrence. Operating System An operating system is the most important system software and is a must to operate a computer system. An operating system manages a computer's resources very effectively, takes care of scheduling multiple jobs for execution and manages the flow of data and instructions between the input/output units and the main memory. The first operating system, called batch processing operating system was developed for the second generation computers. This operating system executes jobs serially one after another from a batch of jobs submitted for execution. The central processing unit is kept busy only during the processing cycle of a job and remains idle during the input and output operations. A multi programming opening system handle multiple jobs simultaneously by overlapping the input/ output and processing cycles of various jobs. Other types of operating system which are popular today are multi-processing operating systems and real time operating systems. A multi-processing operating system uses multiple CPUs to process multiple jobs. A real time operating system is a type of interactive operating system which strict time limitation. Receiving and processing data is done quickly enough to produce output, to control, direct or effect the outcome of ongoing activity. The reservation system used by railway, airlines, hotel are examples of real time applications. The function of an operating system can be compared to the functions of a principal in a school. The principal of the school provides an environment in
which the other employees can do useful work. The principal will do this by allocating resources available such as allocating time for each period, allocating classes to teachers and providing rooms for different classes etc. Similarly, an operating system governs the working of the computer and input/output devices. The operating system programs act as an interface between the user's programs and the computer's components and help in the execution of user's programs. The major functions of an operating system are: (i) User identification and keeping of the resources used by the users. Thus un-authorized users cannot use the computer. Sharing of computer resources among many users. The sharing is achieved by permitting simultaneous executions of more than one user program. This is usually called multi-programming. A mix of programs can keep the whole memory occupied, all devices active, and the control unit and ALU constantly busy, thus increasing utilization of hardware. Executive batches of programs, one after another, without human intervention. Protection of user's data and programs. Controlling the transfer of data and programs between the main memory and secondary storage and other I/O devices. Providing programs to select appropriate translators. Providing facilities to detect and correct errors in a user's program.
(ii)
(iii)
(iv) (v)
(vi) (vii)
An operating system understands a fixed set of commands. This set of commands is often called job control language (JCL). The JCL commands are used by the computer users to indicate their requirements to the operating system. The operating system which is used with a micro-computer is called CP/M (control program for microprocessor). Another operating system which is gaining popularity and which is available on a variety of different machines is UNIX (UNIX was developed by Bell laboratories). DOS is an operating system commonly used in PCs. The second objective of simplifying computer usage is achieved by enabling the users to write their own programs in languages other than the machine language.
Computer Language/Software :: 51
The only language understood by computers is machine language. If any other language is used, the programs must first be translated into the machine language before they can be executed. One of the most significant aspect of computers is that such translations can be made automatically using other programs. A computer manufacturer provides many programs for the translation of many languages into the machine language. These programs are called translators or compliers and form part of the system software. We rarely talk about computer hardware alone. It is the hardware and software both which make up a computer system. There is definitely some substance in the argument that system software is as important, if not more, as its hardware. Utility Software Utility software may be considered as a system software which is used quite often in the development of a program. Sort merge programs are used to sort records in a particular manner or sequence. Such programs are normally provided by the manufacturers. The programmer can also develop his own utility software and keep it in the secondary memory of the computer.
Write it yourself : The program written by the user can be the most satisfactory solution. It will be an exact match to the needs of the business. The program can grow with the business.
(b)
General purpose application packages : Application packages refer to a set of computer programs, which have been written to perform specific, commonly required tasks. Each program is written in such a way that it is applicable to a large number of users. The main advantage is that it is relatively cheap as cost of the package is spread over a number of customers. The major disadvantage of application package is that it is not likely to fulfil all the requirements of the prospective users. Customer software : It refers to computer programs specially written to match the exact needs of the user. It is precisely the same as getting one's clothes stitched from a tailor to fit exactly rather than buying a ready-made dress. The most important advantage is that such software fulfils all the needs of the customer. The major disadvantage is that customer software costs much more than general purpose application software, because the package is specially made for one particular customer.
(c)
Common Application Packages Some of the common requirements of the users of personal computers have been identified and common applications packages have been developed to meet their needs. These packages include word processor, database processing, spreadsheet calculations, mail-merge, presentations and communications (email). These packages have been prepared so that they are simple to use. They also provide graphical user interface to make them very user friendly. These packages are readily available in the market and one can purchase them, install it on his/her computer easily and start using the package.
Computer Language/Software :: 53
An operating system is a must to operate a computer system. JCL stands for Job Common Language. Application software is written to perform a specific task or process. Utility software cannot be considered as an application software.
(e)
2.
(a) Readability (b) Easy learning (c) Easy debugging (d) Easy software development 3. (a) True (b) True (c) False (d) True (e) True
In-Text Questions 3.2 1. Software refers to the set of computer programs that cause the hardware to function in the desired manner. Software is a general term that is used to describe any single program or a group of programs. Application software is a set of programs to carry out operations for a specific application. System software is a set of programs written for performing tasks such as controlling all operations required to move data into or out of the computer. (a) True (b) True (c) False (d) True (e) False
2.
3.
4 Operating System
4.1 Introduction
Most of the personal computers you see today comes with Microsoft Windows operating system. It is an operating system meant for IBM compatible PCs. Operating system is the foundation software that makes it possible for you to use your computer and have it perform the tasks you need. Windows 98 is an updated version of Windows 95.
4.2 Objectives
After going through this lesson, you will be in a position to explain various features of Windows 98 learn various Icons and their features define file management features of Windows 98
interface in which you can communicate with the computer Serves as the base software on which a variety of programs can operate. Examples include MS Word, MS Excel, MS Power Point, and MS Access Handles internal functions, such as managing the computer memory, input and output operations Provides a series of utilities - specialized programs to manage your system - and commands that you can use to manage your files, folders, and disks A Graphical User Interface (GUI), which uses pictures, symbols, windows, and words on your screen that you control with the mouse Built-in programs, or accessories like, WordPad, Notepad, Calculator, Paint program etc. The ability to display several documents and run a number of programs in their own windows, all at the same time. The World Wide Web (WWW) is easily accessible from anywhere in windows. You can communicate over the Internet. Using Internet tools included with windows, you can send e-mail, chat, and view news. Supports DVD and digital audio, so that you can play high quality digital movies and audio on your computer. You can also watch TV.
2.
Operating System :: 57
by clicking the right mouse button, but unless you are instructed, click the left mouse button. 3. Double-clicking : Pointing to an item and then quickly pressing and releasing the mouse button twice is called double-clicking. Whenever you are unsure of the command to use for an operation, try clicking the item you want to affect. If you get no result, try double-clicking. This often displays a dialog box in which you can make changes to the item you double-clicked. Dragging : Pointing to an item and then holding down the mouse button as you move the mouse is called dragging. You can use this action to select data, and to move and copy text or objects.
4.
4.4.1 Desktop
When you turn on your computer, the screen first displays Basic Input Output Information (BIOS) about your computer. Few seconds later, Windows takes control and the Windows logo flashes on your screen with the cloudy sky. You could see "Microsoft Windows 98" . The first thing that always appears after loading is that you will be asked to type your passward to enter Windows (it is the password you typed the first time Windows was launched). The Desktop is where you might place useful things always accessible to you. Depending on which options you choose during installations, you will see some or all the objects as shown in Figure 4.1
My Computer window (see fig. 4.2) looks just like any window you open, you can minimize, this Window with _, maximize with and close by clicking on x.
Operating System :: 59
In My Computer you are forbidden to Delete, Copy, Rename anything, try to press delete key and nothing will happen. The items in My Computer window are so crucial that you cannot run your computer without them. For example, if you remove the hard drive where would you store your files? Since My Computer items are related to the computer system they should remain intact. Suppose you want to use My Computer to view your hard disk. On the Desktop double-clock My Computer. The My Computer window (see Figure 4.2) with different icons will appear.
Double-click the icon (see fig. 4.2) that represents your hard disk. Your hard disk window appears, and you can easily see the contents of your hard disk. Similarly you can double-click the other icons in My Computer. To view the contents of the floppy disk, which is usually designated drive A: To view the contents of the hard disk, which is usually designated drive C: To view the contents of the hard disk, which is usually designated drive D:
To view the contents of compact disk in the CD-ROM drive designated as E: To set up printer and view information about available printers and print job status. To view tools you can use to modify your computer settings. To schedule or view tasks for computer maintenance To view web folder contents To view shared information on another computer by using a modem. The Properties Window in My Computer To learn more about each item, just choose one icon, right-click and select Properties from menu. The Properties window is divided into four tabs: General, Tools, Sharing, and Compression. If you select the Floppy icon, the General tab shows information about your floppy, storage device. It tells you how much space you still have on your disc, and the total size in KB or MB. You should have a total of 1.45,664kb if you are using a 1.44 MB floppy. At the top of the window is the floppy table, usually it is blank. The pie chart shows clearly the Used Space and Free Space (see Figure 4.3)
Operating System :: 61
The Tools tab in fig. 4.3 features the following three important Windows utilities: Error-checking status: It is a utility that let you check your computer for errors. If you accidentally turn your computer off without shutting down, it will run when you restart your computer and perform a scan on your hard drive. Backup status: This utility lets you backup important stuff so you will never loose anything in case your computer was damaged. You should always keep two copies of your work you store in computer. Defragmentation status : Use this utility to make your computer run faster. The more you use the computer the more " it gets tired and old". Defragmentation will refresh it. The Sharing tab will tell you whether your hard disk is shared by other network users or not. The Compression tab is almost never used. Suppose one day you run out of disk space, you can use the Compression utility to squeeze your files and generate more room. Beside My Computer there are quite a few more icon on the Desktop. These are as follows : 2. My Documents : This is where you store all your personal stuff like files, anything you create with your computer. You can put your things somewhere else also. Think of My Documents as your Desktop drawer where you can put your papers. Recycle Bin : Provides space for deleted files from folders or Desktop, and provides a second chance to recover files deleted. Internet Explorer : It is a piece of software called a browser that lets you explore the Internet. You might have another icon like "Internet Connection" that will help you configure your computer to access the Internet. Network Neighbourhood : Provides access to shared resources on your computer and other computers on your local and wide area networks.
3.
4.
5.
If your computer is connected to a network, you can use Network Neighbourhood to browse network resources in the same way you browse the contents of your computer. To open network resources follow the steps given below : i. On the Desktop, double-click Network Neighbourhood. The computers in your workgoup will appear. If you want to view all of the resources available on the network, double-click Entire Network. Double-click the servers and folders you want to open.
ii. 6.
Online Services : As online services is a subscription computer service you can use it to access a wide variety of information and exchange messages with other users. With online services, you can obtain informations on news, sports, weather, the stocks market, and many more. You can get access to different libraries and databases. You can send mail to other users of the online service. Examples of online services include America Online, CompuServe, Prodigy, and MSN. Date, Time, Volume : At the bottom right corner of the screen, you can tell what time is it . By clicking you mouse over the clock icon, you will get the date. You can also control the sound by clicking on the speaker icon. Start Button : This button lies at the bottom left of our screen. It provides an easy way to start different programs and other applications. Taskbar : This lies at the bottom of your screen. This displays all open applications and windows. The Start button and the Taskbar work together and help you in managing your applications opener close windows easier.
7.
8.
9.
You will learn more about these Desktop icons in the next few sections of this lesson.
Operating System :: 63
3. 4.
Fig. 4.4
When you open programs and files on top of other programs and files on the Desktop, Whindows 98 keeps track of all your open windows and lists them on the Taskbar. The advantage of the Taskbar is that when you have multiple applications open at the same time, you can see all of them listed in the foreground, whether or not they are hidden by another windows. Even if an application window is minimized on the Desktop, it can still be accessed from the Taskbar. By clicking on the applications window on the Taskbar, you can bring that application to the front of other windows, and restore if it was minimized. The more windows you open, the more items will be listed on the Taskbar. You can increase the height of the Taskbar for multiple lines of open items. To increase the height of the Taskbar, place the mouse pointer over its top border, the pointer will turn into double-headed sizing arrow ( ). then, click and hold your left mouse button and drag up.
Operating System :: 65
application. Click on Documents in fig. 4.4. and you will see a list of documents you have been working on recently. The documents are listed alphabetically, not by use, and will be listed whether you open them from within an application or from the folder where they are stored. If you find these documents irrelevant and don't want to access, you can clear the list: Right click on the Taskbar. In a small Window you will find properties. On clicking there, another Window will appear. Click on the Start Menu Programs. There, at the documents menu, click on the Clear button.
4.5.4 Settings
From here you have access to the Control Panel (see Figure 4.5), Printers, Taskbar and Start menu, Folder Options, Active Desktop, and Windows update. You can add/delete programs, change monitor settings, connect to networks, create a Startup Disk, Customize Desktop display properties, and set up Dialup Networking. The main features of Control Panel are : 1. You can do customizing of most of your Windows environment. You can display pictures, patterns, or even scanned photographs as your wallpaper, the background of your Desktop. Using the different tabs in the Display Properties of dialog box, you can also change items such as the icons on your Deskstop, the colors of individual windows, and the size of the objects on your screen. You can even add items to your Active Deskstop or set up a screen saver. You can quickly install Programs, such as MS Word or a game, using the Add/Remove Programs feature in Control Panel. You can also connect your computer to a network using Network features in Control Panel. To connect your computer to a network follow the steps given below : i. Click Start, select Settings Control Panel, and then doubleclick Network dialog box appears. Click Add. Select Network. Component Type dialog box appears. Click Client, and then click Add. A list of client software appears. In the Manufactures list, click the name of the manufacture of your network software.
2.
3.
ii.
iii.
In the Network Clients list, select the client software you are using, and then click OK. The client software is added to your computer. On the Configuration tab, select your client, and then click Properties. Enter configuration options for your network, and then click OK. (If you don't know the options for your network, contact your network administrator.). Click OK and then click OK again. The client software is installed and your computer restarts.
iv.
v.
4.
If you have problems with Setup or have trouble in starting Windows98, you can use a Startup Disk to start your computer and run Setup or gain access to your system files. If you have problems with your hard disk, for example, you can use a Startup Disk to start your computer and troubleshoot your hard disk. To create a Startup Disk from within Windows98 follow the steps given below: i. Click Start, point to Setting, click Control Panel, and then double-click Add/Remove Programs. The Add/Remove Programs Properties dialog box appears. Click the Startup Disk tab, and then click Create Disk. Label a floppy disk Windows 98 Startup Disk. insert it into your floppy disk drive, and then click OK.
ii. iii.
To start your computer using Startup Disk follow the steps given below: i. ii. Insert the Startup Disk in the floppy disk drive. Restart your computer. The Windows 98 Startup menu appears. Type the number of the appropriate CD-ROM option, and press ENTER. Follow instructions on your screen. After a series of scans, the MS-DOS prompt appears. From this prompt, you can gain access to the system files on the Startup Disk.
Operating System :: 67
5.
You can Add Printer wizard to quickly set up printers, select default printers, and change printer settings. The wizard guides you step-by-step through printer set up.
4.5.5 Find
When you are looking for a particular folder or file, you can use the Find command instead of opening numerous folders. The Find command lets you quickly search a specific drive or your entire computer or a computer on your network.
4.5.6 Help
When you are stuck, Windows can give you a hand, just go to START HELP or press F1 on your Keyboard.
4.5.7 Run
This is the fastest way to start a program or install a software on your computer or start programs or open folders or connect to network resources. With Run you will have instant access to everything. However, the Run option is for more experienced user. Selecting Run brings up the RUN window where you can type the name of a file or folder that you wish to open. If you don't know the entire path of folders within which a specific file or folder can be found, you can click on the Browse button within this window to find what your are looking for. Although, this is generally not the quickest way to open a document or run a program, sometimes it simply seems more direct than opening a sequence of folders to get the one you need.
Windows Explorer has the following features: You can copy a file or folder containing a number of files from one folder to another folder or one drive to another drive by simply placing the cursor on the source file or folder and dragging it to the destination folder or drive. You can also do this using Copy and Paste. You can delete a file or folder by selecting the file or folder and then clicking on the Delete on the Toolbar. Windows will send it to the Recycle Bin . You can move a file or folder from one folder or drive to another folder or drive using Cut and Paste. By mistake if you have deleted, or moved or copied a file or folder and
Operating System :: 69
want the file or folder in its original place, you can do it pointing the cursor on Undo and then clicking. You can open a file and its program by double clicking a file.
Book1.lnk
Files always lies in folders. In Windows98, you can organize your documents and programs to suite your preferences. You can store these files in folders, and you can move, copy, rename, and even search for files and folders. File names in Windows 98 can be up to 255 characters, including spaces. However, file name cannot contain any of the following characters: \ / : ? < > I.
2.
Double-click disk drive or folder in which you want to create a folder. The drive or folder window opens. On the File menu, point to New, and then click Folder. Type a folder name, and press ENTER. The new folder appears in the location you selected.
3.
To find a file or folder follow the steps given below: 1. Click the Start button, point to Find, and then click Files or Folders. The Find dialog box appears. Now type the file or folder name you want to find. Click the Look in down arrow, or click Browse to specify where to search. Click Find now. After a moment, the results of the search appear.
2.
To open a file or folder follow the steps given below: 1. On the Desktop, double-click My Computer. The My Computer window opens. Otherwise, you can click on Start and Choose Programs Windows Explorer. Double click the drive that contains the file or folder you want to open. Double click the file or folder you want to open.
2. 3.
To rename a file or folder follow the steps given below: 1. On the Desktop, double-click My Computer. The My Computer window opens. Otherwise, you can click on Start and choose Programs Windows Explorer. Double click the drive that contains the file or folder you want to rename. Select the file or folder you want to rename. On the File menu, click Rename. Type a name, and then press ENTER.
2.
3.
To copy or move a file or folder from one location to another location follow the steps given below: 1. On the Desktop, double-click My Computer. The My Computer window opens. Or click on Start and Choose Programs Windows Explorer.
Operating System :: 71
2.
Double click the drive that contains the file or folder you want to move. Select the file or folder you want to copy or move. On the Edit menu, click Copy to copy the file, or click Cut to move the file. Double-click the folder in which you want to place the file or folder. On the Edit menu, click Paste. The file appears in its new location.
3.
To delete a file or folder follow the steps given below: 1. On the Desktop, double-click My Computer. The My Computer window opens. Or click on Start and Choose Programs Windows Explorer. Double click the drive that contains the file or folder you want to delete. Select the file or folder you want to delete. On the File menu, click Delete. The Confirm File Delete dialog box appears. Click Yes. The file is deleted moved to the Recycle Bin.
2.
3.
To permanently delete a file or folder follow the steps given below: 1. On the Desktop, double-click Recycle Bin. The Recycle Bin window opens. Select the file or folder you want to permanently delete. On the Toolbar click on Delete. The Confirm File Delete dialog box appears. Click Yes. The file is permanently deleted. (If you want all files and folders in Recycle Bin are to be deleted, then on the File menu, click Empty Recycle Bin. The Confirm File Delete dialog box appears. Click Yes. All the files are deleted from the Recycle Bin.)
2.
4.7.2 Shortcuts
For an easy access to a file that you use frequently, you can create a shortcut to it. A shortcut does not change the location of a file - the shortcut is just a pointer that lets you open the file quickly. If you delete a shortcut, the original file is not deleted. There are a number of ways to create a shortcut to a file. The most direct route is as follows: 1. On the Desktop, double-click My Computer. The My Computer window opens. Or Click on Start and Choose Programs Windows Explorer.
2.
Double click the drive that contains the file or folder you want to create a shortcut. Select the file or folder you want to create shortcut. Right-click on the file or folder. On the menu that appears, click Create Shortcut. The shortcut appears on the selected drive or folder. (If you want to place the shortcut on the Desktop right-click on the file or folder. On the menu that appears, click Send To Desktop (created shortcut). The shortcut appears on the Desktop.)
3.
To remove a shortcut from your Desktop, drag the shortcut to the Recycle Bin icon or use the right mouse button pointing the shortcut to be deleted and click Delete. To rename a shortcut, close all other open windows, click the right mouse button pointing a file or folder icon to be renamed, click Rename on the menubar that appears. Type the new name to replace old name and then press ENTER.
Operating System :: 73
2.
Title Bar The Title bar resides at the top of the screen. It displays the name of the program in which you are working. It also displays the name of the file or folder or drive you are working with. You can also use Title bar for enlarging and reducing the window by double-clicking on the Title bar. Suppose you opened two or more windows (file, folder), to see in which one you are working, look at the Title bar and the Title bar shows the active window. The advantage of Windows is that you can move the window and place it wherever you want; it is like moving a piece of paper on your actual desktop. Just click the mouse on the Title bar (the window should not be maximized; if it fits the screen you will not be able to move it) hold it and drag. To drag an item you need to click on the Title bar, hold it, then move the mouse. The whole process is called Drag and Drop. You can also move a window (if window is not Maximum) by right clicking on Title bar and selecting Move. By using the mouse you can even change the size of the window : (not maximized) take the mouse pointer to the border of the window, a double-edged arrow will appear:
let you change the height, is for the Width. at the edge of the window let you resample - the ratio between Height and Width is a same.
3.
4.
Menu Bar
Windows 98 provides a variety of menus you can use to choose and perform different tasks. The most frequently used menu in Window 98 is Start menu, which you have already learned. In addition to Start menu, there are many windows and programs that have their own sets of menus and commands.
b.
By default you will be having a Share-level access control. To change it to Userlevel access control, follow the steps given below : i. Click Start, select Settings Control Panel, and then double-click Network. Click the Access Control tab. The Network dialog box appears. Click on User-level access control. In Obtain list of users and groups from, type the name of the domain or server you want to use, and then click OK. You may be prompted to supply additional information about the domain or server you specified. Restart your computer.
ii.
iii.
To set up file-sharing and print sharing services, follow the steps given below : i. Click Start, select, Settings Control Panel, and then double-click Network. Click the Access Control tab. The Network dialog box appears. Click on File and Print Sharing.
Operating System :: 75
ii.
Select the check box(es) the sharing options you want, click OK, and then click OK again. A message prompts you to insert your Windows 98 CD or Setup disk so that File and Print Sharing can be installed. You must restart your computer before the new settings will take effect. After you have set up file-sharing services, you can share a folder or printer.
To share a folder with share-level access control, follow the steps given below: i. In my Computer, right-click the folder you want to share, and then click Sharing in the submenu. Properties dialog box will appear. Click on the Sharing tab, and then click Shared As. In Share Name, type a name for the folder. In Comment, you can type a brief comment or description of the folder. In Access Type, click Read Only, or full depends on Passward. Regardless of which type of access you select, you have the option of adding a password. Type a password if you want to use one, and then click OK. Retype the password and then click OK. The folder or printer icon changes to a folder or printer with a hand, indicating that the item is now shared.
ii.
iii.
iv.
To share a folder with User-level access control, follow the step given below : i. ii. Follow the steps i. and ii. as stated above. Click Add. In the Add Users dialog box, click the name(s) of the person(s) to whom you want to grant permission(s). You can scroll the list of users, or you can type the name and the list will scroll automatically. If you want to grant the same permission to everyone connected to your network, leave The World selected. Click the type of access permissions you want to give to the selected user(s). Read Only means the user has the ability to read, but not change remove files. Full Access means the user has the ability to read, delete, and change file. Custom means the user has a combination of privileges that you specify. When you are finished adding users permission, click OK.
iii.
iv.
The share a printer with share-level access control, follow the steps given below: i. In My Computer, double-click the Printers folder. Right-click the printer you want to share, and then click Sharing. On Sharing tab, click Shared As. In Share Name, type a name for the printer. In Comment, you can type a brief comment or a description of the printer. In Password, you can type a password, retype the password to verify if. Click OK. Click OK. If you typed a password, retype the password to verify it. Click OK.
ii.
iii.
iv.
To share a printer with User-level access control, follow the steps given below: i. ii. Follow the steps i. And ii. as stated above. Click Add. In the Add Users dialog box, click the name(s) of the person(s) to whom you want to grant permissions. You can scroll the list of users, or you can simply type the name and the list will scroll automatically. If you want to grant the same permissions to everyone connected to your network, leave The World selected. Click Full Access. The name(s) of the person(s) you have chosen will be moved to the box on the right side of the screen. When you are finished adding users and permissions, click OK.
iii.
If you have correct permisions, you can use files and printers that are shared on other computers. To use a shared folder or printer, follow the steps given below: i. ii. Double-click Network Neighborhood Double-click the icon for the computer that controls the folder or printer you want to use. If the computer you are looking for is not in your workgroup or domain, first click Entire Network, and then double-click the appropriate workgroup or domain. To use a shared folder or printer, double-click its icon.
iii.
Operating System :: 77
3.
The following Table gives a list of MS-DOS commands. Table 4.1 List of DOS Commands command /? path=c:\windows;c:\dos prompt $p$g dir dir /w dir /p List switches for the DOS command "command" specify in which directories DOS searches for commands or programs make the DOS prompt display the current directory list files in the current directory in one column list files in five columns list files one page at a time
dir *.exe dir z???.exe dir winsock.dll/s type file.ext edit file.ext a: md c:\myfiles cd c:\myfiles rd c:\myfiles del file.ext ren f1 f2 copy f1 f2 verify on verify off xcopy d1 d2 /s xcopy d1 d2 /p diskcopy a: b: diskcopy a: a: format a: format a: /s: backup c:\d1\*.txt a:
list all files with an "EXE" extension list "EXE" files that have four letters and start with z searches for the file "winsock.dll" in the current directory view the contents of the text file "file.ext" use the DOS 5 editor to edit the file "file.ext" change to the A: drive make a new subdirectory named "myfiles" change to subdirectory "myfiles" remove the existing subdirectory names "myfiles" delete a file named "file.ext" rename file "f1" to "f2" copy file 'f1" to "f2" turn on verification of copy commands turn off verification of copy commands copy all files and subdirectories in directory "d1" ask for confirmation of each file before copying duplicate a disk using two floppy drives duplicate a disk using the same floppy drive format floppy disk in drive a: format a bootable floppy disk (include system) back up all files with the extension ".TXT" in "c:\d1\" to the "a:" floppy drive
Operating System :: 79
backup c:\ a: /s restore a: c:\d1\*.txt restore a : C:\/s ver time date cls scandisk chkdsk chkdsk /f chkdsk filename chkdsk a: mem
back up the entire C: drive to floppy drive a: restore certain files to C: from A: restore back-up files and subdirectories check the version of DOS check or correct the system time check or correct the system date clear the screen scan and check the disk C: for errors check disk and memory usage of the current disk fix errors reported by chkdsk check a particular file check a particular disk (a floppy in the a: drive) check memory usage
Note : Replace the drive letter as needed for your own computer. Also, you can type these commands in either upper or lower case letter, because DOS does not distinguish case.
(a) (b) 2.
What are the utilities of the following in Windows 98? (a) (b) (c) (d) My Document Recycle Bin Internet Explorer, and Network Neighborhood
3. 4. 5. 6.
Explain briefly the functions of Start button and Taskbar. Explain the steps in creating a folder. Explain the steps in opening a file or folder. Explain the following (a) (b) (c) (d) Minimize, Maximize/Restore, and Close Title Bar The scroll Box, and Menu Bar.
7. 8.
Explain the steps in using files and printers controlled by others? What is a shortcut. How do you create shortcut.
Operating System :: 81
2.
(a)
Moving the mouse to place the pointer on an item is called pointing. Pointing to an item on the screen and the quickly pressing and releasing the left mouse button is called clicking. Pointing to an item on the screen and then quickly pressing and releasing the mouse button twice is called double clicking. Pointing to an item on the screen and then holding down the mouse button is called dragging.
(b)
(c)
(d)
3.
The Deskstop is place where useful things are accessible by the user, depending on which options you choose during installations. My Computer contains hard drives 'C', floppy drive, CD ROM drive, printers, control panel, Dial up Networking and Scheduled task.
4.
In-Text Questions 4.2 1. Instead of opening drives and folders in separate windows, the user can browse the content in a single Window in a hierarchical structure. On the desktop double click Recycle Bin. In Recycle Bin select the file or folder you want to permanently delete. On the toolbar click delete. The confirm file delete dialog box appears. Then click yes, the file is permanently deleted from the computer. Shortcut is just a pointer that lets you open the file quickly. If you delete a shortcut, the original file is not deleted.
2.
3.
5.1 Introduction
Today computer is available in many offices and homes and therefore there is a need to share data and programs among various computers. With the advancement of data communication facilities the communication between computers has increased and thus it has extended the power of computer beyond the computer room. Now a user sitting at one place can communicate with computers of any remote site through communication channel. The aim of this lesson is to introduce you the various aspects of computer network.
5.2 Objectives
After going through this lesson, you will be in a position to learn the basic elements of data communication system describe communication protocols and data transmission modes explain the use of computer network describe different components of computer network
identify different types of network understand what is internet and e-mail and its uses in modern communication appreciate the use of satellite communication
In data communication four basic terms are frequently used. They are: Data : A collection of facts in raw forms that become information after processing.
Signals : Electric or electromagnetic encoding of data. Signaling : Propagation of signals across a communication medium. Transmission : Communication of data achieved by the processing of signals.
5.4
Communication Protocols
You may be wondering how computers send and receive data across communication links. The answer is data communication software. It is this software that enables us to communicate with other systems. The data communication software instructs computer systems and devices as to how exactly data is to be transferred from one place to another. The procedure of data transformation in the form of software is commonly known as protocol. The data transmission software or protocols perform the following functions for the efficient and error free transmission of data. 1. Data sequencing : A long message to be transmitted is broken into smaller packets of fixed size for error free data transmission. Data Routing : It is the process of finding the most efficient route between source and destination before sending the data. Flow control : All machines are not equally efficient in terms of speed. Hence the flow control regulates the process of sending data between fast sender and slow receiver. Error Control : Error detecting and recovering is the one of the main functions of communication software. It ensures that data are transmitted without any error.
2.
3.
4.
2.
Half-duplex : In half-duplex mode the communication channel is used in both directions, but only in one direction at a time. Thus a half-duplex line can alternately send and receive data. Full-duplex : In full duplex the communication channel is used in both directions at the same time. Use of full-duplex line improves the efficiency as the line turnaround time required in half-duplex arrangement is eliminated. Example of this mode of transmission is the telephone line.
3.
of analog signal to its digital form, is known as demodulation. The device, which converts digital signal into analog, and the reverse, is known as modem. Digital Signals
Analog Signals
2.
3.
2.
Coaxial Cables : Coaxial cable is groups of specially wrapped and insulated wires that are able to transfer data at higher rate. They consist of a central copper wire surrounded by an insulation over which copper mesh is placed. They are used for long distance telephone lines and local area network for their noise immunity and faster data transfer. Microwave : Microwave system uses very high frequency radio signals to transmit data through space. The transmitter and receiver of a microwave system should be in line-of-sight because the radio signal cannot bend. With microwave very long distance transmission is not possible. In order to overcome the problems of line of sight and power amplification of weak signal, repeaters are used at intervals of 25 to 30 kilometers between the transmitting and receiving end. Communication Satellite : The problem of line-sight and repeaters are overcome by using satellites which are the most widely used data transmission media in modern days. A communication satellite is a microwave relay station placed in outer space. INSAT-1 B is such a satellite that can be accessible from anywhere in India. In satellite communication, microwave signal is transmitted from a transmitter on earth to the satellite at space. The satellite amplifies the weak signal and transmits it back to the receiver. The main advantage of satellite communication is that it is a single microwave relay station visible from any point of a very large area. In microwave the data transmission rate is 16 giga bits per second. They are mostly used to link big metropolitan cities.
3.
4.
3.
(a)
The basic requirements for working of a communication system are sender, medium and receiver. Electric or Electromagnetic encoding of data is called Transmission. In full duplex the communication channel issued in both directions at the same time. Analog signal is measured in Volts and its frequency is in Hertz The technique by which a digital signal is converted to analog form is known as modulation.
(b)
(c)
(d) (e)
In addition to these types, the following characteristics are also used to categorize different types of networks. Topology The geometric arrangement of a computer system. Common topologies include bus, star, and ring. Protocol The protocol defines a common set of rules and signals that computers on the network use to communicate. One of the most popular protocols for LANs is called Ethernet. Another popular LAN protocol for PCs is the IBM token-ring network. Architecture Networks can be broadly classified as using either peer-to-peer or client/ server architecture. Computers on a network are sometimes called nodes. Computers and devices that allocate resources for a network are called servers. Local Area Network (LAN) LAN is a computer network that spans a relatively small area. Most LANs are confined to a single building or group of buildings. However, one LAN can be connected to other LANS over any distance via telephone lines and radio waves. A system of LANs connected in this way is called a wide-area network (WAN). Most LANs as shown in Fig. 5.4 connect workstations and personal computers. Each node (individual computer) in a LAN has its own CPU with which it executes programs, but it is also able to access data and devices anywhere on the LAN. This means that many users can share expensive devices, such as laser printers, as well as data. Users can also use the LAN to communicate with each other, by sending e-mail or engaging in chart sessions. There are many different types of LANs-token-ring networks, Ethernents, and ARCnets being the most common for PCs.
LANs are capable of transmitting data at very fast rates, much faster than data can be transmitted over a telephone line; but the distance are limited, and there is also a limit on the number of computers that can be attached to a single LAN. Wide Area Network (WAN) A WAN is a computer network that spans a relatively large geographical area. Typically, A WAN consists of two or more local-area networks (LANs). Computers connected to a wide-area network are often connected through public networks, such as the telephone system. They can also be connected through leased lines or satellites. The largest WAN in existence is the Internet. A typical WAN set up is shown in Fig. 5.5
Network Topologies As we have seen earlier, topology is the geometric arrangement of the computers in a network. Common topologies include star, ring and bus. Star Network The star network as shown in Fig 5.6 is frequently used to connect one or more small computers or peripheral devices to a large host computer or CPU. Many organizations use the star network or a variation of it in a time-sharing system, in which several users are able to share a central processor.
In a time-sharing setup, each terminal receives a fixed amount of the CPU's time, called a time slice. If you are sitting at a terminal and cannot complete your task during the time slice, the computer will come back to you to allow you to do so. Actually, because the CPU operates so much faster than terminals, you will probably not even notice that the CPU is away. By establishing time-sharing, many people in a large organization can use a centralized computing facility. Time-sharing can also be purchased from an outside service, which is an economical way to operate for a small company that cannot afford its own large computer. Star network is frequently used in a LAN to connect several microcomputers to a central unit that works as a communications controller. If the user of one microcomputer wants to send a document or message to a user at another computer, the message is routed through the central communications controller. Another common use of the star network is the feasibility of connecting several microcomputers to a mainframe computer that allows access to an organization's database. Access and control of star network typically is maintained by a polling system. Polling means that the central computer, or communications controller "polls" or asks each device in the network if it has a message to send and then allows each in turn to transmit data. Ring Network The ring network (see Fig. 5.7) is a Local Area Network (LAN) whose topology
is a ring - can be as simple as a circle or point-to-point connections of computers at dispersed locations, with no central host computer or communications controller. That is, all of the nodes are connected in a closed loop. Messages travel around the ring, with each node reading those messages addressed to it. One of the advantages of ring networks is that they can span larger distance than other types of networks, such as bus networks, because each node regenerates messages as they pass through it.
Access and control of ring networks are typically maintained by a "token-passing" system. IBM's Token-Ring network is thought by some observers to be a watershed event comparable to the development of the IBM PCV itself, because the Token-Ring network is designed to link all types of computers together, including not only personal computers but also possible mini computes and mainframes. A Token-Ring network as shown in Fig. 5.7 resembles a merry-go-round. To deliver a message, you would hand over your addressed note to a rider (the token) on the merry-go-round, who would drop it off at the appropriate place. Bus Network Bus networks (see Fig. 5.8) are similar to ring network that the ends are not connected. All communications are carried on a common cable or bus and are available to each device on the network.
Access and control of bus networks are typically maintained by a method called contention, whereby if a line is unused, a terminal or device can transmit its message at will, but if two or more terminals initiate messages simultaneously, they must stop and transmit again at different intervals.
From a user' s point of view, the only interesting aspect about protocols is that your computer or device must support the right ones if you want to communicate with other computers. The protocol can be implemented either in hardware or in software. Some of the popular protocols are TCP/IP, HTTP, FTP, SMTP, POP, Token-Ring, Ethernet, Xmodem, Kermit, MNP, etc.
(b)
(c)
The newest type of network to be used within an organisation is an internet or internet web. Such networks enable computers (or network) of any type to communicate easily. The hardware and software needs are the same as for the internet, specifically TCP/IP, server and browser software used for the World Wide Web. Because most organisations have a need for more dynamic ways to link people and information, the internet market is expanding day by day. Moreover, there is no need to adjust the network when a new user joins in. With the help of Internet, all computers of an organisation can work as stand-alone systems, connected to a mainframe, or part of a LAN or WAN. (b) E-Mail
E-mail stands for electronic mail. This is one of the most widely used features of Internet. Mails are regularly used today where without the help of postage stamp we can transfer mails anywhere in the world. With electronic mail the service is similar. But here data is transmitted through Internet and therefore within minutes the message reaches the destination may it be anywhere in the
world. Therefore the mailing system through e-mail is excessively fast and is being used widely for mail transfer. (c) Voice Messaging
It is a new communication approach which is similar to electronic mail except that it is audio message rather than text messages that are processed. A sender speaks into a telephone rather than typing, giving the name of the recipient and the message. That sender's voice signal is then digitised and stored. The system can then either deliver the message at a specified time in future or it can be retrieved from a database by the recipient. The message is reconverted back into its analog format when it is delivered or retrieved so that the recipient hears it as the original sender's voice on a telephone. Voice messaging requires a computer with an ability to store the audio messages in digital form and then convert them back in an audio form upon verification. Each user has a voice mailbox in secondary storage and special equipment converts the audio message to and from the digital form. The main advantage of voice mail over electronic mail is that the sender does not have to type. Voice mail also makes it easy to include people in the firm's environment in an communication network. (d) E-Commerce
Electronic commerce or e-commerce as it is popularly known refers to the paperless exchange of business information using Electronic Data Interchange, Electronic mail, Electronic Bulletin Boards, Electronic Fund Transfer and other network based technologies. Electronic Commerce (EC) not only automates manual process and paper transactions, but it also helps organisations to move into a fully electronic environment and change the way they usually operate. Few organisations have recently started conducting EC over Internet, the network of networks. Internet has also helped EC to boost up because it is a low cost alternative to the proprietary networks. EC standards are however under development. Electronic Data Interchange (EDI) is still the dominant part of EC. Information Technology has transformed the way people work. Electronic Commerce (EC) has unearthed yet another revolution which is changing the way business houses buy and sell products and services. EC is associated with buying
and selling of products and services over computer communication networks. EC transfers information electronically from computer to computer in autonomous way. EC has, in fact, transformed the way organisations operate. (e) Electronic Data Interchange (EDI)
EDI is the computer-to-computer exchange of business documents in a standard format. These formats look much like standard forms and are highly structured. (f) Teleconferencing
It refers to electronic meetings that involve people who are at physically different sites. Telecommunication technology allows participants to interact with one another without travelling to the same location.
2.
3.
In-Text Questions 5.2 1. LAN is restricted to limited geographical area whereas WAN covers long distance. In LAN the computer terminals and peripheral devices are connected with wires and cables whereas in WAN communication is done through telephone lines and satellite links. The speed of data transmission is much higher in LAN than in WAN. There are three major types of network topology. They are star topology, bus topology and ring topology. (a) False (b) True (c) False
2.
3.
6.1 Introduction
Internet is the world's largest computer network, the network of networks, scattered all over the world. It was created nearly 25 years ago as a project for the U.S. Department of Defence. Its goal was to create a method for widely separated computers to transfer data efficiently even in the event of a nuclear attack. From a handful of computers and users in the 1960s, today the internet has grown to thousands of regional networks that can connect millions of users. Using internet, organisations all over the world can exchange data, people can communicate with each other in a faster and effective way. With the help of video conferencing over the interent, it has become possible that people can even see each other while they are communicating. Even one can do all his shopping sitting back at home. He does not bother to visit crowded market place for wasting his valuable time. Gradually, shopkeepers are also interested to opt for electronic commerce which provides them greater reach, faster and better ways to do business over the internet. Don't get surprised, if tomorrow you come to know that the paanwalla in your locality has started selling his paan over the internet. Thus, the internet has thrown up a number of technological challenges like using the net for secure, private and fast communication as well as supporting video
and 3D graphics. Given this scenario of the internet, there was an implicit need to come up with a programming language to enable authors to incorporate program application fragments (applets) into the web document. Finally this gave birth to Java programming language. We will discuss about this language in detail in later part of this lesson.
6.2 Objectives
After going through this lesson you will be in a position to : explain various terminology used in interent use various services provided by interent search for desired information over internet enjoy internet surfing define e-mail and its various features explain the features of World Wide Web (WWW) explain the utility of Java programming language and its characteristics identify the relationship between java and the internet
the standard used by a network for communication. But the passing time and rapid change in information technology suppressed NCP and brought TCP/IP (Transmission Control Protocol/Internet Protocol) into the world of networking. TCP converts messages into streams of packets at the source, and they are reassembled back into messages at the destination. Internet Protocol handles the dispatch of these packets. IP handles the addressing, and makes sure that a packet reaches its destination through multiple nodes and even across multiple networks with multiple standards. This flexibility of TCP/IP to handle multiple protocols encourages other networks to get connected to ARPANET. Slowly the ARPANET became a massive network of networks and now it is known as 'Internet'. Internet is termed by some people as the world of largest democracy with no government. It has no state head to control it. Why do people want to get connected to Internet? May be because of the freedom it provides. The internet is a rare example of a large democracy with no head of state, no official censors, no bosses, no board of directors. Nobody controls the Internet and in principle, any computer can speak to any other computer, as long as it obeys the technical rules of the TCP/IP protocol. This freedom of Internet helped it to move out of its original base in military and research institutions, into elementary and high schools, colleges, public libraries, commercial sectors even into the shop of a vegetable vendor.
(a)
E-mail or electronic mail is paperless method of sending messages, notes or letters from one person to another or even many people at the same time via the Internet. E-mail is very fast compared to the normal post. E-mail messages usually take only few seconds to arrive at their destination. One can send messages anytime of the day or night and it will get delivered immediately. You need not have to wait for the post office to open and you don't have to get worried about holidays. It works 24 hours a day, seven days a week. What's more, the copy of the message you have sent will be available whenever you want to look at it even in the middle of the night. You have the privilege of sending something extra even such as a file, graphics, images etc. along with your e-mail. The biggest advantage to using e--mail is that it is cheap, especially when sending messages to other states or countries and at the same time it can be delivered to a number of people around the world. Although e-mail is faster and cheaper, it has many of the components of regular mail. It allows you to compose note, get the address of the recipient and send it. Once the mail is received and read, it can be forwarded, replied. One can even store it for later use, or delete. In e-mail even the sender can request for delivery receipt and read receipt from the recipient. (i) Features of E-mail One-to-one or one-to-many communication Instant communication Physical presence of recipient is not required Most inexpensive mail service, 24-hours a day and seven days a week Encourages informal communication (ii) Components of an E-mail Address
As in the case of normal mail system, e-mail is also based upon the concept of a recipient address. The e-mail address provides all the information required to get a message to the recipient from anywhere in the world. Consider the following e-mail ID
john@ hotmail.com In the example above, "john" is the local part, which is the name of a mailbox on the destination computer, where finally the mail will be delivered. Hotmail is the mailserver where the mailbox "john" exists,.com is the type of organisation on net, which is hosting the mail server. There are six main categories; .com Commercial institutions or organization .edu .gov .mil .net .org (b) Educational institutions Government site Military site Gateways and administrative hosts Private organizations FTP (File Transfer Protocol)
File Transfer Protocol, is an Internet utility software used to upload and download files. It gives access to directories or folders on remote computers and allows software, data and text files to be transferred between different kinds of computers. FTP works on the basis of the same principle as that of Client/Server. FTP client is a program running on your computer that enables you to talk to and get stuff from remote computers. The FTP client takes FTP commands and sends them as requests for information from the remote computer, known as FTP servers. To access remote FTP server it is required but not necessary to have an account in the FTP server. When the FTP client gets connected, FTP server asks for the identification in terms of User Login name and password of the FTP client. If one does not have an account in the remote FTP server, still he can connect to the server using anonymous login. This has been properly shown in Fig. 6.1 Using anonymous login anyone can login to a FTP server and can access public file archives, anywhere in the would, without having an account. One can easily Login to the FTP site with the username anonymous and e-mail address as password. The basic objectives of FTP are
to give flexibility and promote sharing of computer programs, files and data. to transfer data reliably and more efficiently over network. to encourage implicit or indirect use of remote computers using Internet. to shield a user from variations in file storage systems among hosts.
USER INTERFACE
SERVER A
USER A
USER
FILE SYSTEM
USER B
The basic steps in an FTP session are: Start up your FTP client; by typing ftp on your systems command line c;\> prompt (or, if you are in a Windows, double-click on the FTP icon). Give the FTP client an address to connect to. This is the FTP server address to which the FTP client will get connected. Identify yourself to the FTP remote site by giving the Login Name Give the remote site a password
Remote site will verify the Login Name/Password to allow the FTP client to access its files. Look directory for files in FTP server Change Directories if required Set the transfer mode (optional); Get the file(s) you want; and Quit (c) Telnet (Remote Computing)
Telnet or remote computing is telecommunication utility software, which uses available telecommunication facility and allows you to become a user on a remote computer. Once you gain access to the remote computer, you can use it for the intended purpose. The TELNET works in a very step by step procedure. The commands types on the client computer are sent to the local Internet Service Provider (ISP), and then from the ISP to the remote computer that you have gained access. Most of the ISP provides facility to TELNET into your own account from another city and check your e-mail while you are travelling or away on business. The following steps are required for a TELNET session Start up the TELNET program; Give the TELNET program an address to connect to Make a note of what the "escape character" is; Log in to the remote computer; Set the terminal emulation; Play around on the remote computer; and Quit.
(c)
(d)
Fig.6.2
(a)
Internet Address
Just like every house, every office, every location has an address every page on the Internet has a unique address. The address is used to get the web page for user from Internet. Just as the address of a house or office is known as its postal address, the address on the Internet is known as URL (Uniform Resource Locator). A typical Internet
address or URL would look like: http://www.nios.og/computers/internet/url.htm The URL locates a particular web page, among all the computes connected to the Internet. The URL contains the components that specify the protocol, server, and pathname of an item. Let us examine the URL given above (http:// www.nois.org/computers/inbtenet/url.htm). The protocol is followed by a colon (http:) the server is preceded by two slashes (// www.nios.org), and each segment of the pathname is preceded by a single slash (/ computers/internet/url.htm). A protocol is a set of rules that tells the computer how to interpret the information at that address. The first component, the protocol, defines the manner for interpreting computer information. Many Internet pages use HTTP (Hyper Text Transfer Protocol). Other common Internet protocols that one might come across are FTP (File Transfer Protocol), NEWS (Usenet news groups protocol), and GOPHER (an alternative transfer protocol). Gopher protocol is mostly obsolete now. The second component, the server (www.nios.edu), identifies the computer system that stores the information you seek and is always preceded by two slashes. A server is a computer that has information stored on it and sends it to the client, when a request is made. Each server on the Internet has a unique address name whose text refers to the organization maintaining the server. The last component (/computers/internet/), defines the path within the server where the requests item (url.htm) will be found. Most of the web pages will have .htm or .html as their secondary or extension name. 6.5.1 How to get connected to Internet There are various type of connectivity to get connected to Internet. They all can be broadly classified as: Gateway Access Dial-up Connection Shell Connection
TCP/IP Connection Leased Connection Gateway Access Gateway Access is also known as Level-One connection. It is the access to the Internet from a network, which is not on the Internet. The gateway allows the two different types of networks to "talk" to each other. But the users of the Gateway Network have limited access to the Internet. They might not be able to use all the tools available on Internet. The local Internet Service Provider (ISP) normally defines this limitation. Good example of network with Level One Connectivity within India is that of VSNL (Videsh Sanchar Nigam Limited). All access to Internet from India are through VSNL gateway as shown in Fig. 6.4
Internet
Fig. 6.4
Dial-up Connection Dail-up connection is also known as Level Two connection. This provides connection to Internet through a dial-up terminal connection. The computer, which provides Internet access is known as 'Host' and the computer that receives the access, is Client or Terminal. The client computer uses a modem to access a host and acts as if it is a terminal directly connected to that host. So this type of connection is also known as Remote Modem Access connection. And the host to which the client gets connected is actually connected to the Internet by a full time connection as shown in Fig 6.5
Dial-up Connection
In dial-up connection to Internet, Host carries all the command that are types on a client machine and forwards them to Internet. It also receives the data or information from the Internet on behalf of the 'Client' and passes it to them. The client computer acted as a 'dumb' terminal connected to remote host. This type of connection can further be divided into two categories. Shell Connection In this type of Internet connection, the user will get only textual matter of a Web Page. This connection does not support Graphics display. However the user will be able to surf the Internet, do FTP, receive mail. Shell Accounts were the only type of Internet access available for many years before the Internet entered in to the world of graphics and became more users friendly. TCP/IP Connection Today's graphical World Wide Web browsers provides easier access with multimedia sound and pictures. The major difference between Shell and TCP/ IP account is that shell can only display text and does not support graphics display, whereas TCP/IP can display both. Hence TCP/IP is more popular Internet connection. Shell accounts are slowly phasing out from the Internet scenario. To access any of these dial-up accounts you need the followings; Computer Modem Telephone Connection Shell or TCP/IP account from the ISP Internet client software such as Internet browser
Leased Connection Leased connection is also known as direct Internet access or Level Three connection. It is the secured, dedicated and most expensive, level of Internet connection. With leased connection, your computer is dedicated and directly connected to the Internet using high-speed transmission lines. It is on-line twenty-four hours a day, seven days a week. Leased Internet connections are limited to large corporations and universities who could afford the cost. These have been clearly shown in Fig. 6.6. Dial-up Connection VSNL Gateway Host Full Time Connection
LOCAL HOST
Leased Line
Local Client
Local Client
Local Client
Local Client
Fig. 6.6
Java is easily programmable, with a minimum of training, since it is based on C++. Most of the development tools available today are huge in size and complexity, and require powerful development platforms. But Javas's components are comparatively very small in size, enabling construction of compact software that can run 'stand-alone' even on small machines. (ii) Object Oriented
An object-oriented design enables the development of small, modular, yet selfcontained units, each of which could later be used as building block for any specific application. It also facilitates a clean definition of interfaces and allows 'plug-and-play' features, wherein reusable software components can be distributed easily across diverse hardware platforms. Programmers can even attach their applications and data together, and bundle the combination as a single
entity. Java retains many of the object oriented features and the 'look and feel' of C++. Hence, programmers can migrate easily to Java and be productive quickly. To be truly considered as 'object oriented' a programming language should support a minimum of four characteristics. Encapsulation - implements information hiding and modularity (abstraction). Polymorphism - the same message sent to different objects results in behaviour that is dependent on the nature of the object receiving the message. Inheritance - you define new classes and behaviour based on existing classes to obtain code re-use and code organization. Dynamic binding - objects could come from anywhere possibly across the network. You need to be able to send messages to objects without having to know their specific type at the time you write your code. Dynamic binding provides maximum flexibility while a program is executing. Now let us see that are objects. They are software programming models. In your everyday life you are surrounded by objects: cars, coffee machines, trees and so on. Software applications contain objects : buttons on user interfaces, spreadsheets, spreadsheet cells and so on. These objects have state and behaviour. You can represent all these things with software constructs called objects, which can also be defined by their state and behaviour. A car can be modelled by an object. It has state (how fast it is going, in which direction, its fuel consumption and so on) and behaviour (starts, stops, turns etc.) Classes are fundamental entities in Java, as they are in any object oriented language. These classes are ways of representing certain sets of data that have something in common and of providing an interface for the use of this data. Encapsulating the data makes it easy to use, safe from outside interference and also make changing the interface and data content easy. It is really simple to reuse a great portion of code already written in Java, without bothering about
how it is implemented. Java has a huge repository of reusable code, called the Application Programming Interface (API), which greatly simplifies basic programming. (iii) Portable and Interpreted
A software application written in Java, be it a word-processor or spreadsheet, a multimedia tool or virtual reality designer, will run perfectly on any computer, on any platform. A Java application is a combination of a compiled and interpreted language. The source code written by a programmer is first compiled into Byte Code which is uniform for all machines. This Byte Code is compatible with the Java interpreter which is termed as Java Virtual Machine. The interpreter converts the Byte Code into specific machine code for direct execution, on any machine to which it has been ported. So, you may write your code anywhere and run it anywhere else. This is very useful because most programmers worry whether their programs will run on other systems. (iv) Architecture-Neutral
The Java Compiler generates an architecture-neutral object file, 'generic' Byte Code instructions, which have nothing to do with a particular computer architecture. This compiled code is executable on any processor, given the presence of the Java run-time system, which will translate it into native machine code on the fly. The same version of the software runs on all platforms, independent of any CPU or hardware architecture, across networks. (v) Dynamic
By making interconnections between modules at run-time, Java completely avoids dependency on other software components like libraries. Therefore, Java applications are always ready-to-run, without any side-effects, irrespective of changes or revisions that may take place in those external components. (vi) Distributed
Java has an extensive library of routines for easy distribution of applications as it abides by industry standard networking protocols like TCP/IP, HTTP, FTP. Java
applications can open and access objects across the net via URLs with the same case that programmers are used to when accessing a local file system over a network. (vii) Automatic Memory Management The Java garbage collector keeps tracks of all objects generated, automatically freeing the memory used by objects that have no further use and are not referred to by other existing objects. This contributes enormously to making the code robust. (viii) Multi-Threaded Multithreading is a way of building applications with multiple processes. Support for multithreading enables the efficient execution of programs that potentially have multiple threads of control. Thus, the garbage collector is efficiently run as a background process overcoming the biggest drawback of garbage collector based languages. Multithreading is supported via inheritable thread class libraries. The result is better interactive response and near real-time features. This enables Java to interface and support many features of modern operating systems and new protocols. Modern network based applications, such a the Hot Java WWW browser, typically need to do several things at the same time. A user working with Hot Java can run several animation concurrently while downloading an image and scrolling the page, Java's multithreading capability provides the means to build applications with many concurrent threads of activity. Multithreading thus results in a high degree of interactivity for the end user. (ix) Robust
Java programs are robust because explicit memory manipulations by the programmer are prevented. (x) Secured
Java programs are secured : distributed applications have to exhibit the highest levels of security concerns. A typecode verifier in the Java interpreter ensures that the complied code is strictly language compliant, thus trapping all malafide modifications, more so the computer viruses parading as legal code.
one way, liberating you from having to worry about compatibility between software and hardware. The hardware configuration before and after Java is shown in Fig. 6.7 and Fig. 6.8 respectively. SOURCE CODE
Fundamentals of Internet and Java Programming :: 121 SOURCE CODE COMPILER MACHINE CODE BIOS OPERATING SYSTEM
SOURCE CODE COMPILER JAVA INTERPRETER BIOS JAVA VIRTUAL MACHINE JUST IN TIME COMPILER OPERATING SYSTEM HARDWARE
With Java, data and programs - the twin staples of computing - do not have to be stored on your computer anymore. They can reside anywhere on the Internet, called up by whoever needs them and whenever they need them. The WWW introduced millions of users to the world of the Internet. But for their charm, most Web pages themselves are nearly as static as their book or magazine counterparts. Although the Web is technically equipped to supply video and sound, the user needs to have the right software to make use of them. Java allows you to package software along with data. In other words, when you download a video clip, you also automatically get the software needed to play it.
One thing is certain. The Web has become a powerful computer which anybody can use, so costly desktop systems will soon be replaced by a simple computer connected to the Internet and capable of executing any program dynamically loaded from anywhere in the world. Companies will sell computing capabilities over the Internet, just like our electricity boards supply us with power. In the near future, a sizable part of our preferred activity will be over the Internet and our success depends on our ability to adapt to and use the Internet technologies. Future of Java Java runs slower than conventional programming languages and the software libraries that streamline a programmer's task are still being written for it. Java has been a programming language for clients with a rather weak server support: Most of the programs developed in Java are applets designed to perform small functions like animating logos, sketching cartoon characters, etc. Application software for client/server environments are to be developed. For these kinds of applications, Java needs a clean, higher-level interface to databases and servers, like ODBC (Object Data Base Connectivity) and OLE (Object Linking and Embedding), to access data. While these issues are being addressed, India has also jumped on the Java bandwagon. Java is seen as a very good opportunity for the Indian software industry. With an online connectivity to the rest of the world and a steady growth rate in the industry, Java would probably catalyse the reorientation required for the Indian software industry to make its mark globally.
(c)
5.
2.
(c) (d)
Physical presence of recipient not required Most inexpensive mail service, 24 hours a day and seven days a week. Encourages informal communication
(e) 3.
Basic objectives of FTP are: (a) to give flexibility and promote sharing of computer programs, files and data. to transfer data reliably and more efficiently over network. to encourage implicit or indirect usae of remote computers using Internet. to shield a user from variations in file storage systems among hosts. E-mail (b) network FTP (c) ISP
(b) (c)
(d)
4.
(a) (d)
In-Text Questions 6.2 1. The world wide web or simply the web is built on top of the Internet. It is hypertext based information retrieval tool. Various ways of connectivity are: (a) (b) (c) (d) (e) 3. Gateway Access Dial-up Connection Shell Connection TCP/IP Connection Leased Connection (b) Flase (c) True (d) True
2.
(a) False
In-Text Questions 6.3 1. Various characteristics are: (a) (b) (c) (d) (e) 2. Simple and small Object oriented Portable and interpreted Dynamic and distributed Robust and Secure
7 Introduction to C++
7.1
Introduction
C++ is an extension to C Programming language. It was developed at AT&T Bell Laboratories in the early 1980s by Bjarne Stroustrup. It is a deviation from traditional procedural languages in the sense that it follows object oriented programming (OOP) approach which is quite suitable for managing large and complex programs. An object oriented language combines the data to its function or code in such a way that access to data is allowed only through its function or code. Such combination of data and code is called an object. For example, an object called Tutor may contain data and function or code as shown below: Object : Tutor
DATA Name Dept Empcode | | | FUNCTION Tot_pay ( ) Deductions ( ) Net_pay ( ) | | |
The data part contains the Name, Dept and Employee code. The function part consists of three functions: To_pay ( ), Deductions ( ) and Net_pay ( ) Thus, the various objects in the object-oriented language interact with each other through their respective codes or functions as shown in Fig. 7.1 Object A Object B
Data Function
Data Function
It may be noted here that the data of an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions of other objects.
7.2 Objectives
After going through this lesson, you would be able to: learn about C++ character set, tokens and basic data types explain the utility of different types of operators used in C++ identify the difference between implicit and explicit conversions explain about Input/Output streams supported by C++ explain the structure of a C++ program write a simple program in C++
Introduction to C++ :: 3
7.3
Character set is a set of valid characters that a language can recognise. A character represents any letter, digit or any other special character. The C++ has the following character set. Letters Digits A-Z, a-z 0-9 Space +-*/^\()[]{}=!=<> . " $ , ; : % ! & ? _ # <= White spaces Horizontal tab (>), Blank space, Carriage return (< ) Newline, form feed. >= @
Special Characters
7.4
Every program specifies a set of operations to be done on some data in a particular sequence. However, the data can be of many types such as a number, a character, boolean value etc. C++ supports a large number of data types. The built in or basic data types supported by C++ are integer, floating point and character type. A brief discussion on these types is given below:
7.5 Tokens
A token is a group of characters that logically belong together. The programmer can write a program by using tokens. C++ uses the following types of tokens. Keywords Identifiers Literals Punctuators Operators
7.5.1 Keywords
There are some reserved words in C++ which have predefined meaning to complier called keywords. Some commonly used keywords are given below: List of Keywords asm auto break case catch char class const continue default delete do double else enum extern float for friend goto if inline int long new operator private protected public register return short signed sizeof static struct switch template this try typedef union unsigned virtual void volatile while
Introduction to C++ :: 5
7.5.2 Identifiers
Symbolic names can be used in C++ for various data items used by a programmer in his program. For example, if a programmer wants to store a value 50 in a memory location, he/she choose any symbolic name (say MARKS) and use it as given below: MARKS = 50 The symbol = is an assignment operator. The significance of the above statement is that MARKS is a symbolic name for a memory location where the value 50 is being stored. A symbolic name is generally known as an identifier. The identifier is a sequence of characters taken from C++ character set. The rules for the formation of an identifier are: (i) (ii) (iii) An identifier can consist of alphabets, digits and/or underscores. It must not start with a digit. C++ is case sensitive, i.e., upper case and lower case letters are considered different form each other. It may be noted that TOTAL and total are two different identifier names. It should not be a reserved word.
(iv)
7.5.3 Literals
Literals (often referred to as constants) are data items that never change their value during the execution of the program. The following types of literals are available in C++. (i) (ii) (iii) (iv) (i) integer-constants character-constants floating-constants string-literals Integer constants
Integer constants are whole numbers without any fractional part. It may contain either + or sign, but decimal point or commas does not appear in any integer constant. C++ allows three types of integer constants. Decimal (Base 10) Octal (Base 8) Hexadecimal (Base 16)
Decimal integer constants It consists of sequence of digits and should not begin with 0 (zero). For example 124, - 179, + 108. Octal integer constants It consists of sequence of digits starting with 0 (zero). For example, 014, 012. Hexadecimal integer constant It consists of sequence of digits preceded by ox or OX. For example OXD, OXC. The suffix l or L and u or U attached to any constant forces it to be represented as a long and unsigned respectively. (ii) Character constants
A character constant in C++ must contain one or more characters and must be enclosed in single quotation marks. For example A, 9, etc. C++ allows nongraphic characters which cannot be typed directly from keyboard, e.g., backspace, tab, carriage return etc. These characters can be represented by using a escape sequence. An escape sequence represents a single character. The following table gives a listing of common escape sequences. Escape Sequence \a \b \f \n \r \t \v \? \\ \ \ \ xhh Nongraphic Character Bell (beep) Backspace Formfeed Newline or line feed Carriage return Horizontal tab Vertical tab Question mark Backslash Single quote Double quote Hexadecimal number (hh represents the number in hexadecimal) Octal number (00 represents the number in octal) Null
\ 000 \0
Introduction to C++ :: 7
(iii)
Floating constants
They are also called real constants. They are numbers having fractional parts. They may be written in fractional from or exponent form. A real constant in fractional form consists of signed or unsigned digits including a decimal point between digits. For example 3.0, -17.0, -0.627 etc. A real constant in exponent form has two parts: a mantissa and an exponent. The mantissa is either an integer or a real constant followed by letter E or e and the exponent which must be an integer. For example 2E03, 1.23E07. (iv) String Literals
A sequence of character enclosed within double quotes is called a string literal. String literal is by default (automatically) added with a special character \O which denotes the end of the string. Therefore the size of the string is increased by one character. For example COMPUTER will be represented as COMPUTER\O in the memory and its size is 9 characters.
7.5.4 Punctuators
The following characters are used as punctuators in C++. Brackets [ ] opening and closing brackets indicate single and multidimensional array subscript. opening and closing brackets indicate functions calls, function parameters for grouping expressions etc. opening and closing braces indicate the start and end of a compound statement. it is used as a separator in a function argument list. it is used as a statement terminator. it indicates a labelled statement or conditional operator symbol. it is used in pointer declaration or as multiplication operator. it is used as an assignment operator. it is used as pre-processor directive.
Parentheses ( )
Braces {
Comma
Semicolon ; Colon :
7.5.5 Operators
Operators are special symbols used for specific purposes. C++ provides six types of operators. Arithmetical operators Relational operators Logical operators Unary operators Assignment operators Conditional operators Comma operator Arithmetical operators An operator that performs an arithmetic (numeric) operation: +, -, *, / , or %. For these operations always two or more than two operands are required. Therefore these operators are called binary operators. The following table shows the arithmetic operators. Operators + / % Meaning Addition Subtraction Multiplication Division Modulus/Remainder Example 8+ 5 8- 5 8 5 8/ 5 8%5 Result 13 3 40 1 3
Note : There is no operator which gives exponent in C++ Relational operators The relational operators are used to test the relation between two values. All relational operators are binary operators and therefore require two operands. A relational expression returns zero when the relation is false and a non-zero when it is true. The following table shows the relational operators.
Introduction to C++ :: 9
Relational operators < <= == > >= != Example 1 int x = 2; Int l = 1; int y = 3; int z = 5; The following statements are true (i) (ii) (iii) (iv) (v) (vi) l==1 x<y z>y y>=1 x!=1 l<=1
Meaning Less than Less than or equal to Equal to Greater than Greater than or equal to Not equal
Logical operators The logical operators are used to combine one or more relational expression. The following table shows the logical operators. Operators || && ! Meaning OR AND NOT
The NOT operator is called the unary operator because it requires only one operand. Example 2 int x = 5; int z = 9; int y = 7; (x > y) & & (z > y) The first expression (x > y) evaluates to false and second expression (z > y) evaluates to true. Therefore, the final expression is false.
In AND operation, if any one of the expression is false, the entire expression is false. In OR operation, if any one of the expression is true, the entire expression is true. In NOT operation, only one expression is required. If the expression is true, the NOT operation of true is false and vice versa. Unary operators C++ provides two unary operators for which only one variable is required. For Example 3 a = - 50; a = + 50; a = - b; a = + b;
Here plus sign (+) and minus sign (-) are unary because they are not used between two variables. Assignment operator The assignment operator = stores the value of the expression on the right hand side of the equal sign to the operand on the left hand side. Example 4 int m = 5, n = 7; int x, y, z; x = y = z = 0; In addition to standard assignment operator shown above, C++ also support compund assignment operators. C++ provides two special operators viz ++ and - - for incrementing and decrementing the value of a variable by 1. The increment/decrement operator can be used with any type of variable but it cannot be used with any constant. With the prefix version of these operators, C++ performs the increment or decrement operation before using the value of the operand. For instance the following code. int sum, ctr; sum = 12; ctr = 4; sum = sum + (++ctr); will produce the value of sum as 17 because ctr will be first incremented and then added to sum producing value 17.
Introduction to C++ :: 11
Similarly, the following code sum = 12; ctr = 4; sum = sum + ( - - ctr); will produce the value of sum as 15 because ctr will be first decremented and then added to sum producing value 15. With the postfix version of these operators, C++ first uses the value of the operand in evaluating the expression before incrementing or decrementing the operands value. For example, the following code sum = 12; ctr = 4; sum = sum + (ctr + +); will produce the value of sum as 16 because ctr will be first used in the expression producing the value of sum as 16 and then increment the value of ctr by 1 (ctr becomes now 5) Similary, the following code sum = 12; ctr = 4; sum = sum + (ctr - -) will produce the value of sum as 16 because ctr will be first used with its value 4 producing value of sum as 16 and then decrement the value of ctr by 1 (ctr becomes 3). Let us study the use of compound assignment operators in the following table : Operator += -= %= /= = Example 5 int x = 2; / / first x + = 5; / / second In the second statement, the value of x is 7 Example A+=2 A-=2 A%=2 A/=2 A=2 Equivalent to A=A+2 A=A-2 A=A%2 A=A/2 A=A2
Conditional operator The conditional operator ?: is called ternary operator as it requires three operands. The format of the conditional operator is: Conditional_expression ? expression1 : expression2; If the value of conditional_expression is true then the expression1 is evaluated, otherwise expression2 is evaluated. Example 6 int a = 5; int b = 6; big = (a > b) ? a : b; The condition evaluates to false, therefore big gets the value from b and it becomes 6. The comma operator The comma operator gives left to right evaluation of expressions. It enables to put more than one expression separated by comma on a single line. Example 7 int i = 20, j = 25; int sq = i i, cube = j j j; In the above statements, comma is used as a separator between two statements / expressions.
Introduction to C++ :: 13
The expression in the following example is calculated from left or right. Example 9 5 + 4 / 3 * (5 - 3) /2 = 5+4/3*2/2 = 5+1*2/2 = 5+2/2 = 5+1 = 6 The following table shows the precedence of operators. ++, - - (post increment / decrement) ++ (Pre increment) - - (Pre decrement), sizeof ( ), ! (not), - (unary), + (unary) , /, % +, <, <=, >, >= = =, ! = && ?: = Comma operator Lowest Highest
Mark True (T) or False (F) for the following: (a) (b) (c) (d) (e)
3. 4.
List out the various types of token used in C++. List out the data types supported by C++.
Introduction to C++ :: 15
When two operands of different type are encountered in the same expression, the lower type variable is converted to the higher type variable. The following table shows the order of data types. Order of data types Data type long double double float long int char (lowest) The int value of b is converted to type float and stored in a temporary variable before being multiplied by the float variable c. The result is then converted to double so that it can be assigned to the double variable a. order (highest)
7.9 Constants
A number which does not charge its value during execution of a program is known as a constant. Any attempt to change the value of a constant will result in an error message. A constant in C++ can be of any of the basic data types. const qualifier can be used to declare constant as shown below: const float Pi = 3.1215; The above declaration means that Pi is a constant of float types having a value 3.1415. Examples of valid constant declarations are: const int rate = 50; const float Pi = 3.1415; const char ch = A;
7.10 Variables
A variable is the most fundamental aspect of any computer language. It is a location in the computer memory which can store data and is given a symbolic name for easy reference. The variables can be used to hold different values at different values at different times during the execution of a program. To understand more clearly we should study the following statements: Total = 20.00; ... (i) Net = Total - 12.00; ... (ii) In statement (i), a value 20.00 has been stored in a memory location Total. The variable Total is used in statement (ii) for the calculation of another variable Net. The point worth noting is that the variable Total is used in statement (ii) by its name not by its value. Before a variable is used in a program, it has to be defined. This activity enables the compiler to make available the appropriate type of location in the memory. The definition of a variable consists of the type name followed by the name of the variable. For example, a variable Total of type float can be declared as shown below: float Total; Similarly the variable Net can also be defined as shown below: float Net; Examples of valid variable declarations are: (i) (ii) int count; int i, j, k;
(iii) char ch, first; (iv) float total, Net; (v) long int sal;
Introduction to C++ :: 17
In addition to the above I/O streams, two operators << and >> are also used. The operator << is known as put to or bit wise shift operator. The operator >> is known as extraction or get from operator. Let us consider a situation where the user desires to display a message My first computer on the screen. This can be achieved through the following statement: cout << My first computer; Once the above statement is carried out by the computer, the message My first computer will appear on the screen. Similarly the following program segment defines a variable sum of integer type, initializes it to value 100 and displays the contents of the variable on the screen. . . . int sum; sum = 100; cout << The value of variable sum=; cout << sum; . . . Once the above program segment is obeyed by the computer, the following output is displayed on the screen: The value of variable sum = 100 From the above discussion we see that cout is the standard output stream of C++ by virtue of which output can be displayed on the screen. However the put to operator << is also required to hand over the contents of the variable to cout as shown in Fig. 7.2 cin is the standard input stream (keyboard) and it can be used to input a value entered by the user from the keyboard. However, the get from operator >> is also required to get the typed value from cin as shown in Fig. 7.3 and store it in the memory location. Let us consider the following program segment: . . . int marks;
cin>> marks; . . . In the above segment, the user has defined a variable marks of integer type in the first statement and in the second statement he is trying to read a value from the keyboard. Once this set of statements is obeyed Variable
Memory VDU
sum
100
Fig. 7.2 Usage of cout and < < Memory Input stream Cin Get from operator
Variable marks
by the computer, whatever is typed on the keyboard (say 87) is received by the cin standard input stream. cin then hands over the typed value to get from operator >> which ultimately stores it in memory location called marks. The contents of this variable can be displayed on the screen by the statements given below: cout << marks=; cout << marks;
Introduction to C++ :: 19
We can use more than one output or put to operators within the same output statement as shown below. The activity is known as cascading of operators: cout << marks = << marks; The output of this statement will be marks = 87
This is my first program in C++ .................................................... Various components of this program are discussed below: (i) Comments First three lines of the above program are comments and are ignored by the compiler. Comments are included in a program to make it more readable. If a comment is short and can be accommodated in a single line, then it is started with double slash sequence in the first line of the program. However, if there are multiple lines in a comment, it is enclosed between the two symbols /* and */ Everything between /* and */ is ignored by the complier. (ii) Include <iostream.h> The lines in the above program that start with symbol # are called directives and are instructions to the compiler. The word include with # tells the compiler to include the file iostream.h into the file of the above program. File iostream.h is a header file needed for input/output requirements of the program. Therefore, this file has been included at the top of the program. (iii) void main ( ) The word main is a function name. The brackets ( ) with main tells that main ( ) is a function. The word void before main ( ) indicates that no value is being returned by the function main ( ). Every C++ program consists of one or more functions. However, when program is loaded in the memory, the control is handed over to function main ( ) and it is the first function to be executed. (iv) The curly brackets and body of the function main ( ) A C ++ program starts with function called main ( ). The body of the function is enclosed between curly braces. These braces are equivalent to Pascals BEGIN and END keywords. The program statements are written within the brackets. Each statement must end by a semicolon, without which an error message is generated. Example 11 Write a C ++ program that reads two values x and y, exchanges their contents and prints the output. Solution: Let us assume x and y are of type int. We will use a variable temp of type int as a temporary location. The program is given below: # include <iostream.h> main ( )
Introduction to C++ :: 21
{ int x, y temp; // ... Read the values x and y cout << Enter the values:; cin >> x >> y; // ... Exchange the contents temp = x; x = y; y = temp; // display the output now cout <<"the exchanged values are: << x << y; }
Mark True (T) or False (F) in front of the following: (a) (b) (c) (d) (e) The computer value of an arithmatic expression is always a numerical value. \n is the remainder operator. Arithmatic operations on characters is allowed in C++. the output of logical AND operation is true if one of its operand is true. + = is a compound assignment operator.
3.
Evaluate the following expressions. (a) (b) (c) 5/3 * 6 6.0 * 5/3 6 * 5/3
How many ways are there in C++ to represent an integer constant? State the rules for comment statement? What is an Escape sequence. Describe any two backslash character constant? Explain briefly about stardard Input/Output stream of C++. Write the equivalent C++ expression for the following Alegbraic expression: (i) 2AB + 2BC + 2CA 2A (ii) 4 3 x2
6. 7.
(iii) b2 - 4ac 2a 8. Evaluate the following C++ expression: Int a, b=2, k = 4; a = b * 3/4 + k/4 + 8 - b + 5/8;
Introduction to C++ :: 23
9.
10.
Write an appropriate C++ statement for each of the following: (i) (ii) read the values of a, b and c write the values of a and b in one line followed by the value of c on another line. write the values of a and b in one line separated by blanks and value of c after two blank lines.
(iii)
11.
Write a program that will find out the square of a given number.
Various type of tokens used in C++ are: (i) Keywords (ii) Identifiers (iii) Literals (iv) Punctuators (v) Operators
4.
Data types are: (i) Integer type (int) (ii) Floating point type (float) (iii) Character type (char)
8.1 Introduction
The object-oriented programming (OOP) is a different approach to programming. Object oriented technology supported by C++ is considered the latest technology in software development. It is regarded as the ultimate paradigm for the modelling of information, be that data or logic.
8.2 Objectives
After going through this lesson, you would be able to: learn the basic concepts used in OOP describe the various benefits provided by OOP explain the programming applications of OOP.
8.4.1 Objects
It can represent a person, a bank account or any item that a program can handle. When a program is executed, the objects interact by sending messages to one another. For example, if customer and account are two objects in a program, then the customer object may send message to account object requesting for a bank balance. Each object contains data and code to manipulate data. Objects can interact without having to know details of each others data or code. It is sufficient to know the type of massage accepted and the type of response returned by the objects.
8.4.2 Classes
We have just mentioned that objects contain data and function or code to manipulate that data. The entire set of data and code of an object can be made a user-defined data type with the help of a class. In fact objects are variables of type class. Once a class has been defined, we can create any number of objects associated with that class. For example, mango, apple and orange are members of class fruit. If fruit has been defined as a class, then the statement fruit mango, will create an object mango belonging to the class fruit.
8.4.5 Modularity
The act of partitioning a program into individual components is called modularity. It gives the following benefits. It reduces its complexity to some extent. It creates a number of well-defined, documented boundaries within the program. Module is a separate unit in itself. It can be compiled independently though it has links with other modules. Modules work quite closely in order to achieve the programs goal.
8.4.6 Inheritance
It is the capability to define a new class in terms of an existing class. An existing class is known as a base class and the new class is known as derived class. Number of examples can be given on this aspect. For example, a motor cycle is a class in itself. It is also a member of two wheelers class. Two wheelers class in turn is a member of automotive class as shown in Fig. 8.1. The automotive is an example of base class and two wheelers is its derived class. In simple words, we can say a motor cycle is a two wheeler automotive. C++ supports such hierarchical classification of classes. The main benefit from inheritance is that we can build a generic base class, i.e., obtain a new class by adding some new features to an existing class and so on. Every new class defined in that way consists of features of both the classes. Inheritance allows existing classes to be adapted to new application without the need for modification.
Scooter Attributes
Bus Attributes
Truck Attributes
Car Attributes
Fig. 8.1
8.4.7 Polymorphism
Polymorphism is a key to the power of OOP. It is the concept that supports the capability of data to be processed in more than one form. For example, an operation may exhibit different behaviour in different instances. The behaviour depends upon the types of data used in the operation. Let us consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are strings then the operation would produce a third string by concatenation.
(d)
Object oriented programs are executed much faster than conventional programs. Since C is a subset of C++, C programs will run under C++ compilers.
(e) 2. 3.
Why is data considered safe if encapsulated ? Differentiate between data hiding and encapsulation.
(ii)
The other application areas of OOP are parallel programming, simulation and modelling, AI and Expert systems, Neural Networks and CAD systems.
(c) (d)
(e) 2.
Mark True or False in front of the following : (a) (b) C++ is an extension to C programming language. Functions of one object cannot access the functions of other objects in C++ Inheritance is capability to define a new class in terms of an existing class. Abstraction refers to the act of representing essential features without including the background details. An object is a new data type.
(c)
(d)
(e) 3.
Differentiate the following : (a) (b) Procedural and object-oriented programming An object and a class
Encapsulation ensures that only authorised functions access that relevant data. The measure against unauthorised access ensures data safety. Data hiding is a property when the internal data structure of an object is hidden from the rest of the program. On the other hand, data encapsulation is the mechanism by which data and its associated functions are bound together within an object definition in such a way that only relevant information is exposed and rest remains hidden. Thus data encapsulation implements data hiding.
3.
computer to do something. The focus is on the processing, the algorithm needed to perform the desired computation. In procedural paradigm, the emphasis is on doing things. The object-oriented approach views a problem in terms of objects involved rather than procedure for doing it. (b) An object is an identifiable entity with some characteristics and behaviour. It represents an entity that can store data and its associated functions. A class is a group of objects that share common properties and relationships.
9 Control Statements
9.1 Introduction
The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending on the requirements of a problem it might be required to alter the normal sequence of execution in a program. The statements which specify the order of execution of statements are called control flow statements. There are many control flow statements provided in C++ that will be discussed in this lesson.
9.2 Objectives
After going through this lesson, you would be able to: differentiate between a statement and compound statement learn about the conditional statements familiarize with the loop statement differentiate between while and do-while loop identify the jump statements explain how to exit from the program
9.3 Statements
Statements are the instructions given to the computer to perform any kind of action. Action may be in the form of data movement, decision making etc. Statements form
the smallest executable unit within a C++ program. Statements are always terminated by semicolon.
condition T statement1
Control Statements :: 35
From the flowchart it is clear that if the 'if condition' is true, statement 1 is executed; otherwise it is skipped. The statement 1 may either be a single or compound statement. Example 1 if else statement syntax of the if- else statement if (condition) statement1; else statement2; statement3
Fig. 9.2
condition
statement2
statement1
From the above flowchart it is clear that the given condition is evaluated first. If the condition is true, statement1 is executed, followed by statement3. If the condition is false, statement2 is executed, followed by statement 3. It should be kept in mind that statement1 and statement2 can be single or compound statement. Example 2 Write a program that will print the greatest of two numbers. # include <iostream.h> void main () { int x, y; cout << Enter two numbers <<\n; cin>> x >> y ; if ( x > y) cout << The bigger number is << X; else cout << The bigger number is <<y; } Example 3 Write a program that will calculate the sum of odd numbers and sum of even numbers for numbers 1 to 10.
# include <iostream.h> void main () { int sum 1, sum2; sum1 = sum2 = 0; for (int i=1; I < = 10; i++) if (i % 2 = = 0) sum 1 + = i ; else sum2+ = i ; cout << sum of odd number = << sum 2 << \n; cout << sum of even number = << sum 1 << \n; } Example 4 Write a program that will print the greatest of three numbers. # include <iostream.h> void main () { int x, y, z, l; cout << Enter three numbers <<\n; cin >> x >> y>>z; if (x > y ) l=x; else l=y; if (l > z) cout << The greatest number is << l; else cout << The greatest number is <<z; } Nested if statement Syntax of the nested if statement
Control Statements :: 37
(i)
The if block may be nested in another if or else block. This is called nesting of if or else block. F condition1 If (condition1) { if (condition2) { statement(s); } }
Fig. 9.3
T condition2 T statement F
(ii)
if (condition 1) statement1; else if (condition2) statement2; else statement 3; T statement2 condition2 F statement3 F condition1 T statement1
Fig. 9.4
From the flowchart it is clear that condition 1, condition2, etc. are nested in sequence until a condition is reached that evaluates to TRUE. Only one statement will be executed. If condition1 is TRUE, then statement1 is executed. If none of the conditions is TRUE, then statement 3 is executed. Regardless of which statement is executed, control is passed to the statement following statement3. Each statement can be single or compound statement. Example 5 Write a program that will find the greatest of three numbers. # include < isostream.h> void main ( )
{ int x, y, z; cout << Enter three numbers << \n; cin >> x >> y >> z ; if ( x > y ) { if (x >z) cout << The greatest number is << x; else cout << The greatest number is <<z; } else { if (y > z) cout << The greatest number is << y; else cout The greatest number is << z; } } Example 6 Write a program using nested if condition that will enter total marks and assign grades according to the following: Mark > = 90 > = 80 and < 90 > = 70 and < 80 > = 60 and < 70 < 60 # include <iostream.h> void main ( ) { int marks; Grade A B C D Fail
Control Statements :: 39
cout << Enter total marks << \n; cin >> marks; if (marks > = 90) cout << A Grade; else if (marks > = 80) cout << B Grade; else if (marks > = 70) cout << C Grade; else if (marks > = 60) cout << D Grade; else Cout << Failed; } switch statement The if and if-else statements permit two way branching whereas switch statement permits multiple branching. The syntax of switch statement is: switch (var / expression) { case constant1 : statement1;
| | |
The execution of switch statement begins with the evaluation of expression. If the values of expression matches with the constant then the statements following this statement execute sequentially till it executes break. The break statement transfers control to the end of the switch statement. If the value of expression does not match with any constant, the statement with default is executed. Evaluation of expression
Is Value = constant1
Statement1
Is Value = constant2
Statement2
F Default T Statement3
Fig.9.5
Example 7 # include < iostream.h> void main ( ) { char ch; cout << "Enter a character"; cin >> ch; switch (ch) {
Control Statements :: 41
case 'a' case 'e' case 'o' case 'i' case u default } }
: : : : : :
cout << "vowel a"; break ; cout << "vowel e"; break ; cout << "vowel o"; break ; cout << "vowel i" break ; cout << vowel u; break; cout <<not a vowel;
The program needs the break statement to confine execution to particular portion of switch. If the break statement is removed from the above program then it starts executing the statements associated with case labels specified till it comes across either the break statement or end of switch statement. The above switch statement can be written as: switch (ch) { case a case A case e case E case i case I case o case O default
: : : : : : : : :
cout << vowel a; cout << vowel e; cout << vowel i; break; cout << vowel o; break; cout << not a vowel;
Example 8 Write a program that will accept a one character grade code and depending on what grade code is input, display the Basic salary according to the table given below: Grade A B C D # include < iostream.h> void main ( ) { char grade; cout << Enter Grade << \n; cin >> grade; switch (grade) { case A case B case C case D default } } : : : : : cout << Basic salary is 15000; break; cout << Basic salary is 12000; break; cout << Basic salary is 10000; break; cout << Basic salary is 9000; break; cout << Invalid grade code; Basic salary 15000 12000 10000 9000
Control Statements :: 43
2.
What is a selection statement? Write down the name of selection statements provided by C++. What is the significance of default clause in switch statement? Identify the error(s), if any, in the following programs and write them in correct format. a) # include <iostream.h> void main ( ) int a, b; cin << b; <<a; if (a > b) Max = a } b) # include <iostream.h> void main( ) { int x, y; cin >> x ; for (y = 0 ; y < 10, y ++) if x = = y cout << y + x ; else cout >> y; }
3. 4.
5.
What will be the output of the following program segments. a) cin >> x; if ( x = = 10 ) cout << x is 10 ; else cout << x is not 10 ; if the input given is (i) 11 (ii) 10
b)
int year ; cin >> year ; if (year % 100 = = 0) if (year % 400 = = 0) cout << Leap ; else cout << Not century year ; if the input is (i) 2000 (ii) 1971
c)
int year ; cin >> year ; if (year % 100 = = 0) { if (year % 400 = = 0) cout << Leap ; } else cout << Not century year ; if the input given is (i) 2000 (ii) 1971
6.
Write equivalent switch statement for the following: if (code = = a) cout << season is summer ; else if (code = = r) cout << season is rainy ; else if (code = = w) cout << season is winter; else cout << wrong code ;
Control Statements :: 45
7.
What would be the value of c? { int c; float a, b; a = 245.05; b = 40.02 ; c = a + b; } a) 285.09 b) 2850 c) 285 d) 285.0
8.
What would be the value of i and k? { int i, j, k ; j=5; i=2*j/2; k = 2 * (j/2) ; } a) i=4, k=4 b) i=4, k=5 c) i=5, k=4 d) i=5, k=5
9.
What is the output of the following program? void main ( ) { int x = 5, y = 6, z = 7; if (x < y + z) cout << Hello \n ; else { cout << How \n ; cout << Are you \n; } } a) Hello b) How c) Are you d) None of the above
10.
Consider the program fragment. switch (choice) { case W case R case B default } What would be the output if choice = R a) RED b) RED BLUE error c) RED error d) WHITE RED BLUE : : : : cout << WHITE ; cout << RED ; cout << BLUE ; cout << error ; break ;
While loop Syntax of while loop while (condition) { statement(s); } T Loop Body condition F
Fig. 9.6
Control Statements :: 47
The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop body is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly as long as the condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to the statement next to the while loop. To make it more clear, we take the following example. Example 9 To find the sum of first ten natural numbers i.e. 1, 2, 3, ..........................10. # include <iostream.h> void main ( ) { int n, total = 0 ; n=1; while (n < = 10) { total + = n ; n++; } cout << sum of first ten natural number << total : } The variable n is called a loop control variable since its value is used to control loop repetition. Normally, the three operations listed below must be performed on the loop control variable. (i) (ii) (iii) Initialize the loop control variable Test the loop control variable Update the loop control variable
Operation (i) must be performed before the loop is entered. Operation (ii) must be performed before each execution of the loop body; depending on the result of this test, the loop will either be repeated or make an exit. Operation (iii) must be included as part of the loop body. Unless the loop control variable is updated in the loop body, its value cannot change and loop exit will never occur.
Loop body
condition
The flow diagram indicates that after each execution of the loop body, the condition is true, the loop body is executed again. If the condition evaluates to false, loop exit occurs and the next program statement is executed. Note : that the loop body is always executed at least once. One important difference between the while loop and the do-while loop is the relative ordering of the conditional test and loop body execution. In the while loop, the loop repetition test is performed before each execution of the loop body; the loop body is not executed at all if the initial test fails. In the do-while loop, the loop termination test is Performed after each execution of the loop body; hence, the loop body is always executed at least once. Let us take an example to explain it further. Example 10 To find the sum of the first N natural number. # include < iostream.h> void main ( ) { int N, number, sum; cin >> N; sum = 0; number = 1; do { sum + = number;
Control Statements :: 49
number + + ; } while (number < = N) ; cout << sum; } For loop It is a count controlled loop in the sense that the program knows in advance how many times the loop is to be executed. syntax of for loop for (intialization; decision; increment/decrement) { statement(s); } Initialize control variable to initial value
Yes
Fig. 9.8
The flow diagram indicates that in for loop three operations take place: (i) (ii) (iii) Initialization of loop control variable Testing of loop control variable Update the loop control variable either by incrementing or decrementing.
Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test whether the condition is true or false. If the condition is true, the program executes the body of the loop and then the value of loop control variable is updated. Again it checks the condition and so on. If the condition is true, it gets out of the loop. Example 11 for (int i = 0 ; i < 5 ; i + + ) cout << i ; The output of the above program is 0 1 2 3 4
for (char i = A; i < E ; i + + ) cout < < i ; The output of the above program is A B C D
Control Statements :: 51
while ( i + + < 5) s + = i; b) int s = 0 ; i = 0; do s+=i; while ( i < 5 ) ; 6. What will be the output of the following program ? a) # include <iostream.h> void main ( ) { long number = 7866372, result = 0 ; do { result * = 10 ; int digit = number % 10 ; result + = digit ; number / = 10 ; } while (number) ; cout << output = << result << endl; } b) void main ( ) { int i = 0, a = 0, b = 0, c = 0, f = 0 ; while ( i < = 5) { switch (i + +) { case 1 : case 2 : + + a ; case 3 : case 4 : + + b ;
case 5 : + + c ; default : + + f ; } cout << a << \n ; cout << b << \n ; cout << c << \n ; cout << f << \n ; } 7. What will be the value of counter after the following program is executed ? void main ( ) { int counter ; int digit = 0 ; counter = 1 ; while (digit < = 10) { + + counter ; + + digit ; } cout <<counter ; } a) 8. 9 b) 10 c) 11 d) 12
What will be the value of sum after the following program is executed ? void main ( ) { int sum, i ; sum = 1 ; i=9; do { i=i-1; sum = 2 * sum ;
Control Statements :: 53
What is the following program doing ? void main ( ) { int digit = 0 ; do { cout << digit + + << \n ; } while (digit < = 10); } a) b) c) d) Display integers from 1 to 10 Display integers from 0 to 10 Adding 10 integers None of the above
10.
What is the final value of digit ? void main ( ) { int digit ; for (digit = 0 ; digit < = 9 ; digit + + ) cout << digit << \n ; digit = 5 * digit ; - - digit ; } a) 49 b) -1 c) 47 d) 46
goto statement syntax of goto statement goto pgr; | | | pgr : pgr is known as label. It is a user defined identifier. After the execution of goto statement, the control transfers to the line after label pgr. Note : It is not a good programming to use goto statement in a program. Break statement syntax of break statement The break statement can be used in a switch statement and in any of the loops. It causes program execution to pass to the next statement following the switch or the loop. while (condition) { statement 1; if (condition) break ; statement 2; } statement 3;
Control Statements :: 55
The break statement skips rest of the loop and goes out of the loop. continue statement The continue statement is used in loops and causes a program to skip the rest of the body of the loop. while (condition) { statement 1; If (condition) continue ; statement 2; } statement 3; The continue statement skips rest of the loop body and starts a new iteration.
The break statement causes an exit i) only from the innermost loop
only from the innermost switch from all loops and switches from the innermost loop or switch
A continue statement within a loop causes control to go to ___________________________. Which header file must be included in the program for using the exit ( ) function. Rewrite the following program segment using goto statement i = 100 ; while (i) cout << i -- ; cout << \n Thank you ;
4.
5.
6.
Rewrite the following program segment using a while loop. i=2; start : cout << i ; i+=2; if ( i < 51) goto start ; cout << \n Thank you ;
7.
What will be the output of following program ? # include < iostream.h> void main ( ) int x = 10, count = 0 ; while (x) { x--; if (x = = 4) continue ; count + + ; } cout << \n <<count ; }
Control Statements :: 57
8.
# include < iostream.h> void main ( ) { char ch = A ; while (ch < = F ) { switch (ch) { case A : case B : case C : case D : ch + + ; continue ; case E : case F : ch + + ; } putchar (ch) ; }
} What will be the output of the above program ? a) ABCDEF b) FG c) EFG d) None of the above
1. 2. 3. 4.
Create a data file Display a data file Edit a data file Exit
Choice : 2. Write a program that will accept a mark and assign letter grade according to the following table. Grade A B C D F 3. 4. 5. 6. Mark > = 90 > = 80 but < 90 > = 70 but < 80 > = 60 but < 70 < 60
Write a program that will print sum of N integers entered by the user. Write a program to generate the members of fibonacci series upto 500. Write a program to reverse a given number. Write a program that will print the table of any number upto any number. input : Enter the table of which number : 4 Enter upto which number : 5 Output 4x1=4 4x2=8 4 x 3 = 12 4 x 4 = 16 4 x 5 = 20 Continue (Y/N) ?
7.
Write a program that will print the factorial of any number. input : 5 Output : 5 x 4 x 3 x 2 x 1 = 120
Control Statements :: 59
8. 9.
Write a program to print all the tables between 2 and 20 upto 10. Write a program that will find pythagorean triplets between 1 to 100. (Pythagorean triplets are such that the square of one number is equal to the sum of the squares of the other two numbers). Example : 3, 4, 5 52 = 32 + 42 25 = 9 + 16 = 25
10.
Determine the roots of the quadratic equation ax2 + bx + c = 0 using the formula x = -b
11.
12.
Write a program that will take a number N as input and print the factorial of all numbers from 1 to K as follows : Number 1 2 3 | | | N Factorial 1 2 6 | | | N1
13.
Write a program that will find out whether the given number is even or odd. If odd number then whether it is prime or not. Write a program that will ask the user to enter N integers. Find out the following: (i) (ii) (iii) Total number of positive integers Total number of negative integers Total number of integers equal zero
14.
2.
3.
4.
Control Statements :: 61
c)
(i) (ii)
6.
Switch (code) { case a : cout << season is summer ; break; case r : cout << season is rainy; break; case w : cout << season is winter; break ; default : cout << wrong code;
7. 8. 9. 10.
c) c) Hello b)
2.
5.
a) b)
6.
a) b)
7. 8. 9. 10.
d) b) b) a)
the decision statement of loop process.h i = 100 ; xyz : i -- ; if i > 0 goto xyz ; cout << \n Thank you ;
6.
i=2; while ( i < 51) { cout << i ; i + = 2, ; } out << \n Thank you ;
7. 8.
9 (b)
10 Functions
10.1 Introduction
Functions in C ++ are available under C++ library header files. It provides declarations of the function prototypes, class definition, etc. For example, double sqrt (float); The above declaration specifies that the sqrt function takes only one argument of type float and return double type. To make use of predefined functions, the header file (that contains the functions prototypes) must be included in a program using a preprocessor directive # include.
10.2 Objectives
After going through this lesson, you would be able to: familiarize with the use of # include directive and its requirement in the program define functions included in math.h, ctype.h and string.h header files explain character handling functions which help in input/output operations define inline function and function with default value
A header file may be included in one of two ways. # include <iostream.h> or # include iostream.h The header file in angle brackets <and> means that file reside in standard include directory. The header file in double quotes means that file reside in current directory.
Mathematical Functions
Mathematical functions like sin ( ), cos ( ), etc. are defined in header file math.h. Some of the important mathematical functions are given in the following table. Some standard mathematical functions Function sin(x) cos(x) tan(x) asin(x) acos(x) exp(x) log(x) log10(x) sqrt(x) pow(x, y) abs(x) fabs(x) Meaning Sine of an angle x (measured in radians) Cosine of an angle x (measured in radians) Tangent of an angle x (measured in radians) Sin-1 (x) where x (measured in radians) Cos-1 (x) where x (measured in radians) Exponential function of x (ex) logarithm of x Logarithm of number x to the base 10 Square root of x x raised to the power y Absolute value of integer number x Absolute value of real number x
Functions :: 65
Character Functions
All the character functions require ctype.h header file. The following table lists the function. String isalpha(c) isdigit(c) Functions It returns True if c is a Letter (A to Z or a to z) otherwise False. It returns True if c is a digit (0 through 9) otherwise False. It returns True if c is a digit from 0 through 9 or an alphabetic character (either uppercase of lowercase) otherwise False. It returns True if c is a lowercase letter otherwise False. It returns True if c is an uppercase letter otherwise False. It converts c to uppercase letter. It converts c to lowercase letter.
isalnum(c)
islower(c)
String Functions
The string functions are present in the string.h header file. Some string functions are given below: strlen(S) It gives the no. of characters including spaces present in a string S. It concatenates the string S2 onto the end of the string S1. The string S1 must have enough locations to hold S2. It copies character string S2 to string S1. The S1 must have enough storage locations to hold S2.
strcat(S1, S2)
strcpy(S1, S2)
strcmp((S1, S2) = =0) It compares S1 and S2 and finds out strcmp((S1, S2)>0) strcmp((S1, S2) <0) whether S1 equal to S2, S1 greater than S2 or S1 less than S2.
The header file for above functions is stdio.h. The first two functions deal with single character and last two functions deal with string (group of characters).
Getchar ( ) function
The getchar ( ) function returns a single character from a standard input device (keyboard). It takes no parameter and the returned value is the input character. The general form of the getchar ( ) function is : A = getchar ( ) ; The variable A is of the type character. It inputs a character from the keyboard and assign it to variable A.
putchar ( ) function
The putchar ( ) function takes one argument, which is the character to be sent to output device. It also returns this character as a result. The general form of the putchar ( ) function is : putchar (ch) ; where ch is a variable of type character. Example 1 # include < iostream.h > # include < stdio.h> void main ( ) { char ch; ch = getchar ( ) ; putchar (ch); }
Functions :: 67
The above program takes a character from the keyboard and prints it on the screen.
gets ( ) function
The gets ( ) function gets a string terminated by a newline character from the standard input stream stdin. The gets ( ) replaces the newline by a null character (\0). It also allows input string to contain white space characters (spaces, tabs), gets return when it encounters a newline; everything upto the newline is copied into A. gets (A) ; Example 2 # # { char A [ 100 ]; cout << Input a string; gets (A); puts (A); } Some More Functions The getch ( ) and getche ( ) functions The general form of the getch ( ) and getche ( ) is ch = getche ( ) ; ch1 = getch ( ) ; ch and ch1 are the variables of type character. They take no argument and require the conio.h header file. On execution, the cursor blinks, the user must type a character. The value of the character returned from getche ( ) is assigned to ch. The getche ( ) function echoes the character to the screen. That's why there's an e in getche. Another function, getch ( ), is similar to getche ( ) but does not echo the character to the screen. Example 3 To count the no. of characters and words in a sentence entered by the user. include < stdio.h > include < iostream.h >
void main ( )
# # {
void main ( ) char ch; int chcnt = 0, wdcnt = 1; while ( (ch = getche ( ) ) ! = \r) { if (ch = = ) wdcnt + + ; else chcnt + + ; } cout < < No. of characters < < chcnt << \n cout < < No. of words < < wdcnt; } The above program counts the no. of characters and no. of words in a sentence terminated by return key. The \r reads the return key character.
Functions :: 69
6.
What will be the output of the following programs. (a) # include < iostream.h > # include < stdio.h> void main ( ) { char name [100]; puts (enter your name ); gets (name); puts (Hello); puts (name) ; } Input : MOHIT (b) # include < iostream.h> # include < stdio.h> viod main ( ) { char c; c = getchar ( ); while ( c ! = .) { putchar (c); c = getchar ( ); } Input : RUBY
7.
Fill in the blanks : a) b) c) d) e) f) All header files have an extension ....................... Character functions are available in ....................... The function toupper (C) converts C to ................... In strcpy (S1, S2) the string................. copies onto the string................ The function which counts the length of the string is .......................... The sin ( ) function is available in .........................
8.
State whether the following are True or False. a) b) c) d) e) f) g) h) i) The isdigit ( ) function checks whether the entered character is digit or not. All string functions are available in stdio.h. The iostream.h contains all input/output functions. The tolower (C) converts C to lowercase. strcat (S1, S2) splits two strings into three strings. pow (x, y ) claculates y to the power x. cos (x) returns the cosine of angle (x). tolower ( ) function is available in ctype.h. The log (x) is available in string.h.
Functions :: 71
Since the return type of function is int by default, the keyword int in main ( ) header is optional. Consider the program given below : # include < iostream. h > void main ( ) { cout < < Computer Science \n; } It prints computer science on the screen. We can also write the above program in the following way: # include < iostream.h> void message ( ); void main ( ) { message ( ) ; } void message ( ) { cout << Computer Science\n; } The above program also prints computer science but it uses a function message for printing. In addition to functions main ( ) and message ( ), the program has an extra line after # include preprocessor directive. The line is void message ( ). This is known as function prototype.
called actual parameters. The variable which receive the value from called statement are termed formal parameters. Consider the following example that evaluates the area of a circle. # include < iostream.h > void area (float); void main ( ) { float radius; cin >> radius; area (radius ) ; } void area (float r) { cout << The area of the circle is << 3.1416 *r* r << \n; } The statement area (radius), that invokes the function, may be written as area (6.0); This will evaluate and display the area of a circle with radius 6.0 Here radius is called actual parameter and r is called formal parameter.
Functions :: 73
cout < < The area of the circle is < < y; } float area (float r) { return ( 3.1416 *r* r) ; } In function protoype, void is replaced by float, this indicates that value returned by the function area to main function is float. In the calling function variable y is assigned the value returned by function area ( ). Thus, variable y will be assigned the area of a circle.
Local variable A variable declared within the body of a function will be evaluated only within the function. The portion of the program in which a variable is retained in memory is known as the scope of the variable. The scope of the local variable is a function where it is defined. A variable may be local to function or compound statement. Global variable A variable that is declared outside any function is known as a global variable. The scope of such a variable extends till the end of the program. These variables are available to all functions which follow their declaration. So it should be defined at the beginning, before any function is defined. If in a program, variable a is declared as local as well as global. Then a represents the local variable : : a represents the global variable. The symbol : : is called scope resolution operator Example 4 # include < iostream.h >
int m = 2; void main ( ) { int m = 15; { int m = 10 * : : m; cout < < m = < < m < < \n; cout < < : : m = < < : : m < < \n } cout < < m = < < m < < \n; cout < < : : m = < < : :m < < \n; } The output of the above program is m= 20 :: m = 2 m = 15 ::m=2 Variables and Storage class The storage class of a variable determines which parts of a program can access it and how long it stays in existence. The storage class can be classified as (i) Automatic (ii) Register (iii) Static (iv) External. Automatic variable All variables by default are auto , i.e., the declarations int a and auto int a area equivalent. Auto variables retain their scope till the end of the function in which they are defined. An automatic variable is not created until the function in which it is defined is called. When the function exits and control is returned to the calling program, the variables are destroyed and their values are lost. The name automatic is used because the variables are automatically created when a function is called and automatically destroyed when it returns. Example 5 # include , iostream.h > void sum (int); void main ( )
Functions :: 75
{ int i; for (i = 1; i < =5; i + +) sum (i); } void sum (int n) { auto int s = 0; s = s + n; cout << s << \n; } The output of the program is 1 2 3 4 5 Register variable A register declaration is an auto declaration. A register variable has all the characteristics of an auto variable. The difference is that register variable provides fast access as they are stored inside CPU registers rather than in memory. The register and auto can be applied to local variable. Static variable The variable may be static automatic variable or static external variable. The later one is meaningful only in multifile programs. A static automatic variable has the visibility of a local variable but the lifetime of an external variable. Thus it is visible only inside the function in which it is defined, but it remains in existence for the life of the program. If in the previous program auto int s = 0 is changed to static int s = 0. The output of the program will be 1 3 6 10 15
External variable A large program may be written by a number of persons in different files. A variable declared global in one file will not be available to a function in another file. Such a variable, if required by functions in both the files, should be declared global in one file and at the same time declared external in the second file. Example : extern int a; Where extern is the keyword for external.
Call-by-value Consider the following program which will swap the value of two variables using the method call-by-value. # include < iostream.h> void swap (int, int); void main ( ) { int a, b; cin > > a > > b; swap (a, b); cout < < a < < b < < \n; } void swap (int c, int d) { int t; t = c; c = d; d = t; cout < < c < < d < < \n; }
Functions :: 77
The variables a and b are called actual parameters. When calling the function swap ( ) the value of a is passed onto c and value of b is passed onto d. Here c and d are called formal parameters.
5 a 5 c
In the function swap ( ), the value are swapped but this change will not be implemented to actual parameters. Input Output 5 6 5 Call-by-reference Consider the following program which will swap the value of two variables using call-by-reference method. # include < iostream.h > void swap (int &, int &); void main ( ) { int a , b; cin > > a > > b; swap (a, b); cout < < a < < b < < \n; } void swap (int &c, int &d) 6 5 6
{ int t; t = c; c = d; d = t; cout < < c < < d < < \n; } In this method, when the function is called, the address is transferred from actual to formal parameters. It means a and c are sharing the same memory address and b and d are sharing the same memory address. 6 5 a/c Input Output 5 6 b/d 5 6 6 6 5 5
Functions :: 79
return (r*r*r*); } void main ( ) { int number, y; cout < < Enter number; cin > > number; y = cube (number); cout < < The cube of the number is < < y; } Some important points to be noted : (i) (ii) (iii) (iv) (v) Function is made inline by putting a word inline in the beginning. Inline function should be declared before main ( ) function. It does not have function prototype. Only shorter code is used in inline function. If longer code is made inline then compiler ignores the request and it will be executed as normal function.
The call Average = result ( 60, 70, 80); passes the value 80 to marks 3. The important point to note is that only the trailling argument can have default values. Consider the following program: # include < iostream.h> void repchar (char = =, int = 30); void main ( ) { repchar ( ); repchar ( *); repchar (+, 45); } void repchar (char ch, int x) { for (int i= 1; i < = x; i + + ) cout < < ch; cout < < \n; } The default argument follows an equal sign, which is placed directly after the type name. In the above program, the function repchar ( ) takes two arguments. It is called three times from main ( ).
l
First time it is called with no argument. The function assigns the default value = to ch and 30 to x and it print = symbol thirty times on the screen. Second time it is called with one argument. The function assigns the default value 30 to x and it prints * symbol thirty times on the screen. Third time it is called with two argument. The actual parameters take priority over the default parameters. It prints + symbol forty-five times.
Function Overloading This means that some function name can be used to create functions that perform a variety of different tasks. This is known as function polymorphism in OOP. The function would perform different operations depending on the argument list in function call. The correct function to be invoked is determined by checking the number and
Functions :: 81
type of arguments. For example, an overloaded function mpy ( ) handles different types of data as follows: / / Declaration void mpy (int, int); void mpy (int, float); void mpy (float, int); void mpy (float, float); / / Function calls cout < < mpy (3.5, 1.2); cout < < mpy (2, 5); cout < < mpy (5.2, 6); cout < < mpy (7, 6.2); // // // // uses prototype 4 uses prototype 1 uses prototype 3 uses prototype 2 // // // // prtotoype 1 prototype 2 prototype 3 prototype 4
A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. A best match must be unique. The function selection involves the following steps: (i) The compiler tries to find an exact match in which types of actual arguments are the same and use that function. If an exact match is not found, the compiler uses the integral promotions to the actual arguments, such as char to int float to double to find a match. (iii) When either of them fails, the compiler tries to use the built in conversions (the implicit conversions) to the actual arguments then uses the function whose match is unique. If the conversion is possible to have multi matches, then the compiler will generate an error message. Suppose, we use the following two functions:long abc (long n); double abc (double x);
(ii)
A function call such as abc (10) will cause an error because int argument can be converted to either long or double, thereby creating an ambiguous situation. (iv) If all the steps fail, then the compiler will try the user defined conversions in combination with integral promotions and built in conversions to find a unique match.
A function printchar is defined as void printchar (char ch = *, int len = 40) { for (int x = 0; x < len ; x + + ) cout < < ch; cout < < \n; } How will you invoke the function printchar for following output: (a) to print * 40 times (b) to print * 20 times (c) to print = 40 times (d) to print = 30 times
6.
Functions :: 83
{ return x * 3 ; } Write a main function that is necessary to call this function. 7. What will be the output of the following programs ? (a) # include < iostream.h> void add (float); void main ( ) { float x = 5.0; add (x ); cout < < x ; } void add (float x) { x = x + 2; } # include < iostream.h > void add (float); float x = 5.0; void main ( ) { add (x); cout < < x ; } void add (float x) { x = x + 2; } # include < iostream.h > float add (float); void main ( ) { float x = 5.0;
(b)
(c)
float y; y = add (x); cout < < x < < < < y < < \n } float add (float x) { return (x +2); } (d) # include < iostream.h > void P1 (int &, int); void main ( ) { int a = 5; int b = 6; cout < < output of the program \n; cout < < values of a and b are < <a < < b < < \n; P1 (a, b); cout < < values of a and b are << a << b; } void P1 (int & a, int b) { a=7; b = 10 ; } include < iostream.h > int a, b; void try2 (int x, int & y); void main ( ) { int a = 10 ; int b = 7 ; try2 (a, b); cout < < a < < b < < \n; } void try2 ( int x, int & y)
(e)
Functions :: 85
{ b = x; y = y + b; x = y; cout < < x < < y < < b < < \n; } 8. Fill in the blanks: (a) (b) (c) (d) (e) (f) (g) 9. Any C++ program contains at least ..............function(s). After each function has done a job, control returns to .................. The declaration of a function in the calling program is known as a function ................... the function can be called in two ways ................ and ........................ When the return type is not specified, the default return type of function is ......................... To return the control back to the calling function, we use the keyboard.......................... In an ......................... function, looping is not allowed.
State whether the following are true or false. (a) (b) (c) (d) (e) (f) (g) (h) (i) (j) There is a limit on the number of functions that might be present in a C++ program. A variable which is declared inside the function is called global variable. When function is not returning anything, return type is void. An inline function is preferred when its size is small. In call by reference, any change made in the object inside the function will reflect in the value of the actual object. A C ++ program can have more than one function with the same name. Inline is a keyword in C++ An inline function must be defined before it is called. Any function in C++ can be declared as inline function. It is necessary to specify the variable name in the function prototype.
2.
3.
4.
Write a program that will count the number of characters in a sentence entered by user. Write a program that will count the number of words in a sentence entered by the user. Write a program that will count the number of A's, E's, I's, O's and U's in a sentence. Differentiate between the following : (i) (ii) Actual and Formal parameters Call by value and call by reference
6.
7.
8.
9.
Functions :: 87
What are the advantages of function prototype in C++? What is the main advantage of passing the arguments by reference ? When do we need to use default arguments in a function? What do you mean by overloading of a function? Write a program in C++ to call a function which will return the cube of a given number using inline function. Write a program in C++ that prints the largest of two number entered from the keyboard. Pass the two numbers to a function as argument, find the largest and return this value to a main function.
15.
2.
3. 4. 5.
6.
uppercase S2 strlen ( ) math.h T (b) T (h) F T (c) (i) T F (d) T (e) F (f) F
2.
3.
4.
void main ( ) { int y, l; cout < < Enter value ; cin > > y ; l = threetimes (y) ; cout < < l; }
Functions :: 89
7.
5 5 5 7
(e)
17 10
17 17
10
8.
1 statement after calling function statement prototype call by value call by reference int return inline (b) F (g) T (c) T (h) T (d) T (i) F (e) T (j) F
9.
(a) F (f) T
11 Array
11.1 Introduction
The ordered collection of identical elements is called an array. Sometimes, it is required to store a large number of variables of the same type, one can use an array. For example: int A[5] ; The above statement declares an array A which reserves 5 memory locations for storing integer data type. These locations are A[0], A[1], A[2], A[3] and A[4]. The number within the square bracket is called index or subscript. The array can be one dimensional (one subscript) or two dimensional (two subscripts).
11.2 Objectives
After going through this lesson, you would be able to: explain the concept of an array define, access and initialize array elements perform common operations on arrays explain two dimensional array define, access and initialize two dimensional array elements
Array :: 91
Traversal It means to access each location of an array, may be for display purpose. Consider a program which will read five values from the user and finds out the maximum value. # include < iostream.h > void main ( ) { int T, A[5], l; cout < < Enter five values; for ( l = 0; l < 5; l ++) cin > > A [ l ]; T = A [ 0 ]; for (l = 1; l < 5; l++) { if (T < A [l]) T = A [ l ]; } cout < < Maximum value < < T; } Searching This method finds out whether the data entered by the user is present in an array or not. There are two types of searching method. (i) (ii) Linear or Sequential search Binary search
Linear or sequential search This method is slower, inefficient and works on unsorted list. If the data we are searching is not present in the list, we come to know at the end of the list. / / Linear search # include < iostream.h > void main ( ) {
Array :: 93
int A[5], l, data, flag = 0; cout < < Enter five values; for (l = 0; l < 5; l ++) cin > > A [l]; cout >> Enter data to be searched; cin >> data; for (l=0; l < 5; l ++) { if (A[l] = = data) flag = 1; } if (flag = = 1) cout < < Data present; else cout << Data not present; }
Binary search
This method requires the array to be either in ascending or descending order. This method calculates the mid location form initial and final locations and compares the data with the value present in mid location. Consider the case where the list is in ascending order. If data is less than a [mid] then data is present in the upper half otherwise data is present in the lower half. The value of either final or initial will be changed. The mid value is calculated again and searching continues till the data is found or initial is greater than final. The values of initial, final and mid for searching a value of 35 in an ascending order sorted list containing 9 elements is shown below:
10 location (0)
15 (1)
18 (2)
20 (3)
27 (4)
30 (5)
35 (6)
40 (7)
45 (8)
Initial + Final Initial Final Mid = 2 0 5 8 8 4 6 27 35 Search is successful / / Binary search # include < iostream.h > const int N = 9; void main ( ) { int A[N], l, initial, final, mid, data; cout < < Enter nine values in ascending order; for (l = 0; l < N; l ++) cin >> A [l]; cout << Enter data to be searched; cin >> data; initial = 0; final = N - 1; mid = (initial + final) / 2; While (initial < = final) & & (A[mid]! = data)) { if (A [mid] > data) final = mid - 1; else initial = mid + 1; } if (A [mid] = = data) cout << data is present; if (initial > final) cout <<data not present in the list; } The advantage of Binary search is that each search cuts the list in to half. A list of 10,000 names can be searched in just 12 searches. A [Mid]
Array :: 95
Sorting It is a method to arrange the list either in ascending or descending order. Bubble sort Consider an array of five locations to be sorted in ascending order:
-1 Index 0
9 1
5 2
0 3
2 4
In this sorting method, A[0] is compared with A[1]. If A[0] is greater than A[1], the values are swapped. Then A[1] is compared with A[2], A[2] is compared with A[3], and A[3] is compared with A[4]. In all cases if the ith location has value greater than I + 1, the values are swapped. The entire process is repeated N-1 times where N is the number of data in an array. # include < iostream.h > const int N = 5; void main ( ) { int A [N], l, j, T; cout << Enter values; for (l = 0; l = N; l ++) cin >> A [ l ]; / / sorting for ( l = 0; l < N - 1; l ++) for (j = 0; j < N - 1; j ++) If (A[j] > A [j + 1]) { T = A [ j ]; A [ j ] = A [ j + 1 ]; A [ j + 1 ] = T; } cout << Sorted array is; for (l = 0; I < N; l ++) cout << A [ l ]; }
Selection sort Consider an array having N elements to be sorted in ascending order. Initially, first element is compared with others so that it holds the smallest value. In the next pass, second element is compared with others so that it holds the smallest value. This procedure is repeated for the entire array. # include < iostream.h > const int N = 5; void main ( ) { int A [N], l, j, T; cout << Enter values; for ( l = 0; l < N; l ++ ) cin >> A [ l ]; / / sorting for ( l = 0; l < N - 1; l ++ ) for (j = l; j < N; j ++ ) If (A [l] > A [j]) { T = A [l]; A [l] = A [j]; A [j] = T; } // printing the sorted data for ( l = 0; l < N; l ++ ) cout < < A [ l ]; } Insertion It means addition of a data item in the middle or at the end of the array. If data is to be added after a given data item then the location of the data item is first determined by applying search procedure and then the insertion procedure is implemented. # include < iostream.h > void main ( ) { int x [20] ;
Array :: 97
int l, loc, n, data; cout << Enter the no. of elements; cin >> n; for (l = 0; l < n; l ++ ) { cout << Enter the array element; cin >> x [ l ]; } cout << Enter the location after which data is to be inserted; cin >> loc; for (l = n - 1; l > = loc; l - - ) x [ l + 1 ] = x [ 1 ]; cout << enter the new data to be added; cin >> x [loc]; n ++ ; cout << Array elements after insertion; for (l = 0; l < n; l ++) cout << x [ l ]; } Let data 12 to be inserted at location 2 0 1 2 3 4 6 8 9 7 10 0 1 2 3 4 5 Before insertion Deletion It means removal of a data. First the location of the item to be deleted is determined by applying an appropriate search procedure and then the value present at particular 6 8 12 9 7 10 After insertion
location is deleted. # include < iostream.h > void main ( ) { int x [20] ; int l, j, n, loc, data; cout << Enter the no. of elements; cin >> n; for (l = 0; l < n; l ++) { cout << Enter value; cin >> x [ l ]; } cout << Enter the location to be deleted; cin >> loc; if (loc ! = 0) { data = x [loc ]; for {j = loc; j < n - 1; j ++ ) x [ j ] = x [ j + 1]; } n = n - 1; cout << Elements after deletion; for ( l = 0; l < n; l ++) cout << x [ l ]; } 0 1 2 3 4 5 12 7 9 10 Before deletion After deletion Let data 7 to be deleted present at location 2 0 1 2 3 5 12 9 10
Array :: 99
4.
5.
What will be the output of the following programs: (a) # include < iostream.h > void main ( ) { int a [ 5 ], t ; for (i= 0; i < 5; i ++ ) a [i] = 5 * i; for (i = o; i < 5; i ++) cout << a [ i ]; } (b) # include < iostream.h > void main ( ) { char title [ ] = Computer; for ( int i = 0; title [ i ]; i ++) cout << \n << (title + i); }
Initialization of Two Dimensional Array The initialization is done at the time of declaration of an array. For example: int A [2] [4] = {1, 2, 3, 4, 5, 6, 7, 8); For more clarity int A [2] [4] = { {1, 2, 3, 4 }, {5, 6, 7, 8} }; The above data can be grouped. The inner braces are ignored by the compiler. For two dimensional array, two loops are required. The following program finds out the maximum value stored in two dimensional array. # include , iostream.h > const int M = 5; void main ( ) { int A [M] [M], i, j, T; cout >> \n Enter Array Elements; for (i = 0; i < = M - 1; i ++ ) for (j = 0; j < = M - 1; j ++ ) cin >> A [i] [j];
Array :: 101
T = A [0] [0]; for ( i = 0; i < = M - 1; i + + ) for (j = 0; j < = M - 1; j + + ) { If (T < A [ i ] [ j ] T = A [ i ] [ j ]; } cout << Largest value << T << \n; }
2. 3. 4.
5. 6.
Which method is better: Bubble or Selection sorting? Why ? Write a program that will read 20 float values in a one dimensional array and find out the following: (i) (ii) (iii) Number of values greater than zero. Number of values equal to zero. Number of values less than zero.
7.
Write a program that will find out the sum of two diagonals of two dimensional array of A [N] [N]. Write a program that will find out whether the data entered by the user present in a one dimensional array of 10 elements using: (i) (ii) Linear search Binary search
8.
9.
Write a program that will sort the given ten numbers in descending order using: (i) (ii) Bubble sort Selection sort
Array :: 103
6.
(a) (b)
10
15
20
(b)
12.1 Introduction
Sometimes it is required to store information, which can be of same or different types. For this purpose, structure statement is used. This lesson contains the three important statements of C++ language.
12.2 Objectives
After going through this lesson, you would be able to: define variable, initialize and access members of the structure explain the concept of nested structure explain typedef statement in a program define enum statement and use it
12.3 Structure
A structure is a collection of simple variables which can be of same or different types. The data items in a structure are called the members of the structure. Consider the following example: # include < iostream.h >
struct student { char name [20]; int marks; }; void main ( ) { student S1, S3; cin >> S1. name >> S1. marks; cout << S1. name << S1. marks; student S2 = {ANKIT, 32}; cout << S2. name << S2. marks; S3 = S2; cout << S3. name << S3. marks; }
Note that one structure variable can be assigned to another only when they are of the same structure type, otherwise compiler will give an error.
cout << Date << b. date _of_birth. date << \n; cout << Year << b. date_of_birth.year << \n; cout << Address << b.add << \n; }
10.
Write a C++ nested structure for the record given below. Use appropriate data type. Name Class Roll Address House No Street City State PIN Code
Declare a variable of the structure. Assign the value of each variable in a nested structure. 11. Write statements in the following program segment that will assign values to all the fields of a structure. struct date { int dd, mm, yy; }; struct donor { char N [ 20 ]; date dob; }; void main ( ) { donor person; --------------------------------}
12.
What will be the output of the following programs. (a) # include < iostream.h > void main ( ) { struct rollno { int roll; }; rollno r; r. roll = 100; cout << roll = << r. roll; }
(b)
# include < iostream.h > void main ( ) { struct student { int roll; int age; }; student S1 = { 100, 15 }; student S2 = S1; if ( S1 = = S2 ) cout << The structures are equal; else cout << The structures are not equal; }
12.4 Typedef
It is used to define new data type for an existing data type. It provides an alternative name for standard data type. It is used for self documenting the code by allowing descriptive names. (for beltes understanding) for the standard data type.
The general format is: typedef existing datatype new datatype; For example: typedef float real; Now, in a program one can use datatype real instead of float. Therefore, the following statement is valid: real amount;
For example: jan = 0, feb = 1, mar = 2, apr = 3, may = 4 The ordering can be altered by using an equal sign and value. enum months { jan = 1, feb, mar, apr, may }; Here jan = 1, feb = 2, mar = 3, apr = 4, may = 5 The value of the next element in the list is previous value plus one. For example: # include < iostream.h > enum months { jan, feb, mar, apr, may }; void main ( ) { months m1, m2; m1 = jan; m2 = apr; int diff = m2 - m1; cout << Months between << diff << \n; if (m1 > m2) cout << m2 comes before m1; } The output of the above program is Months between 3 because the members of the enumerated series is stored as integer constant in the memory.
3. 4.
Can the enum data input by the user? (a) Write a statement that declares an enumerated data type called months with the values jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec (b) Define two variables m1 and m2 and assign them the values jan and mar respectively.
5.
The first three members of an enum type are normally represented by the values ..........................., ................... & ...................... Write a statement that declares an enumerated data type called colour with the values pink, red, green, and blue. Give these four names the integer values 33, 45, 58 and 78.
6.
for (today = sun; today < = sat; today ++ ) cout << \n today is << today; } 3. State the reason why enum boolean {false, true}; is better than enum boolean {true, false}; 4. 5. What is the advantage of typedef statement? A phone number, such as 786-6370, can be thought of having two parts; the exchange code and the number. Write a program in C++ that uses a structure phone to store these two parts. Call the structure phone. Create two structure variable of type phone. Initialize one and have the user input a number for the other one. Then display both the numbers.
2.
3. 4. 5. 6. 7.
8.
9. 10.
18 struct add { char houseno [ 5 ]; char street [ 10 ]; char city [ 10 ]; char state [ 10 ]; char zip [ 10 ]; }; struct biodata { char name [ 20 ]; char class [ 5 ]; into roll; add address [ 30 ]; }; biodata data; cin > > data. name; cin > > data. class; cin > > data. roll; cin > > data. address. houseno; cin > > data. address. street; cin > > data. address. city; cin > > data. address. state; cin > > data. address. zip;
11.
cin > > person. N; cin > > person. dob. dd; cin > > person. dob. mm; cin > > person. dob. yy;
12.
(a) (b)
13.1 Introduction
In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together. Constructor is a specially designed class and destructor returns the memory addresses back to the system.
13.2 Objectives
After going through this lesson, you would be able to define class and object access the members of the class learn about three visibility modes: public, private and protected familiarize with constructor and its types define constructor with default arguments use destructor
13.3 Class
A class is way to bind the data and its associated functions together. It allows data
functions to be hidden, if necessary from external use. A class specification has two parts. (i) (ii) Class declaration Class function definitions
The general format of a class declaration is class class-name { private : Variable declarations; Function declarations; public: Variable declarations; Function declarations; protected : Variable declarations; Function declarations; }; The keyword class is followed by the name of the class. The body of the class is enclosed between braces and terminated by semi-colon. The class body contains the declaration of variables and functions. These are collectively called members. The variables declared inside the class are called data members. The functions are known as member functions. The keywords public, private and protected are called visibility modes. The data member and member functions present in private and protected mode can be accessed by the member function in public mode. the private and protected modes are exactly the same except that protected can be inherited (covered later) but private mode cannot be inherited. Therefore, for the class concept, private mode is used. The use of keyword private is optional. By default, the members of a class are private. If the labels are missing, members are private by default. Such a class is completely hidden from outside world and does not serve any function.
Example 1 # include < iostream.h > class student { private : char name [ 80 ]; int rn ; float marks ; private : void getdata ( ) ; void putdata ( ) ; }; void student : : getdata ( ) { cin >> name >>rn >> marks ; } void student : : putdata ( ) { cout << name << rn << marks ; } void main ( ) { student st ; st. getdata ( ) ; st. putdata ( ) ; }
class student { } x, y, z ; The above definition would create the object x, y and z of type student.
{ cout << name << rn << marks : } }; (ii) Outside the class : When a function has larger code then it should be defined outside the class declaration. The prototype of such functions, however, must be provided in the class definition. The operator : : known as scope resolution operator is used to associate member functions to their corresponding class. The format is : return _type class_name : : function_name
void greatest : : getdata ( ) { cout <<Enter values of x, y, z << \n; cin >> x >> y >> z ; } void greatest : : display ( ) { cout << largest value << largest ( ) << \n; } void main ( ) { greatest A; A. getdata ( ) ; A. display ( ) ; }
for ( i = 0; i < 10; i ++) e [ i ]. getdata ( ) ; for (i = 0; i < 10; i ++ ) e [ i ] .putdata ( ); In the above program, the ten objects are created, namely, e [ 0 ], e [ 1 ] ---------e [ 9 ]. The statement e [ i ]. getdata ( ) will get the data of the ith element of the array e.
7.
(c)
(d) 8.
Whether the following are True or False. (a) (b) A class contains only private data members. A class member is accessed using dot operator.
(c) (d)
The class declaration must end with a semicolon. Scope resolution operator always be used for definition of member functions outside the class declaration.
13.4 Constructor
A constructor is a special member function that initializes the objects of its class. It is special because its name is the same as the class name. It is invoked automatically whenever an object is created. It is called constructor because it constructs the values of data members of the class. It does not have any return type, not even void. A constructor is declared and defined as follows : class student { int rn; int total ; public student ( ) { rn = 0 ; total = 0 ; } }; The declaration student st ; Invokes the constructor, student ( ) and assign rn = 0 and total = 0.
class student { int rn, total ; public student (int x, int y) { rn = x ; total = y ; } }; When the object is created, we must supply arguments to the constructor function. This can be done in two ways: By calling the function explicitly By calling the function implicitly The first call is implemented as follows : student S1 = student ( 1, 70 ) ; The second call is implemented as follows : student S1 ( 1, 70 ) ; The second method is used very often as it is shorter.
rn = i. rn ; total = i. total ; } }; The above program has both parameterized and copy constructor. The statement student S1 ( 1, 75 ) ; calls the parameterized constructor and assigns 1 to rn and 75 to total. The statement student S2 (S1) ; uses copy constructor and initializes an object S2 from another object S1. Another form of the statement is student S2 = S1 ; The process of initialization through a copy constructor is known as copy initialization. Note that the statement S2 = S1 ; does not invoke the copy constructor. However, it simply assigns the value of S1 to S2, member by member.
assigns 3 to rn and 75 to total. In this case actual parameter takes the priority over default parameter. All default values should be on the right side. Consider the following statement A (int = 0) ; It has only one argument. It can be called in two ways. AB; AB(5); In the first statement, no parameter is supplied. In the second statement, one parameter is supplied. When no parameter is supplied, it becomes a default constructor. When both the forms are used in a class (default constructor and constructor with one default argument), it causes ambiguity for a statement such as AB (whether to call A ( ) or A ( int = 0 )
13.6 Destructor
It is used to destroy the objects that have been created by a constructor. The destructor is a member function whose name is the same as the class name but is preceded by a tilde. For example the destructor of the class student can be defined as - student ( ) ; It never takes any argument nor does it return any value. It will be invoked by the compiler upon exit from the program ( or function or block) to clean the storage. It is a good practice to declare destructor in a program because it releases memory space for future use.
4.
A constructor is executed automatically when the object is created True or False? What is a destructor? Fill in the blanks: (a) (b) (c) (d) A constructor name is the same as ....................... A constructor is executed automatically when an object is .................... Destructor is executed ............................. at the end of the program A class can have any number of constructors but only ........................... destructor at a time The name of the destructor function is same as that of class but proceed with a symbol............................... The constructor which accepts value from outside is called .............................. constructor.
5. 6.
(e)
(f)
7.
State whether the following are true or False. (a) (b) (c) (d) (e) (f) A constructor name is not the same as class name. In a class, you can have more than one constructor with the same name. Constructor does not return any value. A constructor that accepts no parameter is known as default constructor. Destructor never takes any arguments. Destructor is called automatically at the end of compound statement, function or main program. Constructor initialize the data members of a class.
(g)
4.
Calculate ( ) function computes the salary and returns it. Salary is sum of Basic, DA and HRA Public members : Readdata ( ) function accepts the data values and invokes the calculate function. Displaydata ( ) function prints the data on the screen. 5. Define a class worker with the following specifications : Private members of class worker wno wname hrwk, wgrate totwage calcwg ( ) integer 25 characters float (hour worked and wage rate per hour) float (hrwk * wgrate ) A function to find hrwk * wgrate with float return type. Public members of class workder
In_data ( )
a function to accept values for wno, wname, hrwk, wgrate and invoke calcwg ( ) to calculate netpay.
Out_data ( ) 6. 7. 8. 9.
What are the special properties of a constructor function? What is parameterized constructor? What is copy constructor ? What is the importance of destructors ?
6.
7.
8.
a) b) c) d)
F T T T
2. 3. 4. 5.
6.
14.1 Introduction
This lesson discusses about inheritance, the capability of one class to inherit properties from another class as a child inherits some properties from his/her parents. The most important advantage of inheritance is code reusability. Once a base class is written and debugged, it can be used in various situations without having to redefine it or rewrite it. Reusing existing code saves time, money and efforts of writing the code again. Without redefining the old class, you can add new properties to desired class and redefine an inherited class member function.
14.2 Objectives
After going through this lesson, you would be able to explain the concept of inheritance describe the five forms of inheritance define three types of inheritance explain all three visibility modes describe the concept of abstract class & virtual class
(ii)
(iii)
B (ii) Multiple inheritance > A derived class with several base classes is called multiple inheritance.
C (iii) Multilevel inheritance > The mechanism of deriving a class from another derived class is called multilevel inheritance.
(iv)
Hierarchical inheritance > One class may be inherited by more than one classes. This process is known as hierarchical inheritance.
(v)
When we say that members of a class are inheritable, it means that the derived class can access them directly. However, the derived class has access privilege only to the non-private members of the base class. Although the private members of the base class cannot be accessed directly, yet the objects of derived class are able to access them through the non-private inherited members.
(ii)
(iii)
Base class Access specifier public private public public Not inherited protected The Public Visibility mode protected
Derived class private private Not inherited protected protected protected Not inherited Protected
The following example and figure illustrate the public derivation in classes. class student { private : int x; void getdata ( ); public: int y; void putdata ( ); protected: int z; void check ( ); }; class marks : public student { private : int a ; void readdata ( ); public : int b; void writedata ( ); protected :
int c; void checkvalue ( ); }; class student Private section x getdata ( ) class marks private section a readdata ( )
Inherited from base class student Fig. 14.1 public derivation of a class The public derivation does not change the access specifiers for inherited members in the derived class. The private data of base class student cannot be inherited. The Private Visibility Mode We are using the same example, but the derivation is done in private mode. Class student { // same as in previous example
}; class marks : private student { // }; The following figure illustrates the private derivation in the classes. class student private section x getdata ( ) class marks private section a y z public section y putdata ( ) readdata ( ) putdata ( ) check ( )
Inherited from class student Fig 14.2 Private derivation of a class As it is clear from the figure that the data present in public and protected section of base class become the private members of derived class. The data in private section of base class cannot be inherited. The Protected visibility mode We are using the same example but the derivation is done in protected mode. class student {
// same as in previous example }; class marks : protected student { }; The following figure illustrates the protected derivation in the classes. class student private section x getdata ( ) class marks private section a readdata ( )
Inherited from class student Fig. 14.3 Protected derivation of a class The data present in private section of base class cannot be inherited. The difference between private and protected section is that data present in protected section can be inherited. Otherwise both the section cannot be accessed by the object of the class.
concept in program development and provides a base upon which other classes may be built. In the previous example, the class student is an abstract class since it was not used to create any object.
fees
academics
child
Fig. 14.4 The child has two direct base classes fees and academics which themselves have a common base class school. The child inherits the traits of school via two separate paths. It can also inherit directly as shown by the broken line. The school is sometimes referred to as indirect base class. All the public and protected members of school are inherited into child twice, first via fees and again via academics. This means, child would have duplicate sets of the members inherited from school. This introduces ambiguity and should be avoided. The duplication of inherited members due to these multiple paths can be avoided by making the common base class as virtual class by declaring the base class as shown below : class school { }; class fees : virtual public school { }; -----------------------------------------------------------
class academics : public virtual school { }; class child : public fees, public academics { / / only one copy of school will be inherited. }; Note : you can write either virtual public or public virtual. --------------------------------------
(c) (d)
8.
State whether the following are True or False. (a) (b) Inheritance means child receiving certain traits from parents. The default base class is visible as public mode in derived class.
When a derived class is derived from more than one base class then the inheritance is called hierarchical inheritance. The base class is called abstract class Private data of base class can be inherited
Consider the following class declaration and answer the questions given below: class zoo { char location [20]; protected; int no_of_animals; public; void inputdata (char, int); vod outputdata ( ); }; class animal : protected zoo { int tail; protected; int legs; public: void readdata (int, int) ; void writedata ( ); }; class carnivorous : private animal { int paw_size; public : void fetchdata (int); void displayed ( ) ; }; (a) (b) Name the base class and derived class of the class animal. Name the data member(s) that can be accessed from function displayed ( ).
(c)
Name the data member(s) that can be accessed by an object of carnivorous class. Is the member function outputdata accessible to the objects of animal class ?
(d)
}; class bus : private heavy_vehicle { char make [20]; public : void fetchdata (int); void displaydata ( ) ; }; (i) (ii) Name the base class and derived class of the class heavy_vehicle. Name the data member(s) that can be accessed from function displaydata. Name the data member(s) that can be accessed by an object of bus class? Is the member function outputdata accessible to the objects of heavy_vehicle class?
(iii)
(iv)
2.
5. 6. 7.
The data in protected section can be inherited. The base class is called an abstract class. (a) (b) (c) (d) Abstract class public, private, protected private multiple T F F T F base class - zoo derived class - carnivorous (b) (c) (d) legs, no-o-animals, paw_size None No
8.
9.
(a)
15 Pointer
15.1 Introduction
In C++, the programming with pointers is more powerful and it is used extensively. It saves the processing time. Pointer is a variable which holds the address of another variable. So, programming is concerned with the address, not with the direct value stored.
15.2 Objectives
After going through this lesson, you would be able to: use pointers in arrays define pointer variables in a structure and access data members through pointer define pointer objects in a class and access members through pointer
15.3 Pointer
A pointer is a variable that represents the location (rather than the value ) of a data item such as a variable or an array element. Pointers are used frequently in C++, as they have a number of useful applications. Consider the following example: # include < iostream.h > void main ( ) {
Pointer :: 147
int A = 5; cout << & A; int *ptr; ptr = & A; cout < < *ptr; } If variable A in the above example has a value 5, then & A holds the address of memory cell A. The variable which holds the address is called pointer variable. int *ptr means that a variable ptr is a pointer to a memory cell which can hold the int data type. *ptr is used for the value stored in a memory cell pointed to by the pointer ptr. It is called de-referencing the pointer. The output of the above program is the address of memory cell A and value 5. void *ptr; Here ptr can point to any data type.
The above program can be written as pointer notation. # include < iostream.h > void main ( ) { int A [5] = { 20, 35, 25, 22, 27 } for (int i = 0; i < 5; i + + ) cout << \n << *(A + i); } At one stage the value of i is 2. Therefore A + i is 2, i.e., two locations from the zero location. The *(A+i) will print the data stored at that location.
Pointer :: 149
int rn; }; The statement student st; declares st as the variable of the structure student. The statement student *ptr; declares a pointer variable ptr to a student. That data members using ptr can be referred to as ptr -> name; ptr -> rn; Another way of referring the data member is (*ptr) . name; (*ptr) . rn;
cin >> name; cin >> rn; cin >> marks; } void student : : putdata ( ) { cout << Name << << name << \n; cout << Roll no << rn << \n; cout << Marks << marks << \n; } Declare an object st and pointer ptr as follows: student st; student *ptr; We can refer to the member functions and data member of student in two ways. (i) using dot operator st. marks = 90; st. getdata ( ); (ii) using arrow operator and object pointer ptr -> marks = 90; ptr -> getdata ( ); another way to represent is (*ptr) (*ptr) . marks = 90; (*ptr) . getdata ( );
Pointer :: 151
int rn; public: void getdata ( ) { cin >> this -> rn; } void putdata ( ) { cout << this -> rn; }; void main ( ) { ABC A, B; A . getdata ( ); A . putdata ( ); B . getdata ( ); B . putdata ( ); } When a getdata ( ) or putdata ( ) function is called through object A, this has the address of object A. Similarly, when a getdata ( ) or putdata ( ) function is called through object B, this has the address of object B.
If a pointer ptr points to a variable A, write a statement that represents the content of A but does not use its name. The expression *ptr can be said to
4.
be a pointer to ptr refer to the contents of ptr refer to the value of the variable pointed to by ptr dereference ptr
The expression int* can be said to (i) (ii) (iii) be a pointer pointing to variable int refer to contents of int be a pointer to a int type value.
6.
Fill in the blanks: (a) (b) (c) (d) (e) A pointer variable stores the ............................ of another variable The ....................... operator is called address operator. To declare t_age pointer to integer, we should write ..................... If A is an integer variable than .................... gives its address. If ptr is a pointer to an integer variable, the number stored in it is given by ..............................
7.
State whether the following are True or False. (a) (b) A pointer is a address of the variable. Dereferencing operator (*) is a unary operator. It is different from the multiplication operator (*) which needs two operands. this pointer points to the objects that is currently used to invoke a function.
(c)
Pointer :: 153
2. 3.
What is the difference between arr [4] and *(arr+4)? If a structure defined has pointer variable, how can it access the members of the structure ? Explain if by taking an example. How a data member and member function present in public in class accessed through pointer object? Explain it by taking an example. What is this pointer? Explain briefly?
4.
5.
2. 3. 4. 5. 6.
16 Files
16.1 Introduction
At times it is required to store data on hard disk or floppy disk in some application program. The data is stored in these devices using the concept of file.
16.2 Objectives
After going through this lesson, you would be able to: store data in a file access data record by record from the file move pointer within the file open or close file
16.3 File
A file is a collection of logically related records. A program usually requires two types of data communication. (i) Writing data on the datafile: The data flows from keyboard to memory and from memory to storage device.
Files :: 155
keyboard > memory > hard disk/floppydisk This is called output stream where stream is the flow of data and requires an ofstream.h header file. (ii) Reading data from datafile:
The data flows from storage device to memory and from memory to output device, particularly monitor. datafile > memory > output device (screen) external storage device (hard disk/floppy) This is called input stream and requires ifstream.h header file. If both input stream and output stream are used in the same program then header file fstream.h is required. If header file fstream.h is included in the program, there is no need to include iostream.h explicitly.
Opening a file using constructor function The following statement opens the file STU.DAT in output mode, i.e., for writing data on the file. ofstream outfile (STU.DAT); ofstream is a class available in the compiler file. outfile is any user defined object. The statements
outfile < < TOTAL MARKS << \n; outfile < < total << \n; are used for writing data on the file. The newline character is used for moving the pointer to the next line. Similarly, the following statement ifstream infile (STU.DAT); opens the file STU.DAT in input mode, i.e., for reading purpose The statements infile >> string; infile >> number; read the data from the data file. The following program uses a single file for both writing and reading purposes. First, it takes the data form the keyboard and writes it to the file. After the writing is completed, the file is closed. The program again opens the same file, reads the information already written to it and displays it on the screen. # include < fstream.h > void main ( ) { char name [30]; int rn, marks; ofstream outfile ( INF); cout << Enter student name; cin >> name; cout << Enter student roll number; cin >> rn; cout << Enter student marks; cin >> marks; outfile << name << \n; outfile << rn << \n; outfile << marks << \n; outfile . close ( );
Files :: 157
ifstream infile ( INF ); infile >> name; infile >> rn; infile >> marks; cout << Name << name << \n; cout << Roll no << rn << \n; cout << Marks << marks << \n; infile close ( ); } The output of the program would be: Enter student name Enter student roll number Enter student marks Name Roll No. Marks PARAM 20 90 PARAM 20 90
Opening a file using open ( ) function The function open ( ) can be used to multiple files that use the same stream object. First a stream object is assigned to and then it is used to open the file in turn. filestream_class stream_object; stream_object . open (filename); For example : ofstream outfile; outfile . open (ABC); _____ outfile . close ( ); outfile . open (XYZ); _____ outfile.close ( );
format is: stream_object . open (filename, access mode); The second argument specifies the mode in which the file is opened. The default values are taken for ifstream or ofstream functions. (the mode is not defined explicitly). ios : : in for ifstream functions ios : : out for ofstream functions The file mode parameters can take one or more of the constants defined in the class ios. The following table shows the file mode parameters. Parameter ios : : app Meaning It opens the file in output mode. The file pointer is at the end of file and it can add a record. The file pointer is at the end of the file and it allows to add data or to modify the existing data anywhere in the file. Binary file It opens the file in input mode. The file pointer is at the top of the file and it is ready for reading. If file is already present, it opens the file otherwise open fails. If file is not present, it opens the file otherwise open statement fails. It opens the file in output mode. The file pointer is at the end of the file. If it already has a data, the output mode erases the content of the file. It deletes the contents of the file if exist.
ios :: ate
ios :: nocreate
ios :: noreplace
ios :: out
ios :: trunc
Files :: 159
The mode can combine two or more parameters using bitwise OR opertor. Example: outfile . open (ABC, ios::in l ios::out l ios :: binary);
ios :: cur
ios :: end
means start of the file means current position of the pointer means end of the file
The seekg ( ) and seekp ( ) statement has two parameters. object . seekg (no. of bytes, refposition); object . seekp (no. of bytes, refpostion); The refposition takes one of the above three constants defined in the ios class. Example 1 infile.seekg (0, ios::beg); It moves the pointer to the beginning of the file. In this case, the refposition ios :: beg is optional. infile.seekg ( 100, ios::cur); It moves the pointer 100 bytes forward from the current position.
infile.seekg (-200, ios::end); It moves the pointer 200 bytes backward from the end of the file.
Files :: 161
Example 3 # include <fstream.h> class student { char name [30]; int rn; public: void getdata ( ); void putdata ( ); }; void student : : getdata ( ) { cout <<Enter student name; cin >> name; cout << Enter roll number; cin >> rn; } void student :: putdata ( ) { cout << Student name << name << \n; cout << Student roll number << rn << \n; } void main ( ) { fstream file; file . open ( ABC, ios::in l ios::out l ios::binary); student st; / / create a data file int i, n; cout << How many record to enter; cin >> n; for (i = 1; i < = n, i ++ ) { st. getdata ( );
file . write ((char*) & st, sizeof st); } / / Display a data file file . seekg ( 0, ios::beg); while (file . read ((char*) & st, sizeof st)) { st. putdata ( ); } file . clear ( ) / / To make the end of file mark false / / To append record st . getdata ( ); file . write ((char*) & st, sizeof st); / / To modify a record file.clear ( ); cout << Enter record number; cin >> n; file . seekp ((n - 1)* sizeof st, ios::beg); st. getdata ( ); file.write ((char*) & st, sizeof st); / / To close a file file . close ( ); }
Files :: 163
The file open in ofstream is only available for ........................... The file open in ifstream is only available for .................................. We can open the file using ............................... function. The mode app opens the file for .............................. The file open in output mode is ....................... by default.
State whether the following are True or False. (a) (b) (c) A file is a collection of record. The file open in ofstream is available for writing. The output mode of opening a file deletes the contents, if present in the file. The close ( ) function is used to close a file. The statement outfile.write ((char*) & obj, sizeof obj); writes only data in obj to outfile. (f) (g) (h) The ios::ate mode allow us to write data at the end the file only. We can add data to an existing file by opening in append mode. The data written to a file with write ( ) function can be read with the get ( ) function.
(d) (e)
opening a file with open () function? 3. 4. What is the file access mode? Describe the various file modes. A file consists of 5 records, each takes 100 bytes of storage: fstream file: file. seekg ( 0, ios::end); N = file.tellg ( ); (i) (ii) 5. What will be the datatype of N? What will be the value of N?
Consider the following statements: fstream file; file.open (ABC, ios::in l ios::out); Write C++ statement(s) for the following: (i) (ii) (iii) (iv) To move the pointer at the beginning of file. To move the pointer at the end of file. To find the total number of bytes. To close the file.
6.
Explain the functioning of the following: fstream file; (i) (ii) (iii) file.seekg (100, ios::cur); file.seekg (-100, ios::end); file.seekg ( 100, ios::beg);
7.
The record consists of two fields: name and rollno. Write a program that will perform the following: (i) (ii) (iii) (iv) create a data file of 5 records display a data file append a record modify one of the records
Files :: 165
3. 4. 5. 6.