48 views

Uploaded by Sutirtha Bhaumik

- 6.11.18 css2.docx
- Tcloud Handbuch En
- Mac
- Manual So Touch Air Presenter Plus
- Very Useful Commands for Registry Editor
- Read Me Crane Girder 20041110
- Capabilities
- Essential Windows
- TPSC-SI37461
- Using Your Gmail
- Excel Lessons Intermediate
- (GROUP 7) MATLAB (1)
- Flow sheet Development.docx
- Computer for All
- 35011929 3 en TerraStationUserGuide
- 1.Intro
- CA
- Data Extraction Macro
- A Computer is a Device That Accepts Information
- Windows Hacking Page 2 3

You are on page 1of 160

Paper 4B

SOFTWARE ASSIGNMENT ON SINGLE USER AND MULTIUSER OPERATING SYSTEM AND PROGRAMMING THROUGH C LANGUAGE

ROLL NUMBER: 301241 0121 REGISTRATION No. & SESSION: 030429 of 20082009

-2-

INDEX

Section I:

Familiarity with single user and multi user operating systems: Serial Number

1

Contents

Microsoft DOS (Disk Operating System)

Page

6

Date

16.09.2009.

Teachers Signature

14

23.10.2009.

32

28.10.2009

Section II:

Programming in C Language: Serial Number

1

Contents

Program in which for all integers I,J,K,L from 1 to 10, all combinations of I,J,K,L are printed such that I+J+K=L and I<J<K<L Program which finds the intersection, union, and minus of two sets of integers entered by the user Program to express every even number greater than 4 as the sum of two odd primes

Page

40

Date

30.10.2009.

Teachers Signature

42

04.11.2009.

47

11.11.2009.

51

18.11.2009

-3-

Write a menu driven program to find the value of sin(x), cos(x), e^(x), log(x)

53

20.11.2009.

60

25.11.2009.

63

27.11.2009.

66

04.12.2009.

Program to compute real roots of a non-linear equation by Newton Raphson method Program to find integration using Trapezoidal rule and Simpsons 1/3 rule for a function

71

11.12.2009.

10

74

16.12.2009.

11

77

18.12.2009.

12

Program to print a normal input string vertically where each character in the output string is in uppercase Program to squeeze the blanks (more than one) from a given string

82

23.12.2009.

13

84

06.01.2010.

14

86

08.01.2010.

15

Program to find the minimum spanning tree using Prims algorithm Program to find the shortest distance and shortest path between any vertex to any vertex using Floyds algorithm

88

15.01.2010.

16

92

22.01.2010.

-4-

17

Program to find the shortest distance from one vertex to all vertices in a directed graph by Dijkstras method

96

27.01.2010.

18

101

29.01.2010.

19

Program to simulate different sorting techniques through menu driven program Program to build a binary search tree having characters as content of each node and traverse it in preorder, inorder, and postorder Program to create a general binary tree and traverse it in preorder, inorder, and postorder Program which accepts a string of parentheses and checks whether the string is valid in algebraic sense Program to convert decimal numbers to roman numerals

107

03.02.2010.

20

128

05.02.2010.

21

133

10.02.2010.

22

138

17.02.2010.

23

142

19.02.2010.

24

Program to find the age of people Program that accepts three text files (say f1, f2, f3) as command line arguments and merge lines alternately from two files f1 and f2 and writes the results into the third file f3. Finally print all the three files. Program to print Pascals triangle up to n level

147

24.02.2010.

25

150

05.03.2010.

26

155

10.03.2010.

27

158

12.03.2010.

-5-

Section- I

-6-

ASSIGNMENT No. 1

Date: 16.09.2009.

An Operating System (OS) is the most important system software and is a must to operate a computer system. An OS manages computer resources very effectively, takes care of scheduling multiple jobs for executions and manages the flow of data and instructions between the input/output units and the main memory. Popular OSs are WINDOWS-95/98 , WINDOWS 2000 , WINDOWS NT , UNIX , LINUX , DOS etc. In other words, an OS is a program that acts as an intermediary between the user and the computer.

Introduction:

DOS (an acronym for Disk Operation System) is a tool which allows you to control the operation of the IBM PC. DOS is software which was written to control hardware. IDRISI, Atlas*GIS, Micro station, AutoCAD, CPS/PC, and ARC/INFO are, in turn, application software which run under DOS. By this we mean that, although IDRISI, Atlas*GIS, Micro station, AutoCAD, CPS/PC, and ARC/INFO were written to accomplish a single task or application (in this case manipulation of spatially related data), they must use DOS to pursue its work. DOS can be used for a wide range of tasks far beyond the requirements of this class. You will be able to manage well if you master only a small subset of DOS commands and functions. These relate almost exclusively to file and directory management and are introduced in this handout. This tip sheet assumes that you have learned how to turn on the PCs as they are configured in room 230 and that you have familiarized yourself with their keyboards (no small task in itself). It also assumes that you understand the meaning of the concept of a file and the elements of a file specification (drive, filename, and extension). The microcomputers you will be using are equipped with two floppy disk drives. The A-drive is the 3.5" (1.44MB) drive and the B-drive is the 5.25" (360KB) drive. The microcomputers also contain a C-drive, a hard disk drive of 130MB or 200MB capacity. You will quickly find that the best way to learn how to use a computer is through experimentation. That is, once you have learned a command, try some variations until they don't work, then start over. Often there are five or six ways for you to accomplish a particular task. Usually, I will introduce you to only one, leaving it up to you to discover the rest. Don't hesitate to consult the DOS Reference Manual; copies can be found on the bookcase in room 230. Finally, don't be unduly disturbed by error messages. With computers, one of the best ways to learn is by making mistakes. Most of the common DOS commands you need to use for this class (copy, rename, delete) are available to you in Windows through the Filemanager icon. And, since you can move back and forth between DOS and Windows, it doesn't matter which option you employ. Some commands are faster in invoke in Windows, some in DOS. If you haven't worked with Windows previously, go to the Windows tutorials in the help area.

Booting Sequence:

As soon as P.C is switched on it runs program that is permanently stored in its memory. The program is called Basic Input Output System(BIOS) and it is always there, whether or not you have any disk loaded and even when the power is turned off. Upon startup, BIOS automatically looks for the PCs master computer program, first in the A:\ drive, if a floppy drive is loaded, otherwise in the C:\ drive.

Files are a collection of records. Concept of files is very important in DOS. There are three files in DOS. They are as follows: 1. Data files. 2. Program files. 3. Sub Directory files. Every file name has two parts: 1. File name 2. Extension y File name should not contain more than 8 letters and extension should not contain more than 3 letters. y File name part identifies the particular file and extension identifies the category of files.

Following the boot sector comes the FAT that keeps track of all the disk space on the device to provide reliability, sometimes the FAT is replicated. The FAT contains one entry for each block on the disk. The block size is given in the boot sector and can range from 1-8 sectors. The size of the FAT entry is 16 bits. The free blocks are marked by another code in the FAT. A directory in DOS has a 32-bit entry for each file name and directory it contains. The first 11(8+3) characters hold the file name and extension. Next comes the attribute byte containing the following bits. A Archive bit (set when the file is modified, cleared when it is backed up). D set to indicate that the entry is for a directory. V set to indicate that the entry is for volume label. S set for system (undeletable file). IO.SYS MS-DOS.SYS ALL.SYS files. H set for hidden files. R read only bit. The time and date of the last modification are stored in the next two fields. 4bits hours. 6bits minutes. 6bits seconds. 7bits years. 4bits months. 5bits days. The last two fields hold the number of the first block and the file size. File Extension Name A D V S H R Future Time use Date 1st File block size

-8-

A command is defined as something that is typed in a line on the screen of the DOS prompt. The command may consist of single word or more. There are three types of commands. They are as follows: 1. Internal commands. 2. External commands. Internal Commands: A handful of the smallest and the most useful commands are a resident part of DOS. These are called the internal commands. External Commands: All other command programs in DOS are called external commands, and they are kept stored in the disk until they are needed. Now the important DOS commands are given below.

To modify and see the date and time, we use the following command. C:\>date The current date is: Thu 07/14/2005 Enter the new date: (mm-dd-yy) C:\>time The current time is: 15:02:24.24 Enter the new time:

To display the volume label on a disk, we use the following command. C:\>vol Volume in drive C is WINDOWS 98 Volume serial number is 0448-16FF

To display the MS-DOS version we use the ver command. C:\>ver Windows 98 [version 4.10.2222]

Version of MS DOS

Clear Screen

The cls command clears the screen. C:\>cls

Backup Files

It is possible to lose files by mistake, although the more you practice the less likely it becomes. For your own peace of mind, it is good practice to make backup copies of your most valuable files on a separate diskette. Store your backup disk in a safe place and don't carry it through a metal detector. Use the COPY command to create the backup. There is no need to backup every file you create, only the ones in which you've invested much work. Also, prune your backup diskette every week or two using the ERASE command. Backup files which have been made redundant by subsequent additions will simply create clutter on your backup diskette. An effective file naming convention is essential to keeping track of your backups.

-9-

To change the default drive, simply type the letter of the your choice. The new default will be listed in subsequent DOS prompts. Example:

y y y y

C:\> A: Changes the default drive from C to A. A:\> C: Changes the default drive from A to C.

[enter] means that you must press the Enter Key before the format command will execute. [Enter] is required after any DOS command, it is assumed in all commands found below.

Once you have located the directory you want, you may move from directory to directory using the CD command (change directory) Example:

y y y y y y y y

C:\> cd furniture Moves you to the directory called 'FURNITURE' C\:> cd \furniture\chairs Moves you to the directory called 'CHAIRS' under the directory called 'FURNITURE'. C:\> cd.. Moves you up one level in the path. C:\> cd\ Takes you back to the root directory (c: in this case).

COPY Command

The COPY command can be used both to copy files from disk to disk or to create a second copy of a file on a single disk. (There are many more uses of the COPY command, but only the basic operation is discussed here.) Example:

y y y y

C:\> copy c:kermit.exe a: Copies the file 'KERMIT.EXE' from the C drive to the A drive and gives it the same name. C:\> copy a:brazil1.dat b:\south\brazil2.dat Creates a copy of 'BRAZIL1.DAT' from drive A on drive B, putting it in the 'SOUTH' subdirectory and renaming it 'BRAZIL2.DAT'.

The key to use this command correctly is to remember that the first file specified after the COPY command is the source file, the second is the target:ehp1 file. The source is the file to be copied. The target will be the location and name of the new file. If the file name and extension are omitted after the target's drive specification, the new file will have exactly the same name as the source file. Example:

y y

- 10 y y y

C:\> copy b:golly.gee a:whao.boy C:\> copy command.* a: C:\> copy a:mymap.dwg c:\maps

Note: it is always good practice to us the complete file specifications for both source and target files, Be very sure of yourself before you accept defaults or employ wild-card characters. Otherwise you may end up with some interesting results. Incomplete or incorrect source names may result in errors, such as the command: copy edlin a:myomy.bat. Try it and see what happens.

The DIRECTORY command lists the names and sizes of all files located on a particular disk. Example:

y y y y y y y y y y

C:\> dir a: Shows directory of drive A C:\> dir b: Shows directory of drive B C:\> dir \windows Shows files in a subdirectory on drive C (default) C:\> dir Shows directory of drive C C:\> dir /w Shows directory in wide format, as opposed to a vertical listing.

All the files are listed at the screen, you can stop the display by typing CTRL-BREAK. If you ask for a directory on the A or B drives, be sure there is a diskette in the drive and that the diskette has been formatted. If the drive is empty, or if the diskette is unformatted, the DOS will respond with an error message.

DIR Options

Two little characters, '*' and '?', will make your life with computers much easier. Their use is illustrated below. Example:

y y y y

C:\> dir a:*.ex Lists all files on the A drive with an extension of 'EXE'. C:\> dir b:kermit.* Lists all files on the B drive with a filename of 'KERMIT'.

The asterisk is a wild-card character which allows the user to enter only a limited part of a file specification to find a file. It is useful when you wish to locate a group of files with the same filename or the same extension. On other occasions you may have forgotten part of a file specification. You can use '*' in place of the parts of the specification you have forgotten. Similarly, '?' permits wild-card searches keyed to single characters. Example:

y y y y

C:\> dir a:labe?.com Lists all five-letter files with the first four letters 'LABE' and an extension of 'COM'. C:\> dir b:format.c?? Lists all files with a filename of 'FORMAT' and an extension beginning with 'C'.

y y y y

C:\> dir a:labe?.* Lists all five-letter files with the first four letters 'LABE' and any extension. C:\> dir c:*.ex? Lists all files with an extension beginning with 'EX'.

Experiment with '*' and '?' to improve your ability to find files quickly. These wild-card characters can also be used with several other DOS commands.

TYPE Command

This command is used to display the contents of the file with the extension name on the screen. C:\>type filename Ex: C:\>type scott.doc I am a student of Asutosh College.

ERASE Command

The ERASE command deletes specified files. Example:

y y

C:\> erase a:myfile.txt Erases the file MYFILE.TXT from the diskette in the A drive. If no drive specification is entered, the system looks to delete the specified file form drive C (in this case).

IMPORTANT WARNING: This command is easy to use, but it is the most dangerous one you will encounter in DOS (apart from FORMAT). If you aren't careful, you may delete a file which you--or someone else--needs. And, unless you have saved a backup of that file, the erased file is gone for good. For this reason it is good practice to use only complete file specifications with the ERASE command (and to keep backups of your most valuable files). As a safety precaution, never use the wild-card characters '*' and '?' in ERASE commands. BEWARE: I will rescind your laboratory privileges for a full week if you ever knowingly use either the command: erase c:*.*, or the command: erase *.*. Guess what happens?

File-Naming Conventions

Careful file naming can save time. Always choose names which provide a clue to the file's contents. If you are working with a series of related files, use a number somewhere in the name to indicate which version you have created. This applies only to the filename parameter; most of the file extension parameters you will be using are predetermined (or reserved by DOS for certain types of file). Example:

y y

WORLD.DAT An ATLAS*GRAPHICS file containing data for a world map. The DAT extension is required by ATLAS*GRAPHICS.

- 12 y y y y y y

BRAZIL.BNB A boundary file of Brazil in binary form. BRIT1.DAT BRIT2.DAT BRIT3.DAT Three versions of a data file for a map of Britain.

FORMAT Command

You must format new disks before using them on the IBM computers. The format command checks a diskette for flaws and creates a directory where all the names of the diskette's files will be stored. Example:

y y y

After entering this command, follow the instructions on the screen. When the FORMAT operation is complete, the system will ask if you wish to FORMAT more diskettes. If you are working with only one diskette, answer N (No) and carry on with you work. If you wish to FORMAT several diskettes, answer Y (Yes) until you have finished formatting all your diskettes. BEWARE: Executing the format command with a diskette which already contains files will result in the deletion of all the contents of the entire disk. It is best to execute the format command only on new diskettes. If you format an old diskette make sure it contains nothing you wish to save.

This command creates a new directory. Example:

y y

In some cases, when all attempts to recover from a barrage of error messages fails, as a last resort you can reboot the computer. To do this, you press, all at once, the control, alternate and delete. BEWARE: If you re-boot, you may lose some of your work--any data active in RAM which has not yet been saved to disk.

The RENAME command permits users to change the name of a file without making a copy of it. Example:

y y

C:\> ren a:goofy.txt pluto.txt Changes the name of 'GOOFY.TXT' on the A drive to 'PLUTO.TXT'.

- 13 This command is very simple to use, just remember two points: the file name and extension must be complete for the source file and no drive specification is given for the target. Renaming can only occur on a single disk drive (otherwise COPY must be used).

This command removes a directory. It is only possible to execute this command if the directory you wish to remove is empty. Example:

y y

If you wish to stop the computer in the midst of executing the current command, you may use the key sequence Ctrl-Break. Ctrl-Break does not always work with non-DOS commands. Some software packages block its action in certain situations, but it is worth trying before you re-boot.

Tree Command

TREE command displays the list of all the branches of the directory tree for any disk. Example: C:\>md a C:\>cd a C:\a>md pqr C:\a>md xyz C:\a>cd pqr C:\a\pqr>md p C:\a\pqr>md q C:\a\pqr>md r C:\a\pqr>cd.. C:\a>cd xyz C:\a\xyz>md x C:\a\xyz>md y C:\a\xyz>md z C:\a\xyz>cd.. C:\a>tree Folder PATH listing Volume serial number is 71FAE346 38A6:8127 C:. pqr | p | | q | r xyz x y z

- 14 -

ASSIGNMENT No. 2

Date: 23.10.2009.

MICROSOFT WINDOWS

Introduction: The Microsoft windows operating system is a 32 bit primitive multitasking operating system for Intel Pentium and later microprocessors. Key goals for the system are portability, security, Portable Operating System interface (POSIX), compliance, microprocessor support and compatibility with MS-DOS and Microsoft windows applications. Windows uses micro kernel architecture, so enhancements can be made to one port of the operating system without greatly affecting other parts. What is Windows? Microsoft Windows is a software program that makes the PC easy to use. It does this simplifying the computer user interface a buzzword that refers to the way the computer is given command, the way it is interacted with. Usually the interface between the user and the computer consists on the screen and the keyboard; the user interact with the computer by responding to what is on the screen, typing in cryptic command at the DOS command line to the work. DOS often is not very intelligent at interpreting your commands and most people consider it awkward or intimidating is a user interface. These commands can be confusing and difficult to remember. What has been missing from the PC is a program and WINDOWS is such a program. With Windows, program can be opened, entered and moved, that was stored and performed in DOS, just with the help of a mouse and a keyboard. Windows owes its name due to the fact it runs each program on a separate window of its own. Many windows can be opened on the screen. The user has to shift from program to program just by switching over to different windows. There is no need of closing any program. Windows has a facility called the clipboard that led the user to copy any type of data from any program to another. All application programs that runs on windows has similar features.

Hardware Requirements:

To run Microsoft Windows 3.1 the following hardware are required: y A PC, with DOS ver 3.1 and hard-disk having a minimum of 9MB free space. y A mouse. y 1 MB of memory. y A monochrome graphics monitor or colour monitor.

Design Principles: The design goals that Microsoft has stated for Windows includes :-y Extensibility: It refers to the capacity of the operating system to keep up with advances in computing technology. y Portability: An operating system is portable if it can be moved from one hard-ware architecture to another with relatively few changes.

- 15 y

Reliability: It is the ability to handle error, including the ability of the operating system to protect itself and its users from defective or malicious software compatibility. Compatibility: Windows provides source-level compatibility to applications that follow the POSIX standard. Thus they can be compiled to run on Windows without changes to the source code. Performance: Windows is designed to afford good performance. The subsystems that constitute windows can communicate with one another efficiently by a localprocedure-call facility that provides high performance message passing.

Basics of Microsoft Windows: A window is a rectangular portion on the screen in which an application or a program displays information. Most Windows have certain elements in common. They are as follows: y Title bar displays name of the application or document. y On the extreme left of every title bar there is an icon called system control icon. y The menu bar lists the available menus. y Scroll bars are used for viewing unseen portion of list and other information that cannot fit in the allocated space. y Most windows have a maximize, minimize and a close button. These buttons are used for resizing and closing windows. Application Icon: It represents an application that is running. You can move an icon anywhere on the desktop by clicking on the left mouse and dragging it. You cannot move the icon inside a document or another application. Program Item Icon: This represents the applications which can be started from windows. They are usually unique and are contained in the program managers group windows. The rectangular bar that runs horizontally across the bottom of your screen is called task bar. It includes Start button, current time, and when you start working you will see other items listed on the task bar. This item shows you the name of the windows currently open on your desktop. You can easily switch to different windows by clicking on its taskbar button. Elements of the Desktop: The desktop has a number of application program or some files or folder on it. Some of which are as follows: y My computer. y Recycle Bin. y My Documents. y Task bar. y Start Menu. y Shortcuts. My Computer: My Computer is used to view the contents of a single folder or drive. Double click my computer on your desktop to display the drives available on your computer. When you

- 16 double click a drive icon, a window displays the folders on that drive. There shall be folders for Control Panel, Printers and Dial up networking. Double click a folder to see the files within the folders. Recycle Bin: Recycle Bin is a application program which contain all the deleted files and folders. So if something is deleted by mistake, it can be restored from Recycle Bin using the restore option and to completely delete the folder we select the delete option available. To empty Recycle Bin, right click on the Recycle Bin folder on the desktop and select the Empty Recycle Bin option by clicking on it or enter the Recycle Bin folder on the desktop and choose the Empty Recycle Bin option available on the right hand side. My Documents: My document is a desktop folder that provides a user with a convenient place to store documents, graphics or other files which a user might want to access quickly. On the desktop, a folder with a sheet of paper on it represents it. When a user saves a file in a program such as MS Word, MS Excel, WordPad, Paint etc. the file is automatically saved in My Documents unless a user select some other location. Using the Control Panel: The control panels customize your windows environment. The control Panel is a windows consisting of collection of utilities to set your screen colour, modify the appearance of your desktop, change date and time. The control panel helps in the following :-y Setting date and time. y Display . y Changing pattern. y Loading new wallpaper. y Loading screen saver. To start window explorer:

y Click the start button on taskbar. y Click the program and select window explorer. The left pane of the window explorer screen shows the directory structure while the right pane shows the directories and files in the directory selected.

Creating a new Folder on the Desktop: To create new folders follow the following steps: y Click the right mouse button anywhere is an empty area on the desktop, a menu appears. y Select NEW from the menu. y Click on the folder option. y A new folder appears on the desktop having its name as New Folder. Creating a new File on the Desktop:

y y

Open the Windows Explorer window. Open the folder in which the file is to be created.

- 17 y y

Open the file menu and choose NEW option from the menu. Select the type of file and give name to the file.

y y

Select the file or folder you wish to copy. Choose the option copy from the context menu, click on it and paste on the target location again by choosing the paste option from the context menu.

y y

Select the file or folder you wish to delete. Select the delete option from context menu and click on it.

y y y

Select the file or folder you wish to rename. Select the rename option from context menu and click on it. Type the new name in the text box and press enter.

y y y y y

Double click on the display icon a dialog appears. Click down arrow on the side of the colours schemes box. Select one of the schemes from the list. The screen colours in the sample screen are set to the colours used in the schemes selected. Click OK at the bottom of dialog box.

- 18 -

MICROSOFT WORD

Question 1: Create a document in MS WORD containing several paragraphs. a) Copy the first paragraph of the document in a new page. b) For all the paragraphs change the line spacing to double and spacin g after a paragraph to 6 points Answer: A computer is a machine for manipulating data according to a list of instructions. Computers take many physical forms. Early electronic computers were the size of a large room, consuming as much power as several hundred modern personal computers.[1] Today, computers can be made small enough to fit into a wrist watch and be powered from a watch battery. Society has come to recognize personal computers and their portable equivalent, the laptop computer, as icons of the information age; they are what most people think of as "a computer". However, the most common form of computer in use today is by far the embedded computer. Embedded computers are small, simple devices that are often used to control other devicesfor example, they may be found in machines ranging from fighter aircraft to industrial robots, digital cameras, and even children's toys. The ability to store and execute programs makes computers extremely versatile and distinguishes them from calculators. The ChurchTuring thesis is a mathematical statement of this versatility: Any computer with a certain minimum capability is, in principle, capable of performing the same tasks that any other computer can perform. Therefore, computers with capability and complexity ranging from that of a personal digital assistant to a supercomputer are all able to perform the same computational tasks as long as time and storage capacity are not considerations. It is difficult to define any one device as the earliest computer. The very definition of a computer has changed and it is therefore impossible to identify the first computer. Many devices once called "computers" would no longer qualify as such by today's standards. Originally, the term "computer" referred to a person who performed numerical calculations (a human computer), often with the aid of a mechanical calculating device. Examples of early mechanical computing devices included the abacus, the slide rule and arguably the astrolabe and the Antikythera mechanism (which dates from about 150-100 BC). The end of the Middle Ages saw a re-invigoration of European mathematics and engineering, and Wilhelm Schickard's 1623 device was the first of a number of mechanical calculators constructed by European engineers. However, none of those devices fit the modern definition of a computer because they could not be programmed. In 1801, Joseph Marie Jacquard made an improvement to the textile loom that used a series of punched paper cards as a template to allow his loom to weave intricate patterns automatically. The resulting Jacquard loom was an important step in the development of computers because the use of punched cards to define woven patterns can be viewed as an early, albeit limited, form of programmability. In 1837, Charles Babbage was the first to conceptualize and design a fully programmable mechanical computer that he called "The Analytical Engine".[2] Due to limited finance, and an inability to resist tinkering with the design, Babbage never actually built his Analytical Engine.

- 19 -

Answer a) A computer is a machine for manipulating data according to a list of instructions. Computers take many physical forms. Early electronic computers were the size of a large room, consuming as much power as several hundred modern personal computers.[1] Today, computers can be made small enough to fit into a wrist watch and be powered from a watch battery. Society has come to recognize personal computers and their portable equivalent, the laptop computer, as icons of the information age; they are what most people think of as "a computer". However, the most common form of computer in use today is by far the embedded computer. Embedded computers are small, simple devices that are often used to control other devicesfor example, they may be found in machines ranging from fighter aircraft to industrial robots, digital cameras, and even children's toys. Answer b) A computer is a machine for manipulating data according to a list of instructions. Computers take many physical forms. Early electronic computers were the size of a large room, consuming as much power as several hundred modern personal computers.[1] Today, computers can be made small enough to fit into a wrist watch and be powered from a watch battery. Society has come to recognize personal computers and their portable equivalent, the laptop computer, as icons of the information age; they are what most people think of as "a computer". However, the most common form of computer in use today is by far the embedded computer. Embedded computers are small, simple devices that are often used to control other devicesfor example, they may be found in machines ranging from fighter aircraft to industrial robots, digital cameras, and even children's toys. The ability to store and execute programs makes computers extremely versatile and distinguishes them from calculators. The ChurchTuring thesis is a mathematical statement of this versatility: Any computer with a certain minimum capability is, in principle, capable of performing the same tasks that any other computer can perform. Therefore, computers with capability and complexity ranging from that of a personal digital assistant to a supercomputer are all able to perform the same computational tasks as long as time and storage capacity are not considerations.

- 20 It is difficult to define any one device as the earliest computer. The very definition of a computer has changed and it is therefore impossible to identify the first computer. Many devices once called "computers" would no longer qualify as such by today's standards. Originally, the term "computer" referred to a person who performed numerical calculations (a human computer), often with the aid of a mechanical calculating device. Examples of early mechanical computing devices included the abacus, the slide rule and arguably the astrolabe and the Antikythera mechanism (which dates from about 150-100 BC). The end of the Middle Ages saw a re-invigoration of European mathematics and engineering, and Wilhelm Schickard's 1623 device was the first of a number of mechanical calculators constructed by European engineers. However, none of those devices fit the modern definition of a computer because they could not be programmed. In 1801, Joseph Marie Jacquard made an improvement to the textile loom that used a series of punched paper cards as a template to allow his loom to weave intricate patterns automatically. The resulting Jacquard loom was an important step in the development of computers because the use of punched cards to define woven patterns can be viewed as an early, albeit limited, form of programmability. In 1837, Charles Babbage was the first to conceptualize and design a fully programmable mechanical computer that he called "The Analytical Engine".[2] Due to limited finance, and an inability to resist tinkering with the design, Babbage never actually built his Analytical Engine. Question 2: a) Write a word document of 10 sentences. b) Make font of the heading center aligned Lucida Handwriting of size 1 4. c) Make the rest of the text justified. d) Make size and font of the rest of the text 11 and Courier New respectively. e) Display the text in two columns.

- 21 Answer a)

Computer

A computer is a machine for manipulating data according to a list of instructions. Computers take many physical forms. Early electronic computers were the size of a large room, consuming as much power as several hundred modern personal computers. Today, computers can be made small enough to fit into a wrist watch and be powered from a watch battery. Society has come to recognize personal computers and their portable equivalent, the laptop computer, as icons of the information age; they are what most people think of as "a computer". However, the most common form of computer in use today is by far the embedded computer. Embedded computers are small, simple devices that are often used to control other devicesfor example; they may be found in machines ranging from fighter aircraft to industrial robots, digital cameras, and even children's toys. The ability to store and execute programs makes computers extremely versatile and distinguishes them from calculators. The ChurchTuring thesis is a mathematical statement of this versatility: Any computer with a certain minimum capability is, in principle, capable of performing the same tasks that any other computer can perform. Therefore, computers with capability and complexity ranging from that of a personal digital assistant to a supercomputer are all able to perform the same computational tasks as long as time and storage capacity are not considerations. Answer b and c) A computer is a machine for manipulating data according to a list of instructions. Computers take many physical forms. Early electronic computers were the size of a large room, consuming as much power as several hundred modern personal computers.Today, computers can be made small enough to fit into a wrist watch and be powered from a watch battery. Society has come to recognize personal computers and their portable equivalent, the laptop computer, as icons of the information age; they are what most people think of as "a computer". However, the most common form of computer in use today is by far the embedded computer. Embedded computers are small, simple devices that are often used to control other devicesfor example, they may be found in machines ranging from fighter aircraft to industrial robots, digital cameras, and even children's toys. The ability to store and execute programs makes computers extremely versatile and distinguishes them from calculators. The ChurchTuring thesis is a mathematical statement of this versatility: Any computer with a certain minimum capability is, in principle, capable of performing the same tasks that any other computer can perform. Therefore, computers with capability and complexity ranging from that of a personal digital assistant to a supercomputer are all able to perform the same computational tasks as long as time and storage capacity are not considerations.

Computer

Answer d)

Computer

22

A computer is a machine for manipulating data according to a list of instructions. Computers take many physical forms. Early electronic computers were the size of a large room, consuming as much power as several hundred modern personal computers. Today, computers can be made small enough to fit into a wrist watch and be powered from a watch battery. Society has come to recognize personal computers and their portable equivalent, the laptop computer, as icons of the information age; they are what most people think of as "a computer". However, the most common form of computer in use today is by far the embedded computer. Embedded computers ar e small, simple devices that are often used to control other devices for example, they may be found in machines ranging from fighter aircraft to industrial robots, digital cameras, and even children's toys. The ability to store and execute programs makes computers extremely versatile and distinguishes them from calculators. The Church Turing thesis is a mathematical statement of this versatility: Any computer with a certain minimum capability is, in principle, capable of performing the same tasks that any other computer can perform. Therefore, computers with capability and complexity ranging from that of a personal digital assistant to a supercomputer are all able to perform the same computational tasks as long as time and storage capacity are not considerations.

Answer e)

Computer

A computer is a machine for manipulating data according to a list of instructions. Computers take many physical forms. Early electronic computers were the size of a large room, consuming as much power as several hundred modern personal computers. Today, computers can be made small enough to fit into a wrist watch and be powered from a watch battery. Society has come to recognize personal computers and their portable equivalent, the laptop computer, as i cons of the information age; they are what most people think of as "a computer". However, the most common form of computer in use today is by far the embedded computer. Embedded computers are small, simple devices that are often used to control other devic esfor example; they may be found in machines ranging from fighter aircraft to industrial robots, digital cameras, and even children's toys. The ability to store and execute programs makes computers extremely versatile and distinguishes them from calculators. The ChurchTuring thesis is a mathematical statement of this versatility: Any computer with a certain minimum capability is, in principle, capable of performing the same tasks that any other computer can perform. Therefore, computers with capability and complexity ranging from that of a personal digital assistant to a supercomputer are all able to perform the same computational tasks as long as time and storage capacity are not considerations.

23

MICROSOFT EXCEL

Introduction to Microsoft Excel:

Excel is an electronic spreadsheet. An electronic spreadsheet is a software program that organizes data in cells. The data stored in different cells automatically updated in case of any changes are made to the related cells. For example, we can store the marks of 40 students and their total in a spreadsheet. If the marks stored in any of the cells are changed, the total value will automatically be updated by the spreadsheet. This feature of spreadsheet makes it very easy to maintain large business data sheets with complex calculations. Except MS-Excel some other electronic spreadsheet products are: VisiCalc, Lotus 1-2-3 etc. Excel was originally written for the Apple Macintosh System in 1984-85. It was the first spreadsheet to use a graphical interface with pull down menus and a point and click capability using a mouse. The Excel spreadsheet with a graphical user interface was easier for most people to use than the command line interface of PC-DOS spreadsheet products. When Microsoft launched Windows OS, Excel was one of the first application released for it. When Windows gained wide acceptance with version 3.0 in late 1989 Excel was Microsofts main product. It includes three components worksheets, graph and database management. The calculations are done with more edge in worksheet. If any information is changed the worksheet the program automatically recalculate or rearrange the data. The worksheet program can also display the result in the form of different graphs.

Uses of MS-Excel:

y y y y y

MS Excel can be used in some of the following areas :-Budgets Payrolls Inventory controls Scientific calculations Cost effective analysis

Features of MS Excel:

1. 2. 3. 4. Manipulating data. The results are accurate. Graphs. Information entered can be viewed in a different format.

A spreadsheet is a rectangular table (or grid) of information, often financial information. The word came from "spread" in its sense of a newspaper or magazine item (text and/or graphics) that covers two facing pages, extending across the center fold and treating the two pages as one large one. The compound word "spread-sheet" came to mean the format used to present bookkeeping ledgers with columns for categories of expenditures across the top, invoices listed down the left margin, and the amount of each payment in the cell where its row and column intersectwhich were traditionally a "spread" across facing pages of a bound ledger (book for keeping accounting records) or on oversized sheets of paper ruled into rows and columns in that format and approximately twice as wide as ordinary paper. So let's get started digging into what makes a spreadsheet work. Spreadsheets are made up of

y y y

24

y y y

text (labels) number data (constants) formulas (mathematical equations that do all the work).

Constants are entries that have a specific fixed value. If someone asks you how old you are, you would answer with a specific answer. Sure, other people will have different answers. Formulas are entries that have an equation that calculates the value to display. We DO NOT type in the numbers we are looking for; we type in the equation. This equation will be updated upon the change or entry of any data that is referenced in the equation.

In our first example, the solution was $252.61. This was NOT typed into the keyboard. The formula that was typed into the spreadsheet was:=PMT(C4/12,C5,-C3) C4 (annual interest rate) was divided by 12 because there are 12 months in a year. Dividing by 12 will give us the interest rate for the payment period - in this case a payment period of one month. It is also important to type in the reference to the constants instead of the constants. Had I entered =PMT(.096,60,-12000) my formula would only work for that particular set of data. I could change the months above and the payment would not change. Remember to enter the cell where the data is stored and NOT the data itself. Spreadsheets have many Math functions built into them. Of the most basic operations are the standard multiply, divide, add and subtract. These operations follow the order of operations (just like algebra). Let's look at some examples. For these following examples lets consider the following data: y A1 (column A, row 1) = 5 y A2 (column A, row 2) = 7 y A3 (column A, row 3) = A B 8 1 5 3 y B1 (column B, row 1) = 2 7 4 3 y B2 (column B, row 2) = 3 8 6 4 y B3 (column B, row 3) = 6

Operation

Symbol

Referenced Data = A1 * B3 = A3 / B2 = B2 + A2 = A3 - B1

Answer 30 2 11 5

/ + -

25

Spreadsheet Basics:

Excel allows you to create spreadsheets much like paper ledgers that can perform automatic calculations. Each Excel file is a workbook that can hold many worksheets. The worksheet is a grid of columns (designated by letters) and rows (designated by numbers). The letters and numbers of the columns and rows (called labels) are displayed in gray buttons across the top and left side of the worksheet. The intersection of a column and a row is called a cell. Each cell on the spreadsheet has a cell address that is the column letter and the row number. Cells can contain either text, numbers, or mathematical formulas.

The worksheets in a workbook are accessible by clicking the worksheet tabs just above the status bar. By default, three worksheets are included in each workbook. To add a sheet, select InsertWorksheet from the menu bar. To rename the worksheet tab, right-click on the tab with the mouse and select Rename from the shortcut menu. Type the new name and press the ENTER key. The Standard Toolbar This toolbar is located just below the menu bar at the top of the screen and allows you to quickly access basic Excel commands.

26

New - Select File|New from the menu bar, press CTRL+N, or click the New button to create a new workbook. Open - Click File|Open from the menu bar, press CTRL+O, or click the Open folder button to open an existing workbook. Save - The first time you save a workbook, select File|Save As and name the file. After the file is named click File|Save, CTRL+S , or the Save button on the standard toolbar. Print - Click the Print button to print the worksheet. Print Preview - This feature will allow you to preview the worksheet before it prints. Spell Check - Use the spell checker to correct spelling errors on the worksheet. Cut, Copy, Paste, and Format Painter - These actions are explained in the Modifying A Worksheet section. Undo and Redo - Click the backward Undo arrow to cancel the last action you performed, whether it be entering data into a cell, formatting a cell, entering a function, etc. Click the forward Redo arrow to cancel the undo action. Insert Hyperlink - To insert a hyperlink to a web site on the Internet, type the text into a cell you want to be the link that can be clicked with the mouse. Then, click the Insert Hyperlink button and enter the web address you want the text to link to and click OK. Autosum, Function Wizard, and Sorting - These features are discussed in detail in the Functions tutorial. Zoom - To change the size that the worksheet appears on the screen, choose a different percentage from the Zoom menu.

SUM FUNCTION: Probably the most popular function in any spreadsheet is the SUM function. The Sum function takes all of the values in each of the specified cells and totals their values. The syntax is:

y

In the first and second spots you can enter any of the following (constant, cell, range of cells).

y y

Blank cells will return a value of zero to be added to the total. Text cells cannot be added to a number and will produce an error.

27

A Lets use the table here for the discussion that follows: 1 25 50 75 test 2 We will look at several different specific examples that show how the typical function can be used! Notice that in A4 there is a TEXT 3 entry. This has NO numeric value and cannot be included in a total. 4 5 Example =sum (A1:A3) =sum (A1+A4) =sum (A1:A2, A5) Cells to ADD A1, A2, A3 A1, A4 A1, A2, A5 Answer 150 250 #VALUE! 75

Average Function :

There are many functions built into many spreadsheets. One of the first ones that we are going to discuss is the Average function. The average function finds the average of the specified data. (Simplifies adding all of the indicated cells together and dividing by the total number of cells.) The syntax is as follows.

y

Min Function:

The next function we will discuss is Min (which stands for minimum). This will return the smallest (Min) value in the selected range of cells.

y y

Blank entries are not included in the calculations of the Min Function. Text entries are not included in the calculations of the Min Function. Example of min =min (A1:A4) =min (A1, A3) =min (A1, A5) Cells to look at A1, A2, A3, A4 A1, A3 Ans. min 10 20 10

Max Function:

The next function we will discuss is Max (which stand for Maximum). This will return the largest (max) value in the selected range of cells.

y y

Blank entries are not included in the calculations of the Max Function. Text entries are not included in the calculations of the Max Function

28

Example of Max =max (A1:A4) =max (A1, A3) =max (A1, A5) Cells to look at A1, A2, A3, A4 A1, A3 A1, A5 Ans. Max 30 100 30 10

Count Function:

The next function we will discuss is Count. This will return the number of entries (actually counts each cell that contains number data) in the selected range of cells.

y y

Blank entries are not counted. Text entries are NOT counted. Example of Count =Count (A1:A3) =Count 100) (A1:A3, Cells to look at A1, A2, A3 A1, A2, A3 and 100 A1, A3 A1, A4 A1, A5 Answer 3 4 2 1 1

IF Function:

The next function we will discuss is IF. The IF function will check the logical condition of a statement and return one value if true and a different value if false. The syntax is

y y y

=IF (condition, value-if-true, value-if-false) value returned may be either a number or text if value returned is text, it must be in quotes Example of typed into column B =IF (A2>1,"Yes","No") =IF (A3>1, "Yes", "No") =IF (A5>10000, .08, .05) =IF (A6>10000, .08, .05)

IF

Compares is ( .95 > 1) is (1.37 > 1) is (14000 > 10000) is (8453 > 10000)

29

Examples: Question 1)

Create the following worksheet and answer the following questions.

Compute the following : a) b) c) d) e) Sales figure is expected to grow up by 15% in the year 2006. Advertisement cost will increase by 8%. Material cost will go up by 11%. Labour cost will increase by 15%. Overhead will decrease by 5%.

Calculate the estimated Gross Profit for the year 2006, where a) Gross Profit = Total sales Total Cost b) Total Cost = Advertisement + Material + Labour + Overhead Create a bar graph compareing the expenses of 2005 and 2006.

Answer :

Particulars TOTAL SALES: Total Cost: Advertisement Material Labour Overhead Total Cost: Gross Profit Actuals 2005 (in BUDGETED Rs.) Rs.) 2006(in

30

Actuals 2005 (in BUDGETED Rs.) Rs.) 2006(in

Particulars TOTAL SALES: Total Cost: Advertisement Material Labour Overhead Total Cost: Gross Profit

ve rt i se m en

ia

bo u

at

La

Question 2)

Create a worksheet having the following fields Employee Name, Basic Salary, HRA, Da, PF, Net Pay. Insert at least 10 records having employee Name and Basic Salary. Calculate the HRA, DA, PF and Net Pay of the employees using appropriate formulas in the worksheet. The rules for the calculation are as follows: i) HRA = 15% of Basic Pay ii) DA = 22% of Basic Pay ( If Basic Salary <= 8000) DA = 18% of Basic Pay ( If Basic Salary > 8000 and <= 12000) DA = 15% of Basic Pay iii) PF = 9% of Basic Salary iv) Net Pay = Basic Salary + HRA + DA PF Draw a pie showing a comparison of Net Pay of all the 10 employees. Give appropriate legends and other details.

Ad

ve

rh e

er

ad

31

Answer :

Employee Name: Mr. A Mr. B Mr. C Mr. D Mr. E Mr. F Mr. G Mr. H Mr. I Mr. J Employee Name: Mr. A Mr. B Mr. C Mr. D Mr. E Mr. F Mr. G Mr. H Mr. I Mr. J Basic Salary 8000 20000 7000 8500 15000 6000 17000 25000 33000 12000 Basic Salary 8000 20000 7000 8500 15000 6000 17000 25000 33000 12000 Net Pay 10240 24200 8960 10540 18150 7680 20570 30250 39930 14880

HRA 1200 3000 1050 1275 2250 900 2550 3750 4950 1800

DA 1760 3000 1540 1530 2250 1320 2550 3750 4950 2160

PF 720 1800 630 765 1350 540 1530 2250 2970 1080

Mr.

32

ASSIGNMENT No. 3

Date: 28.10.2009.

Previously UNIX was known as UNICS (Uniplexed Information and Computing System) and was developed by Ken Thompson and Dennis Ritchie at AT&T of Bell Laboratories in 1960. It was developed in C language and found suitable for 1. Multiuser 2. Multi-terminal 3. Multitasking applications The 32-bit machines that support multitasking and networking are generally UNIX driven. The UNIX system itself supports many operations that are confined to application programs such as word processing, screen formatting, terminal-to-terminal communication and even typesetting. The UNIX is an excellent tool for programmers for developing programs. However it is not user-friendly. It is ideal for a user who wants to run off-the-shelf application packages. It has very complex commands which are difficult to remember and tricky to work with, even by a sophisticated user. One can make these commands more English like but the user will have to get assistance from a third party for developing a user-interface program (for example, Uniflex).

The basic features of UNIX operating system are: 1. It is written in high level language C and it is easy to put to different configurations. 2. UNIX programming environment is usually rich and productive and allows facility to build complex program from simpler programs. 3. The UNIX uses hierarchical file system which allows easy maintenance and efficient implementation. 4. In UNIX, it is easy to write application programs because it uses consistent format for files and the byte stream. 5. It is a multiuser and multi-process system. Hence each user can execute several processes simultaneously. 6. The UNIX hides the machine architecture from the user and hence it is easy to write programs that run on different hardware implementation.

There is multilevel security system in UNIX which are as follows : (a) First Level- Supply of correct login and password by the user when terminal is switched on. (b) Second Level- A directory can be assigned permissions as follows: 1. Read Permission- means that the list of filenames stored in the directory is accessible by the user. 2. Write Permission- means that user can manipulate the files, or user can write or add texts into the file. 3. Execute Permission- means that user can pass through the directory for going into the subdirectories under it. (c) Third Level-The files in UNIX system can also be given permissions as follows : 1. Read Permission- means that user can see the contents of the file only. 2. Write Permission- means that user can manipulate the contents of the files. 3. Execute Permission- means that user can run the file as per the requirement. It is to be noted that the user may always apply one or more levels of security as shown above.

33

UNIX COMMANDS:

1. cat

cat[options][files] This command reads one or more files and prints them on standard output. OPTIONS:y e print a $ to mark the end of each line .must be used with v. y a suppress messages about nonexistent files.

Examples:

Display a file $ cat myfile Concatenate two files: $ cat file1 file2 >> file3.dat Put the contents of a file into a variable $my_variable=`cat $myfile.txt`

2. chmod

chmod[options]mode files This command changes the access mode of one or more files. Only the owner of a file or a privileged user may change its mode. OPTIONS:y f suppress error message upon failure to change a filess mode . y R recursively descends error arguments while setting modes.

Examples

chmod 400 file - Read by owner chmod 040 file - Read by group chmod 004 file - Read by world chmod 200 file - Write by owner chmod 020 file - Write by group chmod 002 file - Write by world chmod 100 file - execute by owner chmod 010 file - execute by group chmod 001 file - execute by world To combine these just add the numbers together: chmod 444 file - Allow read permission to owner and group and world chmod 777 file - Allow everyone to read, write, and execute file

34 3. cp

cp[options ]file1 file2. cp[options]files directory This command copies one or more files to the same name under directory. If the destination is an existing file ,the file is overwritten ;if the destination is an existing directory ,the file is copied into the directory.

OPTIONS:y y

i prompt for confirmation (y for yes) before overwriting an existing file . p preserve the modification time and permission modes for the copied file.(normally cp submits the permissionof the invoking user).

$ cp -f /mnt/floppy/* /home/simon

4. echo

echo[-n][string] this is the /bin/echo command.echo arguments to standard output .

VERSION DIFFERENCES ARE:. /bin/echo . /user/ucb/echo. . bourne shell echo. . c shell echo. . korn shell echo.

5. expr

expr arg1 operator arg2[operator arg3] This command evaluates arguments as expressions and prints the results. It is typically used in shell commands to perform a simple mathematics, such as addition or subtraction. ARITHMETIC OPERATORS:. . . . . + / * %

35

RELATIONAL OPERATORS:. = . . . . . != > >= < <=

LOGICAL OPERATORS:. . | $

Examples Here are a few examples, including quoting for shell metacharacters. To add 1 to the shell variable `foo', in Bourne -compatible shells: foo=`expr $foo + 1` To print the non-directory part of the file name stored in `$fname', which need not contain a `/'. expr $fname : '.*/ \(^.*\)' '^|' $fname An example showing that ` \+' is an operator: expr aaa : 'a \+' => 3 expr abc : 'a \(.\)c' => b expr index abcdef cz => 3 expr index index a error--> expr: syntax error expr index quote index a => 0

6. grep

grep[options] regexp[files] This command searches one or more files for lines that match a regular expression [ regexp ]. Exit status is 0 if any line match, 1 if not, and 2 for errors.

OPTIONS:y b precede each line with its block number . y c print only a count of matched lines.

36 7. ls

ls[options] [names] If no names are given, list the files in the current directory. With one or more names ,the list files contained in a directory name or that match a file names can include file name met characters.

OPTIONS:y a list all the files ,including the normally hidden ones. y b show non printing characters in octal.

EXAMPLES

ls -al total 109 drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x drwxr-xr-x dr-xr-xr-x drwx-----drwxr-xr-x drwxrwxrwt drwxr-xr-x drwxr-xr-x

18 18 2 3 6 34 5 4 2 2 5 2 63 13 3 9 19 17

root root root root root root root root root root root root root root root root root root

root root root root root root root root root root root root root root root root root root

4096 Jun 9 21:12 ./ 4096 Jun 9 21:12 ../ 4096 Jun 9 21:14 bin/ 1024 Jun 9 20:32 boot/ 36864 Jul 12 10:26 dev/ 4096 Jul 12 10:25 etc/ 4096 Jun 9 21:28 home/ 4096 Jun 9 21:18 lib/ 16384 Jun 9 21:01 lost+found/ 4096 Nov 24 1999 misc/ 4096 Jun 9 20:32 mnt/ 4096 Aug 23 1999 opt/ 0 Jul 12 11:25 proc/ 4096 Jul 12 01:00 root/ 4096 Jun 9 21:22 sbin/ 4096 Jul 12 13:48 tmp/ 4096 Ju n 9 21:07 usr/ 4096 Jun 9 21:22 var/

the first column under long ( -l) is the file type 'd' for directory(folder) 'f' for file # list ALL subdirectories ls *

8. man

man[options] [[sections] subjects] This command displays information from the on-line reference manuals .If you dont specify a subject ,you must supply either a keyword (for -k) or a file (for -f).

OPTIONS:y f files display a on line summary of one or reference files . y k display any header line that contains one of the keywords.

37

9. mkdir

mkdir[options] directories This command can create one or more directories. You must have write permission in the parent directory in order to create a directory. OPTIONS:y y

m mode set the access mode for new directories. p create intervening if they dont exist.

10. mv

mv [options] sources target This is a command to move files and directories around on the system or to rename them.

OPTIONS:y f force the move ,even if the target files exist, suppress messages about the restricted access modes. y I inquire; prompt for a y (yes) response before overwriting an existing target.

Examples

Rename the file apple as orange.doc: mv apple orange.doc Move orange.doc to the Documents folder: mv orange.doc ~/Documents/orange.doc Rename a bunch of file extensions e.g. change *.txt into *.htm for f in *.txt; do mv ./"$f" "${f%txt}htm"; done `mv' can move only regular files across filesystems.

11. passwd

passwd [options] [user] This command creates or changes a password associated with a user name .Only the owner or privileged user may change the password.

OPTIONS:y d delete password ,user is no longer prompted for one. y f force expiration of users password :user must change password in the next login.

12. rm

rm [options] files

38

This command deletes one or more files .to remove file , you must have written permission in the directory that contains the file , but you need not have permission on the file itself.

OPTIONS:y f force. Remove write protected files without prompting. y I prompt for y (remove the files) or n (do not remove the file) .overrides -f.

13. rmdir

rmdir [options] directories This command deletes the named directories (the directory itself, not the contents) .Directories are deleted from the parent directory and must be empty (if not, rm r can be used instead.). Options: y p remove directories and any inter vening parent directories that become empty as a result ; useful for removing sub directory trees. y s suppress standard error messages caused by p.

Example

Before deleting with a wildcard, it's wise to echo the files first: $ echo elvis?costello*.mp3 $ rm elvis?costello*.mp3

14. sh

sh [options] [arguments] The standard command interpreter (bourn shell) executes commands from a terminal or a file.

15. vi

vi [options] files This command is a screen oriented text editor; based on ex. Options c,-C,-l, -L,-r,-R and t are the same as in ex.

OPTIONS:-c command enter vi and execute the given vi command. -R Read only mode .Files cant be changed.

39

Section- II

40

ASSIGNMENT No. 1

PROGRAM STATEMENT:

Date: 30.10.2009.

Write a C program so that for all integers I,J,K,L from 1 to 10. Find and print all combination of I,J,K and L such that I+J+K=L and I<J<K<L.

THEORY:

The integers are formed by the natural numbers including 0 (0, 1, 2, 3, ...) together with the negatives of the non-zero natural numbers (1, 2, 3, ...). Viewed as subset of the real numbers, they are numbers that can be written without a fractional or decimal component, and fall within the set {... 2, 1, 0, 1, 2, ...}. For example, 65, 7, and 756 are integers; 1.6 and 1 are not integers. The set of all integers is often denoted by Z. Like the natural numbers, the integers form an infinite set. An integer is often a primitive data type in computer languages. However, integer data types can only represent a subset of all integers, since practical computers are of finite capacity. Also, in the common two's complement representation, the inherent definition of sign distinguishes between "negative" and "non-negative" rather than "negative, positive, and 0". (It is, however, certainly possible for a computer to determine whether an integer value is truly positive.) Fixed length integer approximation data types (or subsets) are denoted int in several programming languages (such as C, Java, etc.). In the above problem there are four integers I,J,K,L. Each can have value between 1 and 10. We are to find all the combinations of I,J,K,L such that the conditions I+J+K=L and I<J<K<L holds and print them to the screen.

ALGORITHM:

Function combint(N) (* This function finds and prints all combination of four integers I,J,K,L from 1 to N such that I+J+K=L and I<J<K<L *) Step 1: [Initialise] I=1, J=I+1, K=J+1. Step 2: [Find all possible values of I] Repeat step 3 to step 9 while I<=N/3. Step 3: [Find all possible values of J] Repeat step 4 to step 8 while J<=(N-I)/2. Step 4: [Find all possible values of K] Repeat step 5 to step 7 while K<=N-I-J. Step 5: [Assign I+J+K to L] L=I+J+K. Step 6: [Print combination] Write I+J+K=L. Step 7: [Update value of K] K=K+1. Step 8: [Update value of J] J=J+1. Step 9: [Update value of I] I=I+1. Step 2: [Finished] Return.

41 PROGRAM CODE:

#include<stdio.h> #include<conio.h> int main(void) { int i,j,k,l,n; printf("\nAll combinations of integers i,j,k,l such that i+j+k=l and i<j<k<l from 1 to n are:\n"); printf("\nEnter the value of n:"); scanf("%d",&n); for (i=1;i<=n/3;i++)/* for different values of i */ for (j=i+1;j<=(n-i)/2;j++)/* for different values of j greater than i*/ for (k=j+1;k<=n-i-j;k++)/* for different values of k greater than j*/ { l=i+j+k; /* Assign i+j+k to l */ printf("\n%d+%d+%d=%d",i,j,k,l); /* Print combination */ } getch(); return 0; }

All combinations of integers i,j,k,l such that i+j+k=l and i<j<k<l from 1 to n are: Enter the value of n:10 1+2+3=6 1+2+4=7 1+2+5=8 1+2+6=9 1+2+7=10 1+3+4=8 1+3+5=9 1+3+6=10 1+4+5=10 2+3+4=9 2+3+5=10

DISCUSSIONS:

1. In this program, only the ith loop starts from 1. All the inner loops j,k are started from i+1, j+1 since one of the condition of combination is I<J<K<L. The program would have also worked if all loops are started from 1 and we keep a separate check on I<J<K<L. But the method is avoided since it requires much more no. of iterations, thus making the program slower. 2. The time complexity of the algorithm is reduced by minimizing the upper limit of i,j, and k loops. By examining manually the combinations, we see that the value of i cannot be more than n/3, n being the maximum value of l. Similarly, the value of j must be less than (n-i)/2 and value of k must be less than n-i-j. Thus much less number of iterations is required to find all possible combinations rather than setting the upper limit of all loops to n. 3. The value of n is input by the user. Thus the program has the capability to find combination of these four integers up to a desired value from 1 by satisfying the given conditions.

42

ASSIGNMENT No. 2

PROGRAM STATEMENT:

Date: 04.11.2009.

Write a program, which will ask to enter two set of integers. Then perform the following set operations:

a. Intersection. b. Union. c. Minus.

THEORY:

A set is a well-defined collection of distinct objects which are called members of the set or the elements of the set. By well-defined, we mean that it must be possible to tell beyond doubt whether or not a given object belongs to the collection that we are considering. The elements or members of a set can be anything: numbers, people, letters of the alphabet, other sets, and so on. Sets are conventionally denoted with capital letters. Sets A and B are equal if and only if they have precisely the same elements. For example, if the set A consists of the elements 1, 2, 3 and 4, then we express the set as A = {1, 2, 3, 4}. The three basic set operations are: a. Union The union of two sets A and B is a new set consisting of the elements which belong to A or B or to both. The union of A and B is denoted by AUB. For example, if A = {a, b, c} and B = {c, d, e, f}, then AUB = {a, b, c, d, e, f}. b. Intersection - The intersection of two sets A and B is a new set consisting of the elements which belong to A as well as in B. The intersection of A and B is denoted by A B. For example, if A = {a, b, c} and B = {c, d, e, f}, then A B = {c}. c. Minus The difference or minus of two sets A and B in that order is the set of elements which belong to A but do not belong to B and is denoted by A-B or A\B. For example, if A = {a, b, c} and B = {c, d, e, f}, then A-B = {a, b}. We now implement the above three set operations by the algorithm given below.

ALGORITHM:

Function isort(X,k) (* This function inserts a new element in sorted order in a previously sorted set X. This function is called every time when a new element is inserted in a set X. At beginning, the new element is inserted at the end of sorted set. The position of the new element is k. *) Step 1: [Hold new element in a temporary variable] temp=X[k]. Step 2: [Move ith element to (i+1)th position till the actual position of temp is found] for i=k-1 down to 1 if temp<X[i] X[i+1]=X[i]. End if. End for. Step 3: [Insert element temp in its actual position] X[i+1]=temp. Step 4: [Finished] Return. Function setoperations(A,B,UNION,INTER,MINUS,n1,n2) (* The union, intersection, and minus of two sorted sets A and B are computed by this function. A, B are the two input sets. UNION, INTER, MINUS are the solution sets.

43

n1, n2 are number of elements in set A and set B *) Step 1: [Initialise number of elements of three solution sets to zero] n3=n4=n5=0. Step 2: [Find union, intersection, and minus sets] for i=1 to n1 AND j=1 to n2 if A[i]<B[j] [If element i of set A is less than element j of set B] n3=n3+1. n5=n5+1. UNION[n3]=MINUS[n5]=A[i].[Insert element i of set A to sets UNION and MINUS] i=i+1. End if. else if A[i]=B[i] [If element i of set A is equal to element j of set B] n3=n3+1. n4=n4+1. UNION[n3]=INTER[n4]=A[i]. [Insert element i of set A to sets UNION and INTER] i=i+1. j=j+1. else [If element i of set A is greater than element j of set B] n3=n3+1. UNION[n3]=B[j]. [Insert element j of set B to union set] j=j+1. End of inner if else structure. End of outer if else structure. End for. [At this point one set gets exhausted] while (i<=n1) [Copy remaining contents of set A to sets union and minus, if any] n3=n3+1. n5=n5+1. UNION[n3]=MINUS[n5]=A[i]. i=i+1. End while. while (j<=n2) [Copy remaining contents of set B to union set, if any] n3=n3+1. UNION[n3]=B[j]. j=j+1. End while. Step 3: [Finished] Return.

44 PROGRAM CODE:

#include<stdio.h> #include<conio.h> #define MAX 100 void isort(int x[MAX],int k); void setoperations(int [],int [],int [],int [],int [],int *,int *,int *,int *,int *); int main(void) { int a[MAX],b[MAX],u[MAX],inter[2*MAX],minus[MAX],n1,n2,n3,n4,n5,i; printf("*** Program to find union, intersection, and minus of two sets A and B ***\n\n"); /* Input number of elements in set A and set B */ printf("\nEnter the number of elements in set A:"); scanf("%d",&n1); printf("\nEnter the number of elements in set B:"); scanf("%d",&n2); /* Input elements in set A and so the elements by insertion sort */ rt for (i=0;i<n1;i++) { printf("\nEnter element %d in set A:",i+1); scanf("%d",&a[i]); isort(a,i); } /* Input elements in set B and sort the elements by insertion sort */ for (i=0;i<n2;i++) { printf("\nEnter element %d in set B:",i+1); scanf("%d",&b[i]); isort(b,i); } setoperations(a,b,u,inter,minus,&n1,&n2,&n3,&n4,&n5); /* Print set A */ printf("\nA={"); for (i=0;i<n1;i++) printf("%d, ",a[i]); printf("}\n"); /* Print set B */ printf("\nB={"); for (i=0;i<n2;i++) printf("%d, ",b[i]); printf("}\n"); /* Print set AUB */ printf("\nAUB={"); for (i=0;i<n3;i++) printf("%d, ",u[i]); printf("}\n"); /* Print intersection of set A and B */ printf("\nIntersection of set A and B={"); for (i=0;i<n4;i++) printf("%d, ",inter[i]); printf("}\n"); /* Print set A-B */ printf("\nA-B={"); for (i=0;i<n5;i++)

45

printf("%d, ",minus[i]); printf("}\n"); getch(); return 0; } /* Function isort inserts a new element in sorted order in a previously sorted set */ void isort(int x[],int k) { int i,temp; temp=x[k]; /* Store the element k in a temporary variable */

/* Move ith element to (i+1)th position till the position of temp is found */ for (i=k-1;i>=0 && temp<x[i];i --) x[i+1]=x[i]; x[i+1]=temp; }/* End isort */ /* Insert te in its new position */ mp b[],int u[],int inter[],int minus[],int *n1,int

void setoperations(int a[],int *n2,int *n3,int *n4,int *n5) { int i,j; *n3=*n4=*n5=0;

for (i=0,j=0;i<*n1 && j<*n2;) /* If element i of set A is less than element j of set B */ if (a[i]<b[j]) /* Insert element i of set A to sets union and minus */ u[(*n3)++]=minus[(*n5)++]=a[i++]; /* If element i of set A is equal to element j of set B */ else if (a[i]==b[j]) { /* Insert element i of set A to sets union and intersection */ u[(*n3)++]=inter[(*n4)++]=a[i]; i++; j++; } else /* If element i of set A is greater than element j of set B */ u[(*n3)++]=b[j++]; /* Insert element j of set B to union set */ /* At this point one set gets exhausted */ /* Copy remaining contents of set A to sets union and minus, if any*/ for (;i<*n1;) u[(*n3)++]=minus[(*n5)++]=a[i++]; /* Copy remaining contents of set B to union set, if any */ for (;j<*n2;) u[(*n3)++]=b[j++]; }/* End setoperations */

*** Program to find union, intersection, and minus of two sets A and B *** Enter the number of elements in set A:3 Enter the number of elements in set B:4 Enter element 1 in set A:5 Enter element 2 in set A:4

46

Enter element 3 in set A:3 Enter element 1 in set B:6 Enter element 2 in set B:2 Enter element 3 in set B:4 Enter element 4 in set B:5 A={3, 4, 5, } B={2, 4, 5, 6, } AUB={2, 3, 4, 5, 6, } Intersection of set A and B={4, 5, } A-B={3, }

DISCUSSIONS:

1. Each element inserted in the arrays a and b are sorted by using insertion sort. 2. The two sets are sorted and then the merging algorithm is applied to find the resultant sets. 3. The set operations union, intersection, and minus are very important in set theory and are very often used.

47

ASSIGNMENT No. 3

PROGRAM STATEMENT:

Date: 11.11.2009.

Every even integer greater than 4 can be expressed as the sum of two odd primes, like 6=3+3, 8=3+5, and so on. Write a program to generate such combinations for all the even integers from 6 to 100.

THEORY:

An even number is a number which is divisible by 2. For example, 4,10, 22 are even numbers. An odd number is a number which is not divisible by 2. For example 3, 5, 17 are odd numbers. A prime number is a natural number that has exactly two distinct natural number divisors, 1 and itself. For example 2, 3, 5, 7, 11 are prime numbers. The number 1 is by definition not a prime number. Expressing an even number as a sum of two odd primes is called a Goldbach partition of the number. For example, 4=2+2 6=3+3 8=3+5 10 = 7 + 3 or 5 + 5 12 = 5 + 7 14 = 3 + 11 or 7 + 7. We need to generate such combinations for even integers greater than 4 from range 6 to 100.

ALGORITHM:

Procedure Goldbach(a,b) (* a,b are the starting range and ending range of the integers. *) Step 1: [Check for validity of a and b] if (a mod 2=1 OR b mod 2=1 OR a<=4 OR a>b) Write Wrong value entered. Stop. End if. Step 2: [Initialise] i=a. Step 3: [For generating different even numbers within the input range] Repeat steps 3 to step 8 till i<=b. Step 4: [Initialise] j=3. Step 5: [For finding two odd primes whose sum equals number i] Repeat steps 6 to step 7 till j<=i/2. Step 6: [Check if j and i-j is prime. If both are prime then write combination] if (is_prime(j) AND is_prime(i-j)) Write i=j+(i-j). End if. Step 7: [Update inner loop counter] j=j+2. Step 8: [Update outer loop counter] i=i+2. Step 9: [Finished] End. Function is_prime(x) (* This function returns 1 if x is prime, otherwise it returns 0 *) Step 1: [Initialize] div=2.

48

Step 2: [Find whether x is prime] Repeat steps 2 to 4 till div<= . Step 3: [Check is x is divisible by div] if (x mod div)=0 Return 0. End if. Step 4: [Update counter] div=div+1. [End of Step 2 loop] Step 5: [Finished] Return 1.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<math.h> int is_prime(int x) /* Function is_prime returns 1 if x is prime and 0 otherwise */ { int div; for (div=2;div<=sqrt(x);div++) if (x%div==0) return 0; return 1; } int main(void) { int a,b,i,j; printf("Program to generate every even integer (greater than 4) as the sum of two odd primes within a certain range \n"); do { /* Input the range of even of numbers */ printf("\nEnter the starting even number (larger than 4):"); scanf("%d",&a); printf("\nEnter the ending even number:"); scanf("%d",&b); /* Check for correct input values */ if (a%2==0 && b%2==0 && a>4 && a<b ) break; else printf("\nWrong value entered. Enter correct values. \n"); } while (1); /* Continue loop if wrong values are entered */ printf("\nThe combinations are: \n\n"); for(i=a;i<=b;i+=2) /* Fi nd different even numbers within the input range */ { for(j=3;j<=i/2;j+=2) /* Find two odd primes whose sum equals number i */ { if(is_prime(j) && is_prime(i -j)) /* if both j and i -j are prime numbers */ { printf("%d = %d + %d\n", i, j, i-j); break; }/* End if */ }/* End inner for */ }/* End outer for */ getch();

49

return 0; }

Program to generate every even integer (greater than 4) as the sum of two odd primes within a certain range Enter the starting even number (larger than 4):6 Enter the ending even number:100 The combinations are: 6=3+3 8=3+5 10 = 3 + 7 12 = 5 + 7 14 = 3 + 11 16 = 3 + 13 18 = 5 + 13 20 = 3 + 17 22 = 3 + 19 24 = 5 + 19 26 = 3 + 23 28 = 5 + 23 30 = 7 + 23 32 = 3 + 29 34 = 3 + 31 36 = 5 + 31 38 = 7 + 31 40 = 3 + 37 42 = 5 + 37 44 = 3 + 41 46 = 3 + 43 48 = 5 + 43 50 = 3 + 47 52 = 5 + 47 54 = 7 + 47 56 = 3 + 53 58 = 5 + 53 60 = 7 + 53 62 = 3 + 59 64 = 3 + 61 66 = 5 + 61 68 = 7 + 61 70 = 3 + 67 72 = 5 + 67 74 = 3 + 71 76 = 3 + 73 78 = 5 + 73 80 = 7 + 73 82 = 3 + 79 84 = 5 + 79 86 = 3 + 83 88 = 5 + 83

50

90 = 7 + 83 92 = 3 + 89 94 = 5 + 89 96 = 7 + 89 98 = 19 + 79 100 = 3 + 97

DISCUSSIONS:

1. This program has the capability to input the range of even numbers. 2. In this program, for each even number, only one combination of sum of odd numbers is computed. There may be combinations of other odd numbers whose sum equals the even number. 3. The program checks for wrong input values and asks the user to enter correct values. 4. The sqrt() function is used to compute the square root of x, thus reducing the computational time in checking whether a number is prime or not.

51

ASSIGNMENT No. 4

PROGRAM STATEMENT:

Write a C program to find the perfect numbers up to a certain range.

Date: 18.11.2009.

THEORY:

In mathematics, a perfect number is a positive integer that is the sum of its proper positive divisors, that is, the sum of the positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). For example, 6 is a perfect number because its factors 1, 2, 3 adds up to give 6. But 15 is not a perfect number because its factors 1, 3, 5 on adding does not give 15.

ALGORITHM:

Function IsPerfect( n) (* This function checks whether a number n is perfect. The function returns 1 if the number is perfect and 0 otherwise. *) Step 1: [Initialize] s=0. Step 2: [Find the sum of the factors of the given number] for i=1 to n/2 do if (n mod i = 0) then s=s+i. end if. end for. Step 3: [Check whether the number is perfect and returning accordingly] if (s=n) then Return 1. else Return 0.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> /* Function IsPerfect returns 1 if n is a perfect number and 0 otherwise */ int IsPerfect(int n) { int i,s=0; for(i=1;i<=n/2;i++) if(n%i==0) /* Finding the factors of the given number */ s+=i; /* Add the factors */ if(s==n) return 1; else return 0; } int main() { int n,i; printf("\t*** Program to generate perfect numbers from 1 to n *** n"); \ /* Input */ /* The given number is a perfect number */ /* The given num ber is not a perfect number */

52

printf("\nEnter the value of n : "); scanf("%d",&n); /* Output */ printf("\nPerfect number up to %d : \n",n); for(i=1;i<=n;i++) if(IsPerfect(i)) printf(" %d ",i); getch(); return 0; }

*** Program to generate perfect numbers from 1 to n *** Enter the value of n : 10000 Perfect number up to 10000 : 6 28 496 8128

DISCUSSIONS:

1. The range of perfect numbers can be maximum 32767 in this program, since variable is declared of integer type (int). To check whether there is perfect number higher than this number, then long integer (long int) data type must be used. 2. The perfect numbers are not very common. From the program output we see that only four perfect numbers exists between the first 10000 natural numbers. 3. To find the factors of each number we checked factors up to n/2 for every number. This is because no factors of a number can be greater than n/2 except the number itself.

53

ASSIGNMENT No. 5

PROGRAM STATEMENT:

Write a menu driven program to find the value of sin(x), cos(x), , log(x).

Date: 20.11.2009.

THEORY:

Sin(x) and cos(x) are two basic operations or functions in trigonometry. Here x is the angle between two sides of a right angled triangle. It is not practical to get the values of different sides of a right angled triangle. So, it is not possible to calculate the values of these basic operations easily. For this reason, we need other computational method to calculate these values. We use De -Moivres theorem to calculate these basic operations or functions. From De-Moivres theorem we get, (1). where i= Again, from exponential series,

(4) Here the angle is in radian unit. We know the relation between degree and radian units as follows: (5) Now, using (3) and (4) along with (5), it is possible to calculate the value of these basic operations. and log(x) are two very important infinite series in mathematics, called the exponential series and the logarithmic series, which are defined as follows. For all values of x the infinite series denoted by . (6) If -1<x 1, then the infinite series denoted by . is convergent and its sum to infinity is (7) is convergent and its sum to infinity is

; [0<x ](8) Using equations (6) and (8), it is possible to calculate the values of these two functions. We note that all the four series that we are to evaluate are infinite series. So it is not possible to calculate all the infinite terms. Also, it can be noted that the rate of growth of numerator is lesser than the denominators. So the higher terms are negligibly small. For finite precision of computation, no. of significant terms after decimal point restricts its higher terms. So we may neglect them. This idea is used for our algorithm and program generation as follows.

ALGORITHM:

To form the algorithm, we need to search for the computational iterative formula for finding the different terms of the different series. They are as follows.

54

For By observation we get, for i 1, and Now, . .

Now, the algorithm for calculating the different functions is given below. is the error up to which terms will be added. Function sine(x) (* This function returns the sine of x. Here x is in radian unit *) Step 1: [Initialisation] sine=x, i=1, term=x. Step 2: [Apply the formula iteratively] while (|term|>) term=-(term*x*x)/((2i+1)*(2i)).

55

sine=sine+term. i=i+1. End while. Step 3: [Finished] Return sine. Function cosine(x) (* This function returns the cosine of x. Here x is in radian unit *) Step 1: [Initialisation] cosine=1, i=0, term=1. Step 2: [Apply the formula iteratively] while (|term|>) term=-(term*x*x)/((2i+1)*(2i+2)). cosine=cosine+term. i=i+1. End while. Step 3: [Finished] Return cosine. Function expo(x) (* This function returns the exponential value of x *) Step 1: [Initialisation] e=1, i=1, term=1. Step 2: [Apply the formula iteratively] while (|term|>) term=(term*x)/i. e=e+term. i=i+1. End while. Step 3: [Finished] Return e. Function logarithmic(x) Step 1: [Initialisation] log=x-1, i=0, term=x-1. Step 2: [Apply the formula iteratively] while (|term|>) term=-(term*(i+1)*(x-1))/(i+2). log=log+term. i=i+1. End while. Step 3: [Finished] Return log.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<math.h> #define DIFF 0.0000001 double double double double sine(double x); cosine(double x); expo(double x); logarithmic(double x);

int main(void)

56

{ int n; double x; printf("\t*** ***\n"); do { printf("\n1.Find sin(x)\n2.Find log(x)\n5.Exit\n"); printf("\nEnter your choice:"); scanf("%d",&n); if (n==5) break; /* Check for wrong value of n */ if (n>5 || n<1) { printf("\nWrong key pressed.\n"); continue; } switch (n) { case 1: printf("\nEnter the value of x in degrees:"); scanf("%lf",&x); printf("\nThe value of sin(%lf) is % lf\n",x,sine(x)); break; case 2: printf("\nEnter the value of x in degrees:"); scanf("%lf",&x); printf("\nThe value of cos(%lf) is %lf \n",x,cosine(x)); break; case 3: printf("\nEnter the value of x:"); scanf("%lf",&x); printf("\nThe value of e^(%lf) is %lf \n",x,expo(x)); break; case 4: printf("\nEnter the value of x(0<x<=2):"); scanf("%lf",&x); printf("\nThe value of natural log(%lf) %lf\n",x,logarithmic(x)); break; } } while (1); /* Continue loop till user presses exit key */ getch(); return 0; } double sine(double x) { double term,sine; int i; x=x*M_PI/180; term=x; sine=term; /* Convert x to radian */ /* 1st term is calculated */ /* 1st term is added to sine / * cos(x)\n3.Find e^(x)\n4.Find Program to find the value of sin(x), cos(x), e^(x), log(x)

is

/* Continue adding successive terms greater than DIFF */ for (i=1;fabs(term)>=DIFF;i++) { term=-(term*x*x)/((2*i+1)*2*i); /* Calculate next term */ sine=sine+term; /* Add new term to sine */

57

} return sine; } double cosine(double x) { double term,cosine; int i; x=x*M_PI/180; term=1.0; cosine=term; /* Convert x to radian */ /* 1st term is calculated */ /* 1 term is added to cosine */ st

/* Continue adding successive terms greater than DIFF */ for (i=0;fabs(term)>=DIFF;i++) { term=-(term*x*x)/((2*i+1)*(2*i+2)); /* Calculate next term */ cosine=cosine+term; /* Add new term to cosine */ } return cosine; } double expo(double x) { double term,e; int i; term=1.0; e=term; for (i=1;fabs(term)>=DIFF;i++) { term=(term*x)/i; e=e+term; } return e; } double logarithmic(double x) { double term,log; int i; term=x-1; log=term; /* 1st term is calculated */ /* 1st term is added to log */ /* 1st term is calculated */ /* 1st term is added to e */

/* Continue adding successive terms greater than DIFF */ for (i=0;fabs(term)>=DIFF;i++) { term=-(term*(i+1)*(x-1))/(i+2); /* Calculate next term */ log=log+term; /* Add new term to log */ } return log; }

*** Program to find the value of sin(x), cos(x), e^(x), log(x) *** 1.Find sin(x) 2.Find cos(x) 3.Find e^(x) 4.Find log(x) 5.Exit

58

Enter your choice:1 Enter the value of x in degrees:30 The value of sin(30.000000) is 0.500000 1.Find sin(x) 2.Find cos(x) 3.Find e^(x) 4.Find log(x) 5.Exit Enter your choice:2 Enter the value of x in degrees:60 The value of cos(60.000000) is 0.500000 1.Find sin(x) 2.Find cos(x) 3.Find e^(x) 4.Find log(x) 5.Exit Enter your choice:3 Enter the value of x:1 The value of e^(1.000000) is 2.718282 1.Find sin(x) 2.Find cos(x) 3.Find e^(x) 4.Find log(x) 5.Exit Enter your choice:4 Enter the value of x(0<x<=2):.5 The value of natural log(0.500000) is -0.693147 1.Find sin(x) 2.Find cos(x) 3.Find e^(x) 4.Find log(x) 5.Exit Enter your choice:5

59 DISCUSSIONS:

1. The logarithmic function can compute logarithmic values of x only in the range [0<x<=2]. The program fails to compute other logarithmic values. It can be overcome by using some other method or from the standard library function log(x) under math.h. 2. The switch-case structure is used to create the menu in the program. 3. The precision of the results is up to 7 digits after decimal place. It can be increased or decreased by modifying the macro DIFF before compiling the program each time. 4. The macro M_PI is used to get the value of during calculation. M_PI is defined in file math.h. 5. The program checks for wrong input key; if wrong key is pressed it again takes the user back to the menu to press a correct key. 6. These are the basic trigonometric and algebraic functions and so these must be efficiently designed, so that it can be used in a library for complex mathematical calculations. To do so here we have tried to avoid the inclusion of factorial and power calculation. 7. Using sin(x), cos(x) and equation we can easily calculate tan(x) correctly. Using these basic trigonometry functions we can easily calculate other functions like cosec(x), sec(x), cot(x) etc. Similarly using we can calculate all hyperbolic and other complex function. 8. In C, there are inbuilt functions for calculating sin(x), cos(x) and . They can also be used to compare the accuracy of the program.

60

ASSIGNMENT No. 6

PROGRAM STATEMENT:

Write a C program to find the saddle point in a given matrix.

Date: 25.11.2009.

THEORY:

In mathematics, a matrix is a rectangular array of numbers. An item in a matrix is called an entry or an element. A saddle point in a matrix is the position, the value of which is the smallest in its row and maximum in its column. That is, in a matrix A, the point (m, n) is the saddle point if A(m, n) is the smallest element of the mth row and greatest element of the nth column. There can be more than one saddle point in a matrix.

ALGORITHM:

Function saddlepoint(A, x, y, r, c) (* This function checks whether a point (x, y) is a saddle point in matrix A. It returns 1 if (x, y) is a saddle point and 0 otherwise. r is the number of rows and c is the number of columns in the matrix. *) Step1: [Initialize] min=max=A[x][y], p=1. Step 2: [Check if it is the minimum element in its row] for i=1 to c do if A[x][i]<min p=0. End if. End for. Step 3: [Check if it is the maximum element in its column] for i=1 to r do if A[i][y]>max p=0. End if. End for. Step 4: [Finished] Return p.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> int check_saddle(int[20][20],int,int,int,int); int main(void) { int a[20][20],i,j,x,r,c,flag=0; printf("\t\t*** Program to find saddle point of a matrix *** \n"); /* INPUT VALUES */ printf("\nEnter the number of rows in the matrix: "); scanf("%d",&r); printf("\nEnter the number of columns in the matrix: "); scanf("%d",&c); printf("\nEnter each element:"); for(i=0;i<r;i++) for(j=0;j<c;j++) {

61

printf("\nElement (%d,%d) : ",i+1,j+1); scanf("%d",&a[i][j]); } /* PRINTING ORIGINAL MATRIX */ printf("\nOriginal matrix : \n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) printf("%4d",a[i][j]); printf("\n"); } /* SEARCH SADDLE POINT */ for(i=0;i<r;i++) for(j=0;j<c;j++) { x=check_saddle(a,i,j,r,c); if(x==1) { printf("\nSaddle point = %d at position (%d,%d)",a[i][j],i+1,j+1); flag=1; } } if(flag==0) printf("\nThere is no saddle point for the matrix!"); getch(); return 0; }/* END OF main

*/

/* Function check_saddle returns 1 if position (a,b) is a saddle point and 0 otherwise */ int check_saddle(int m[20][20],int a,int b,int r,int c) { int i,x=1,min,max; min=max=m[a][b]; /* Check if it is the minimum element in its row */ for(i=0;i<c;i++) if(m[a][i]<min) x=0; if (x==0) return x; /* Check if it is the maximum element in its column */ for(i=0;i<r;i++) if(m[i][b]>max) x=0; return x; }/* end of check_saddle */

Run 1: *** Program to find saddle point of a matrix ***

Enter the number of rows in the matrix: 2 Enter the number of columns in the matrix: 3 Enter each element: Element (1,1) : 0

62

Element (1,2) : 2 Element (1,3) : 3 Element (2,1) : 2 Element (2,2) : 1 Element (2,3) : 4 Original matrix : 0 2 3 2 1 4 There is no saddle point for the matrix! Run 2: *** Program to find saddle point of a matrix ***

Enter the number of rows in the matrix: 3 Enter the number of columns in the matrix: 3 Enter each element: Element (1,1) : 2 Element (1,2) : 1 Element (1,3) : 3 Element (2,1) : -1 Element (2,2) : 0 Element (2,3) : 1 Element (3,1) : 3 Element (3,2) : -1 Element (3,3) : 4 Original matrix : 2 1 3 -1 0 1 3 -1 4 Saddle point = 1 at position (1,2)

DISCUSSIONS:

1. There can be more than one saddle point in a matrix. The program is capable to find all the saddle points in a given matrix. 2. Saddle point does not exist in all matrices.

3. If (m, n) be the saddle point of a matrix A, then (m, n) will not be the saddle point of AT.

63

ASSIGNMENT No. 7

PROGRAM STATEMENT:

Write a program to check if a square matrix is Skew-Symmetric.

Date: 27.11.2009.

THEORY:

In mathematics, a matrix is a rectangular array of numbers. An item in a matrix is called an entry or an element. A square matrix is a matrix which has the same number of rows and columns. An n-by-n matrix is known as a square matrix of order n. A square matrix A is said to be skew-symmetric, if its transpose be equal to its negative, i.e., if . Hence the matrix is skew-symmetric, if for all i and j. The diagonal elements of a skew-symmetric matrix are thus obviously 0. For example, symmetric matrix. is a skew-

ALGORITHM:

Function Skew(A,n) (* This function returns 1 if the input matrix is skew-symmetric and 0 otherwise. A is the input matrix. n is the order of input matrix. *) Step 1: [Check for skew-symmetric condition] for i=1 to n do for j=i to n do if a[i][j]!=-a[j][i] Return 0. End if. End inner for. End outer for. Step 2: [Finished] Return 1.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> int skew(float [50][50], int); int main(void) { int i,j,n,x; float a[50][50]; printf("*** Program to check whether a square matrix is skewsymmetric ***\n"); /* Input order of matrix n and check for validity of n */ do { printf("\nEnter the order of the square matrix:"); scanf("%d",&n); if (n<1) printf("\nError in input.\n"); } while (n<1); /* Input elements of the matrix */ for (i=0;i<n;i++)

64

for (j=i;j<n;j++) { printf("\nEnter element in matrix in position(%d,%d):",i+1,j+1); scanf("%f",&a[i][j]); } x=skew(a,n); /* Print output */ if (x==1) printf("\nThe square matrix is skew -symmetric."); else printf("\nThe square matrix is not skew -symmetric."); getch(); return 0; } /* Function skew returns 1 if matrix is skew -symmetric and 0 otherwise */ int skew(float a[50][50], int n) { int i,j; /* Check for skew-symmetric condition */ for (i=0;i<n;i++) for (j=0;j<n;j++) if (a[i][j]!=-a[j][i]) return 0; return 1; }

1. *** Program to check whether a square matrix is skew-symmetric *** Enter the order of the square matrix:3 Enter element in matrix in position(1,1):0 Enter element in matrix in position(1,2):5 Enter element in matrix in position(1,3):1 Enter element in matrix in position(2,1):6 Enter element in matrix in position(2,2):0 Enter element in matrix in position(2,3):2 Enter element in matrix in position(3,1):-1 Enter element in matrix in position(3,2):-2 Enter element in matrix in position(3,3):0 The square matrix is not skew-symmetric. 2. *** Program to check whether a square matrix is skew-symmetric ***

65

Enter the order of the square matrix:3 Enter element in matrix in position(1,1):0 Enter element in matrix in position(1,2):-1 Enter element in matrix in position(1,3):2 Enter element in matrix in position(2,1):1 Enter element in matrix in position(2,2):0 Enter element in matrix in position(2,3):-3 Enter element in matrix in position(3,1):-2 Enter element in matrix in position(3,2):3 Enter element in matrix in position(3,3):0 The square matrix is skew-symmetric.

DISCUSSIONS:

1. In this program we traverse only half of the input matrix. For the non-diagonal and diagonal elements we check whether condition satisfies and thus the non-diagonal elements are also accessed by the same for loop. 2. By checking only one half of the matrix, the no. of comparisons of the above algorithm is of order of .5 . 3. A separate function skew is used to check whether the given input matrix is skew-symmetric or not. The main function is only used to take inputs and show the output.

66

ASSIGNMENT No. 8

PROGRAM STATEMENT:

Write a program to implement matrix multiplication of chain of matrices.

Date: 04.12.2009.

THEORY:

In mathematics, a matrix is a rectangular array of numbers. An item in a matrix is called an entry or an element. If m, n numbers are arranged in a rectangular array of m rows and n columns, it is called a matrix of order mXn. The product AB of two matrices A and B exists if the number of columns in A is equal to the number of rows in B and the matrices A and B are said to be conformable for the product AB. If and B= matrices then the number of columns (p) of A equals the number of rows A=

(p) of B. Hence the product AB is defined. The product AB is of order mXn and each of its elements is given by:

If many matrices are multiplied together, and their dimensions are written in a list in order, e.g. mn, np, pq, qr, the size of the result is given by the first and the last numbers (mr), and the values surrounding each comma must match for the result to be defined. The ordinary matrix product is not commutative.

ALGORITHM:

Function MatMult(A,B,C,p,q,r) (* This function multiplies two matrices A and B and store it in another matrix C. Size of A is (p X q) and size of B is (q X r) *) Step 1: [Initialize] i=j=k=0. Step 2: [Multiply] for i=1 to p do for j=1 to r do C[i][j]=0. for k=1 to q do C[i][j]=C[i][j]+(A[i][k]XB[k][j]). End for. End for. End for. Step 3: [Finished] Return. Function ChainMatMult(M,n) (* This function implements chain of matrix multiplication. It returns the final matrix. M is the array of matrices. n is the number of matrices . *) Step 1: [Check if there is only one matrix] if n=1 R1=M[0].A Return R1 End if. Step 2: [Perform multiplication of first two matrices] R=MatMult(M[0].A,M[1].A)

67

Step 3: [Perform chain multiplication] for i=1 to n MatMult(R1,M[i].A,R) End for. Step 4: [Finished] Return R.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<process.h> #define MAX 10 typedef struct matrix { int a[MAX][MAX]; int r,c; }MAT; /* Function GetMat input a matrix */ void GetMat(int m[MAX][MAX],int r,int c) { int i,j; for(i=0;i<r;i++) for(j=0;j<c;j++) { printf("\nElement (%d,%d):",i+1,j+1); scanf("%d",&m[i][j]); } } /* Function ShowMat shows a matrix */ void ShowMat(int m[MAX][MAX],int r,int c) { int i,j; for(i=0;i<r;i++) { printf("\n"); for(j=0;j<c;j++) printf("%4d",m[i][j]); } } /* Function MatMultiply multiplies two matrix and store into a third matrix */ void MatMultiply(int a[MAX][MAX],int b[MAX][MAX],int c[MAX][MAX],int p,int q,int r) { int i,j,k; for(i=0;i<p;i++) for(j=0;j<r;j++) { c[i][j]=0; for(k=0;k<q;k++) c[i][j]+=(a[i][k]*b[k][j]); } } /* Function CopyMat copies matrix a to matrix b */ void CopyMat(int a[MAX][MAX],int b[MAX][MAX],int r,int c) { int i,j; for(i=0;i<r;i++) for(j=0;j<c;j++) b[i][j]=a[i][j]; }

68

int main(void) { MAT m[MAX]; int r1[MAX][MAX],r2[MAX][MAX]; int n,i,j,k,x,r,c; printf("\n*** Program to implement matrix multiplication of chai of matrices n ***\n\n"); /* Input part */ printf("\nEnter the number of matrices:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("\n\nMatrix %d:\n",i+1); printf("\nEnter the number of rows:"); scanf("%d",&x); m[i].r=x; printf("\nEnter the number of columns:"); scanf("%d",&x); m[i].c=x; printf("\nEnter each element: \n"); GetMat(m[i].a,m[i].r,m[i].c); printf("\nMatrix is:\n"); ShowMat(m[i].a,m[i].r,m[i].c); } /* If number of matrices is 1 then copy it to resultant matrix */ if(n==1) { CopyMat(m[0].a,r1,m[0].r,m[0].c); r=m[0].r; c=m[0].c; } else { /* Check if the first two matrices satisfy matrix multiplication condition */ if(m[0].c==m[1].r) { /* Multiply the two matrices and store in r2 */ MatMultiply(m[0].a,m[1].a,r2,m[0].r,m[0].c,m[1].c); r=m[0].r; c=m[1].c; /* Copy contents of r2 to resultant matrix */ CopyMat(r2,r1,r,c); } else { printf("\nCannot multiply!"); getch(); exit(0); } /* Multiply the rest of the matrices */ for(i=2;i<n;i++) /* Check if condition of matrix multiplication is satisfied */ if(c==m[i].r) { /* Multiply matrix i+1 with previous resultant matrix */ MatMultiply(r1,m[i].a,r2,r,c,m[i].c); c=m[i].c; /* Copy contents of r2 to resultant matrix */ CopyMat(r2,r1,r,c); } else { printf("\nCannot Multiply."); getch(); exit(0);

69

} } /* Output part */ printf("\n\nResultant matrix:\n"); ShowMat(r1,r,c); getch(); return 0; }

*** Program to implement matrix multiplication of chain of matrices *** Enter the number of matrices:3 Matrix 1: Enter the number of rows:2 Enter the number of columns:2 Enter each element: Element (1,1):2 Element (1,2):3 Element (2,1):1 Element (2,2):2 Matrix is: 2 3 1 2 Matrix 2: Enter the number of rows:2 Enter the number of columns:3 Enter each element: Element (1,1):1 Element (1,2):0 Element (1,3):2 Element (2,1):3 Element (2,2):1 Element (2,3):-1

70

Matrix is: 1 0 2 3 1 -1 Matrix 3: Enter the number of rows:3 Enter the number of columns:2 Enter each element: Element (1,1):3 Element (1,2):2 Element (2,1):-1 Element (2,2):0 Element (3,1):0 Element (3,2):1 Matrix is: 3 2 -1 0 0 1 Resultant matrix: 30 23 19 14

DISCUSSIONS:

1. Each successive multiplication must satisfy the condition that the number of columns in first matrix is equal to number of rows in second matrix. 2. Multiplying two matrix Apxq and Bqxr gives a resultant matrix of size pxr. 3. Matrix multiplication is not commutative, so in general A X B B X A. Thus we should be aware of the order in which the matrices are inputted for correct result. 4. The chain of matrices is implemented by a structure MAT. It could have also been implemented by using a three dimensional array.

71

ASSIGNMENT No. 9

PROGRAM STATEMENT:

Date: 11.12.2009.

Write a program to compute the real roots of the following non-linear equation by Newton-Raphson method: Correct up to 5 significant digits.

THEORY:

In numerical analysis, NewtonRaphson method is perhaps the best known method for finding successively better approximations to the roots of a real-valued function. Newton's method converges remarkably quickly, especially if the iteration begins sufficiently near the desired root. Given a function f(x), we first find the derivative of the function f(x), i.e. f(x). Then we begin with an initial guess x0. Provided the function is reasonably well-behaved a better approximation x1 is The process is repeated until a sufficiently accurate value is reached: where xn+1 and xn are the n+1 and nth approximations of x. The condition of convergence of Newton-Raphson method is Here the given function is f(x)= . Therefore the derivative of the function f(x)= Now we compute the real roots of the function using the above iterative formula.

ALGORITHM:

Function NR(x0, H) (* x0 is the initial guess closer to root. H is the error between two successive terms. *) Step 1: [Initialization] i=0. Step 2: [Check whether the input function converges for ] if Write The function is divergent. Roots cannot be computed. Stop. End if. Step 3: [Perform the iteration to find the next successive approximate value of x] Step 4: [Check for termination condition] if H i=i+1. Go to Step 2. else Go to Step 5. End of if-else structure. Step 5: [Finished] Return . .

72 PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<math.h> float f(float x); float f1(float x); float f2(float x); int main(void) { float x[50]; int i=0; printf("\n*** To find the real roots of the equation x^3 -4x+1=0 by Newton Raphson Method ***\n"); /* Input initial approximation closer to root */ printf("\nEnter the initial guess of x closer to root:"); scanf("%f",&x[0]); printf("\nIteration No.\tx\n"); while (1) { /* Check whether the function is divergent */ if (fabs(f1(x[i])*f1(x[i]))<fabs(f(x[i])*f2(x[i]))) { printf("\nThe function is divergent. So roots cannot be computed by this method."); return 1; } /* Calculate next approximation closer to root */ x[i+1]=x[i]-f(x[i])/f1(x[i]); /* Print successive approximations of root */ printf("\n%d\t\t%f\n",i+1,x[i+1]); if (fabs(x[i]-x[i+1])<0.000005) break; i++; } /* Print final output correct upto 5 decimal places */ printf("\nThe final root is %.5f",x[i+1]); getch(); return 0; } float f(float x) /* Function f computes the function x^34*x+1 */ { return (x*x*x-4*x+1); } float f1(float x) /* Function f1 computes derivative of the function */ { return (3*x*x-4); } float f2(float x)/* Function f2 computes second order derivative of the function */ { return 6*x; } /* Check for termination */

1. *** To find the real roots of the equation x^3-4x+1=0 by Newton Raphson Method *** Enter the initial guess of x closer to root: 3 Iteration no. x 1 2.304348 2 1.967489 3 1.869470 4 1.860871 5 1.860806 6 1.860806 The final root is 1.86081 2. *** To find the real roots of the equation x^3-4x+1=0 by Newton Raphson Method *** Enter the initial guess of x closer to root: -3 Iteration no. x 1 -2.391304 2 -2.154963 3 -2.115946 4 -2.114908 5 -2.114908 The final root is -2.11491

DISCUSSIONS:

1. The program can compute roots of any other non-linear and transcendental equations. We just need to modify the functions f(x), f1(x), and f2(x) according to the new function. 2. The program will fail to compute the root of a function if the derivative of the function for any approximate value of x becomes equal to 0. 3. For every approximate value of x, we should check whether f(x) converges or diverges. If f(x) diverges, then the roots cannot be computed. 4. The Newton-Raphson method works only if we have a functional representation of f(x). Some functions are very difficult to differentiate. 5. If the derivative of a function changes near a tested point, the program may oscillate between those two values of x, resulting in an infinite loop. 6. The library function fabs() is used to calculate the absolute value of differences between two successive values of x.

74

ASSIGNMENT No. 10

PROGRAM STATEMENT:

Write a program to find the value of

Date: 16.12.2009.

using trapezoidal rule and Simpsons 1/3 rule and .

THEORY:

an interval [a, b] of the real line, the definite integral is defined informally to be the net signed area of the region in the xy-plane bounded by the graph of f, the x axis, and the vertical lines x=a, and x=b. If is a continuous real-valued function defined on a closed interval [a, b], then, once an antiderivative F of is known, the definite integral of over that interval is given by Integration is a very important concept in calculus. Given a function f of a real variable x and

and the composite trapezoidal rule is given by ]. Now we find the integration of the function using these rules.

Thus, to evaluate a definite integral we need to know the anti-derivative of the given function. Since it is not a numeric value, it cannot be computed by the computer. So we need to use some numerical method to find the integration of the given function. This is done by composite Simpsons 1/3 integration rule or trapezoidal rule which are defined below. Suppose that the interval [a,b] is split up in n subintervals, with n an even number. Let h be the length of each equal space. Then, the composite Simpson's rule is given by ]

ALGORITHM:

Function Simpson(a, b, h, n) (* This function returns the value of integration of a function f(x) over the interval [a, b]. n is the number of intervals, h is the length of each interval. *) Step 1: [Initialize] , Step 2: [Add the values of the function in the first and last interval] s=f( )+f( ) Step 3: [Add the values of the function in intermediate intervals] for i=1 to n-1 do =a+ih. if i mod 2=1 s=s+4 f( ). else s=s+2 f( ). end of if-else structure. end for. Step 4: [Multiply with h/3 to get final result] s=sh/3. Step 5:[Finished] Return s.

75

Function Trapezoidal(a, b, h, n) (* This function returns the value of integration of a function f(x) over the interval [a, b]. n is the number of intervals, h is the length of each interval. *) Step 1: [Initialize] , Step 2: [Add the values of the function in the first and last interval] s=f( )+f( ) Step 3: [Add the values of the function in intermediate intervals] for i=1 to n-1 do =a+ih. s=s+2 f( ). end for. Step 4: [Multiply with h/2 to get final result] s=sh/2. Step 5:[Finished] Return s.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<math.h> float simpsons(float, float, float, int); float trapezoidal(float, float, float, int); float f(float); int main(void) { float a,b,h,sum1,sum2; int n; printf("\nThis program finds the integral of the function sin((2x)/(1+x)^5) over the range (a,b) over n no. of intervals \n"); printf("\nEnter the no. of intervals:") ; scanf("%d",&n); printf("\nEnter the values of a and b:"); scanf("%f%f",&a,&b); h=(b-a)/n; sum1=simpsons(a,b,h,n); sum2=trapezoidal(a,b,h,n); printf("\nThe value of the integral by Simpson's rule is %f",sum1); printf("\nThe value of the integral by Trapezoidal rule is %f",sum2); getch(); return 0; } float trapezoidal(float a, float b, float h, int n) { float s=0,xi,x0,xn; int i; x0=a; xn=b; s=f(x0)+f(xn); for (i=1;i<n;i++) { xi=a+i*h; s+=2.0*f(xi);

76

} s=s*h/2; return s; } float simpsons(float a, float b, float h, int n) { float s=0,xi,x0,xn; int i; x0=a; xn=b; s=f(x0)+f(xn); for (i=1;i<n;i++) { xi=a+i*h; if (i%2==1) s+=4.0*f(xi); else s+=2.0*f(xi); } s=s*h/3; return s; } float f(float x) { return sin((2*x)/pow(1+x,5)); }

This program finds the integral of the function sin((2x)/(1+x)^5) over the range (a,b) over n no. of intervals Enter the no. of intervals:100 Enter the values of a and b:0 1 The value of the integral by Simpson's rule is 0.114260 The value of the integral by Trapezoidal rule is 0.114243

DISCUSSIONS:

1. If the interval of integration [a, b] is in some sense small, then Simpson's rule will provide an adequate approximation to the exact integral. 2. Simpsons 1/3 rule gives more accurate result than trapezoidal rule. 3. Simpsons 1/3 rule gives exact result for polynomials of degree<=3. 4. The accuracy of the results increase if we increase the value of n, i.e. the accuracy increases by increasing the number of intervals.

77

ASSIGNMENT No. 11

Write a program for matrix inversion method.

Date: 18.12.2009.

PROGRAM STATEMENT:

In mathematics, a matrix is a rectangular array of numbers. An item in a matrix is called an entry or an element. A square matrix is a matrix which has the same number of rows and columns. An n-by-n matrix is known as a square matrix of order n. The inverse of a square matrix A, also called reciprocal matrix is a matrix such that =I, where I is the unit matrix or identity matrix. A square matrix A has an inverse if the determinant |A|0 i.e. the matrix must be non-singular. In general the inverse of the matrix A is defined as: (i,j=1,2,3,,n) are the co-factors of the elements (i,j=1,2,3,,n) in where Adj. of A = and |A| and each is a determinant of order (n-1). But this method requires the evaluation of a number of co-factors or determinants depending upon the number of unknowns. Thus, if the number of unknowns be greater than four and the coefficients of the unknowns are numeric ally large, the above method is not suitable rather will become troublesome due to tremendous computational labour. To avoid this, the inverse of the matrix can be found more easily by Gauss Jordans Matrix Inversion Method. In this method we write the given matrix A and the unit matrix I of same order that of A side by side. Then the matrix A is transferred to unit matrix by Gauss Jordon elimination method. Due to this operation, there is also a change to the unit matrix which was at right side. The modified unit matrix is the inverse of the given matrix after applying Gauss Jordon Elimination method. The steps of finding the inverse of the matrix are illustrated below by considering an example. Let, (1)

THEORY:

where I is the identity matrix, and we use Gauss Jordan Elimination to obtain a matrix of the form (2)

The matrix

(3)

is then the inverse of matrix A. The procedure is numerically unstable unless pivoting (exchanging rows and columns as appropriate) is used.

78 ALGORITHM:

Function MatInv(A,n,X) (* This function returns 1 if the inverse of the matrix is found out and returns 0 if the inverse does not exists. A is input square matrix which has sufficient space to accommodate another square matrix in right hand side. n is the order of input square matrix. X is the resultant inverse matrix *) Step 1: [Augment an unit matrix] for i=1 to n do for j=n+1 to 2n do if ((j-n)=i) then A[i][j]=1 else A[i][j]=0 end of if-else structure. end inner for. end outer for. Step 2: [Initialisation of column counter] i=1. Step 3: [Apply Gauss Jordan elimination] Repeat step 4 to step 9 while i<=n. Step 4: [Find pivot element] if A[i][i]=0 j=i+1. while (j<=n && A[j][i]=0) j=j+1. if (j>=n) Write Input Matrix is singular. Inverse does not exist. Return 0. end if. /* Swap Rows */ for k=i to 2n do swap A[i][k], A[j][k]. end if. Pivot=A[i][i]. Step 5: [Pivotise ith row using pivot element] for k=i to 2n do A[i][k]=A[i][k]/pivot. Step 6: [Eliminate ith column using this pivotised row] k=1. Repeat steps 7 and 8 while k<=n. Step 7: [Elementarise elimination of kth row elements] if (ik) mult=A[k][i]. for j=i to 2n do A[k][j]=A[k][j]-A[i][j]*mult. End for. End if. Step 8: [Update row counter] k=k+1. Step 9: [Update column counter] i=i+1. Step 10: [Separate out the inverse part] for i=1 to n do for j=n+1 to 2n do

79

X[i][j-n]=A[i][j]. Step 11: [Finished] Return 1.

PROGRAM CODE:

/* The a-> n-> x-> */ #include<stdio.h> #include<conio.h> #include<stdlib.h> void matinv(float [50][100],int); int main(void) { int i,j,n; float a[50][100], x[50][50]; printf("\n\t*** Program to find out the inverse of a square matrix ***n\n"); \ /* Input order of matrix n and check for validity of n */ do { printf("\nEnter the order of the square matrix:"); scanf("%d",&n); if (n<1) printf("\nError in input."); } while (n<1); /* Input elements of the matrix */ for (i=0;i<n;i++) { for (j=0;j<n;j++) { printf("\nEnter element in matrix in position(%d,%d):",i+1,j+1); scanf("%f",&a[i][j]); } } matinv(a,n); /* Separate out the inverse part */ for (i=0;i<n;i++) for (j=n;j<2*n;j++) x[i][j-n]=a[i][j]; /* Show inverse of the given matrix */ printf("\nThe inverse of the matrix is: \n\n"); for (i=0;i<n;i++) { for (j=0;j<n;j++) printf("%f ",x[i][j]); printf("\n"); } getch(); return 0; } following program finds the inverse of a matrix using Gauss Jordan method. is the input matrix. is the order of input matrix. is the inverse of given matrix.

80

void matinv(float a[50][100],int n) { int i,j,k; float pivot,mult,temp; /* Augment an unit matrix to a */ for (i=0;i<n;i++) for (j=n;j<2*n;j++) if ((j-n==i)) a[i][j]=1; else a[i][j]=0; /* Applying Gauss Jordan Elimination technique */ for (i=0;i<n;i++) { /* Find pivot element */ if (a[i][i]==0) { j=i+1; while (j<=n && a[j][i]==0) j++; if (j>=n) { printf("\nCoefficient matrix is singular. Inverse of the given matrix does not exist."); getch(); exit(0); } for (k=i;k<2*n;k++) /* Swap Rows*/ { temp=a[i][k]; a[i][k]=a[j][k]; a[j][k]=temp; } }/* End if */ pivot=a[i][i]; for (k=i;k<2*n;k++) a[i][k]=a[i][k]/pivot; /* Pivotising ith row */

for (k=0;k<n;k++) /* Eliminating ith column using pivotised row */ { if (i!=k) { mult=a[k][i]; for (j=i;j<2*n;j++) /* Elementarise elimination of kth row elements */ a[k][j]=a[k][j]-a[i][j]*mult; }/* End if */ }/* End inner for */ }/* End outer for */ }/* End of function */

*** Program to find out the inverse of a square matrix *** Enter the order of the square matrix:3 Enter element in matrix in position(1,1):2 Enter element in matrix in position(1,2):5 Enter element in matrix in position(1,3):3 Enter element in matrix in position(2,1):3 Enter element in matrix in position(2,2):1 Enter element in matrix in position(2,3):2 Enter element in matrix in position(3,1):1 Enter element in matrix in position(3,2):2 Enter element in matrix in position(3,3):-1 The inverse of the matrix is: -0.166667 0.366667 0.233333 0.166667 -0.166667 0.166667 0.166667 0.033333 -0.433333

DISCUSSIONS:

1. Here Gauss Jordan matrix inversion method is applied to find the inverse of the matrix. This is because if the order of the matrix is large then we have to evaluate a large number of cofactors to calculate the inverse of a matrix by the general method which takes more computational time and labour. 2. The algorithm keeps a check on whether the input matrix is singular. If input matrix is singular then the program terminates without further computation because inverse of a singular matrix does not exists. 3. To find the pivot element we check whether the element in pivot position is equal to 0. If it is, then we swap the rows so that a non-zero element comes in pivot position. 4. The size of the input matrix is taken sufficiently large to accommodate another square matrix to the right side.

82

ASSIGNMENT No. 12

PROGRAM STATEMENT:

Date: 23.12.2009.

Write a program to print a normal input string vertically where each character in the output will be in uppercase form.

THEORY:

A string is an character array which contain characters as its element and its end is marked by a special symbol \0 called the null character in C language. To change each character in a string from lowercase to uppercase, we first check whether the character is in lowercase. If it is, then convert it to uppercase by subtracting 32 to its ASCII value. Otherwise, we keep the character unchanged. In each iteration, we convert a lowercase character to uppercase, uppercase characters remaining unchanged; we print the character and go to the next line. Thus the string is printed vertically in the screen. We do this program easily by efficient use of pointers which is a very important concept in C language.

ALGORITHM:

Function PrintVertically(s) (* s is the string to be printed vertically in upper case *) Step 1: [Initialize] i=1. Step 2: [Perform the iteration] Repeat step 3 to step 5 while s[i]NULL. Step 3: [Convert the alphabets that are in lower case] if s[i]>=97 AND s[i]<=122 then s[i]=s[i]-32. End if. Step 4: [Print each character and go to next line] Write s[i]. Go to new line. Step 5: [Update counter] i=i+1. Step 6: [Finished] Return.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<string.h> void PrintVertically(char *a) { char *ptr; ptr=a; while((*ptr)!='\0') { /* Convert the lower case letters to upper case */ if(*ptr>=97 && *ptr<=122) (*ptr)-=32; printf("%c\n",*ptr); ptr++; } } int main(void)

83

{ char *s; printf("\t*** Program to print a string in upper case vertically ***n"); \ /* Input the string */ printf("\nEnter a string : "); gets(s); printf("\nThe uppercase form of the string printed vertically is :n\n"); \ /* Call function to print the string in upper case and vertically */ PrintVertically(s); getch(); return 0; }

*** Program to print a string in upper case vertically *** Enter a string : Alan Turing The uppercase form of the string printed vertically is : A L A N T U R I N G

DISCUSSIONS:

1. 2. 3. 4. If the text contains some special characters then the program will display them unchanged. If there is some blank spaces then in place of the spaces, there will be a blank line. Pointers are used to access each location. Here character pointers are used to store the string. Thus there is no limit to the length of input string. This is an advantage of using character pointers over character arrays.

84

ASSIGNMENT No. 13

PROGRAM STATEMENT:

Write a program to squeeze the blank (more than one) from a given string.

Date: 06.01.2010.

THEORY:

A string is an character array which contain characters as its element and its end is marked by a special symbol \0 called the null character in C language. In this program, if in the input string, there are more than one blanks between words, then we have to remove the extra blanks so that the string becomes a sentence. To implement this in C, we use two pointers; one containing the original string and the other will contain the final output string. Pointers are very important in C language.

ALGORITHM:

Function Squeeze(s) (* This function returns a string s1 which does not contain more than more than 1 blank consecutively. s is the input string *) Step 1: [Initialize an empty string] s1=NULL. Step 2: [Initialize] i=1,j=1. Step 3: [Squeeze the blanks] Repeat step 4 to step 6 while s[i]NULL. Step 4: [If character is not a blank then copy it to final string] if s[i] s1[j]=s[i]. j=j+1. x=0. End if. Step 5: [If the character is the first blank then copy it to the final string] if s[i]= AND x=0 s1[j]=s[i]. j=j+1. x=1. End if. Step 6: [Update counter] i=i+1. Step 7: [Mark an end to final string] s1[i]=NULL. Step 7: [Finished] Return s1.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> char *Squeeze(char *a) { char *b,*ptra,*ptrb; int x=0; b="\0"; ptrb=b; ptra=a; while(*ptra!='\0')

85

{ /* if the character is not a blank then copy it to the final string */ if(*ptra!=' ') { *ptrb=*ptra; ptrb++; x=0; } /* if the character is the first blank then copy it to the final string */ if(*ptra==' ' && x==0) { *ptrb=*ptra; ptrb++; x=1; } ptra++; /* more blanks are not copied */ } /* end of while */ *ptrb='\0'; return b; } int main() { char *s,*p; printf("*** Program to squeeze blank spaces (more than one) in a string *** \n"); printf("\nEnter a string : "); gets(s); printf("\nString entered : %s \n",s); p=Squeeze(s); printf("\nString after squeezing : %s",p); getch(); return 0; }

*** Program to squeeze blank spaces (more than one) in a string *** Enter a string : He String entered : He is is a boy. He went to school. a boy. He went to school.

DISCUSSIONS:

1. The program will also squeeze blank spaces (more than one) given at the front of the string. 2. The program will have no effect on the special characters. It will be restored as before. 3. Here character pointers are used to store the string. Thus there is no limit to the length of input string. This is an advantage of using character pointers over character arrays.

86

ASSIGNMENT No. 14

PROGRAM STATEMENT:

Date: 08.01.2010.

Write a program, which will ask to enter a full name, and it will display as an appropriate short form. Example: Input Mr. Pinaki Ranjan Sinha, Output Mr. P. R. Sinha

THEORY:

A string is an character array which contain characters as its element and its end is marked by a special symbol \0 called the null character in C language. To input a name we need to use a string. Sometimes a full name is often represented by abbreviation. Some examples are given below. Name Ms. Annesha Mukherjee Mr. Sachin Ramesh Tendulkar Sourav Ganguly Tanay Bhaduri Abbreviation Ms. A.Roy Mr. S. R. Tendulkar S. Ganguly T. Bhaduri

ALGORITHM:

Function abbreviation(str) (* str is the input string which contains the full name. strlen() function finds length of string. *) Step 1: [Find length of the string] l=strlen(str). Step 2: [Initialize] c=1. Step 3: [Perform operation to find abbreviated form] for x=1 to l do if str[x]= AND str[x]NULL if str[x-1]=. i=0. while ix do Write str[i]. i=i+1. End while. else Write str[c].. End of if else structure. c=x+1. End if. End for. Step 4: [Finished] Return.

87 PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<string.h> int main(void) { char str[40]; int x,c=0,l,i; printf("\nEnter the name: "); gets(str); l=strlen(str); printf("\n\nThe abbreviated form is: \n"); for(x=0;x<=l;x++) { if(str[x]==' '&&(str[x]!=' \0')) { if(str[x-1]=='.') { i=0; while(i!=x) printf("%c",str[i++]); } else printf("%c. ",str[c]); c=x+1; } } for(x=c;x<=l;x++) printf("%c",str[x]); getch(); return 0; }

Enter the name: Mr. Sourav Chandi Ganguly The abbreviated form is: Mr.S. C. Ganguly

DISCUSSIONS:

1. Here the library function strlen() is used to compute the string. Thus we do not have to write a code to calculate the length ourselves. strlen() function is in file string.h. This makes the program simpler. 2. This program uses a character array to store string. Thus, user must be aware of the boundary limit of the array and cannot input larger names without modifying the size of the array. This problem would not have arisen if character pointer was used to keep the string in memory.

88

ASSIGNMENT No. 15

PROGRAM STATEMENT:

Date: 15.01.2010.

Write a program to find the minimum spanning tree of a given weighted graph using Prims algorithm.

THEORY:

A graph G is an ordered pair (V,E) where V is finite non-empty set, called the set of vertices and E is a finite set (may be empty) whose elements are called edges (or arcs) such that each edge is identified with a pair (u, v) of vertices. A graph may be undirected, meaning that there is no distinction between the two vertices associated with each edge, or its edges may be directed from one vertex to another. A weighted graph associates a weight with every edge in the graph. Weights are usually real numbers. They may be restricted to rational numbers or integers. The weight of a path or the weight of a tree in a weighted graph is the sum of the weights of the selected edges. Sometimes a non-edge is labelled by a special weight representing infinity. Sometimes the word cost is used instead of weight. A graph is said to be connected if there is at least one path between every pair of vertices in the graph. A connected graph without any circuits is called a tree. A tree T is said to be spanning tree of a graph G if T is a subgraph of G, and T contains all the vertices of G. A spanning tree is called a minimum spanning tree if the weight of T is minimum. There are different ways to store graphs in a computer system. The data structure used depends on both the graph structure and the algorithm used for manipulating the graph. Theoretically one can distinguish between list and matrix structures but in concrete applications the best structure is often a combination of both. List structures are often preferred for sparse graphs as they have smaller memory requirements. Matrix structures on the other hand provide faster access for some applications but can consume huge amounts of memory.The list structures are incidence list and adjacency list and the matrix structures are incidence matrix, adjacency matrix, etc. Prim's algorithm is an algorithm that finds a minimum spanning tree for a connected weighted undirected graph. This means it finds a subset of the edges of the graph that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. In the Prims algorithm we use the weighted adjacency matrix to represent the graph. Now the algorithm is as follows.

ALGORITHM:

Function Prims (graph, tree, n) (* graph is the weighted adjacency matrix in which the non-edges are represented by . tree is an adjacency matrix of same order of graph which stores resultant spanning tree. n is the number of vertices in the graph. *) Step 1: [Initially do not select any vertex] for i=1 to n do select[i]=FALSE. End for. Step 2: [Make tree empty] for i=1 to n do for j=1 to n do tree[i][j]=0. End for. End for. Step 3: [Select first vertex] select[1]=TRUE. Step 4: [Initialize edge counter] edge=1. Step 5: [Compute the spanning tree]

89

Repeat step 6 to step 10 while edge<n. Step 6: [Initialize infinite value to min] min=. Step 7: [Find minimum edge from the selected vertices that are not already taken] for i=1 to n do if select[i]=TRUE then for j=1 to n do if select[j]=FALSE then if min>graph[i][j] then min=graph[i][j]. x=i. y=j. End if. End if. End for. End if. End for. Step 8: [Insert the minimum edge to matrix tree] tree[x][y]=graph[x][y]. Step 9: [Make the other end vertex of the minimum edge to selected] select[y]=TRUE. Step 10: [Update counter] edge=edge+1. Step 11: [Finished] Return tree.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #define MAX 20 #define INFINITY 32767 void prims(int [MAX][MAX], int [MAX][MAX], int); int main(void) { int i,j,w,n,graph[MAX][MAX],tree[MAX][MAX]; printf("*** Program to find the minimum spanning tree of a weighted graph by Prim's algorithm ***\n"); printf("\nEnter the number of vertices in the graph:"); scanf("%d",&n); /* Assign infinite weight to all edges of graph and zero to all edges of tree */ for (i=1;i<=n;i++) for (j=1;j<=n;j++) { graph[i][j]=INFINITY; tree[i][j]=0; } /* Input the different edges */ printf("\nInput the edges of graph in the format [vertex1 vertex2 weight]:n"); \ do { printf("\nInput edge [0 0 0 to exit]:",i); scanf("%d %d %d",&i,&j,&w); graph[i][j]=w; } while (i!=0 && j!=0 && w!=0); prims(graph,tree,n);

90

/* Show output */ printf("\nThe edges of the minimum spanning tree of the graph a e:\n"); r for (i=1;i<=n;i++) for (j=1;j<=n;j++) if (tree[i][j]!=0) { printf("\nOne edge is between vertex %d and vertex %d with weight %d.\n",i,j,graph[i][j]); w=w+graph[i][j]; } printf("\nThe minimum cost of the spanning tree is %d.",w); getch(); return 0; } void prims(int graph[MAX][MAX], int tree[MAX][MAX], int n) { int select[MAX],edge,i,j,x,y,min; /* Initially do not select any vertex */ for (i=1;i<=n;i++) select[i]=0; /* Select first vertex and initialise edge counter */ select[1]=1; edge=1; /* Continue loop untill all n -1 edges of the spanning tree are found */ while (edge<n) { min=INFINITY; /* Initia lize infinte distance to min variable */ for (i=1;i<=n;i++) { if (select[i]==1) /* Choose a vertex which is selected */ for (j=1;j<=n;j++) if (select[j]==0) /* If vertex j is not selected * / if (min>graph[i][j]) /* If edge exists at position i,j */ { min=graph[i][j]; /* Assign weight of edge to min */ x=i; /* Hold row position of minimum edge to x */ y=j; /* Hold column position of minimum edge to y */ } } tree[x][y]=graph[x][y]; /* Insert the minimum edge to tree */ select[y]=1; /* The other vertex of the edge is selected */ edge++; /* Increment edge */ }/* end while */ }/* end prims */

*** Program to find the minimum spanning tree of a weighted graph by Prim's algorithm *** Enter the number of vertices in the graph:6 Input the edges of graph in the format [vertex1 vertex2 weight]: Input edge [0 0 0 to exit]:1 2 16 Input edge [0 0 0 to exit]:2 3 5 Input edge [0 0 0 to exit]:2 4 6

91

Input edge [0 0 0 to exit]:3 4 10 Input edge [0 0 0 to exit]:1 6 21 Input edge [0 0 0 to exit]:2 6 11 Input edge [0 0 0 to exit]:4 6 14 Input edge [0 0 0 to exit]:4 5 18 Input edge [0 0 0 to exit]:1 5 19 Input edge [0 0 0 to exit]:5 6 33 Input edge [0 0 0 to exit]:0 0 0 The edges of the minimum spanning tree of the graph are: One edge is between vertex 1 and vertex 2 with weight 16. One edge is between vertex 2 and vertex 3 with weight 5. One edge is between vertex 2 and vertex 4 with weight 6. One edge is between vertex 2 and vertex 6 with weight 11. One edge is between vertex 4 and vertex 5 with weight 18. The minimum cost of the spanning tree is 56.

DISCUSSIONS:

1. The complexity of Prims algorithm is O( ) in the worst case. 2. Since adjacency matrix is used to represent the weighted graph, there is a possibility of sparse matrix when the number of edges is small. In those cases a great deal of space is wasted.

3. This implementation assumes cost 32767 as infinite cost. None of the costs can be greater than or equal to 32767.

4. Prims algorithm is a solution to the travelling salesman problem. It enables the salesman to find the shortest route from the minimum spanning tree. 5. In this program, the graph is represented by an adjacency matrix. Graphs can also be represented by adjacency list.

92

ASSIGNMENT No. 16

PROGRAM STATEMENT:

Date: 22.01.2010.

Write a program to find the shortest distance between any vertex to any vertex in a weighted connected graph by using Floyds algorithm.

THEORY:

A graph G is an ordered pair (V,E) where V is finite non-empty set, called the set of vertices and E is a finite set (may be empty) whose elements are called edges (or arcs) such that each edge is identified with a pair (u, v) of vertices. A graph may be undirected, meaning that there is no distinction between the two vertices associated with each edge, or its edges may be directed from one vertex to another. A weighted graph associates a weight with every edge in the graph. Weights are usually real numbers. They may be restricted to rational numbers or integers. The weight of a path or the weight of a tree in a weighted graph is the sum of the weights of the selected edges. Sometimes a non-edge is labelled by a special weight representing infinity. Sometimes the word cost is used instead of weight. A graph is said to be connected if there is at least one path between every pair of vertices in the graph. There are different ways to store graphs in a computer system. The data structure used depends on both the graph structure and the algorithm used for manipulating the graph. Theoretically one can distinguish between list and matrix structures but in concrete applications the best structure is often a combination of both. List structures are often preferred for sparse graphs as they have smaller memory requirements. Matrix structures on the other hand provide faster access for some applications but can consume huge amounts of memory.The list structures are incidence list and adjacency list and the matrix structures are incidence matrix, adjacency matrix, etc. Floyds algorithm determines the shortest route between any two nodes in the network. The algorithm represents n node network as a square matrix with n rows and n columns. Entry (i,j) of the matrix is finite if vertex i is linked to vertex j, and infinite otherwise. The idea of Floyds algorithm is straight forward. Given three nodes i, j, and k in the above figure with the connecting distances shown on the three arcs, it is shorter to reach k from i passing through i if . In this case it is optimal to replace the direct route from i k with indirect route i j k. The triple operation exchange is applied systematically to the networ using the k following algorithm.

ALGORITHM:

Function Floyd(d, s, n) (* This algorithm finds the minimum distance and the sequence of nodes to be traversed in the form of matrix between every vertex to every other vertex. d is the distance matrix which is finite if vertex i is linked to j and otherwise contains , s is the node sequence matrix whose elements are =j for all j. *) Step 1: [Apply triple operation for each element] for k=1 to n do for i=1 to n do if d[i][k]< for j=1 to n do if d[k][j]< sum=d[k][j]+d[i][j]. if sum<d[i][j] d[i][j]=sum. s[i][j]=k. end if. End if.

93

End for.

End if.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> void floyds(int [10][10], int [10][10], int); int main(void) { int d[10][10],s[10][10],i,j,n; printf("*** Program to implement Floyd's algorithm *** n"); \ /* Input part */ printf("\nEnter the number of vertices in graph:"); scanf("%d",&n); for (i=0;i<n;i++) { for (j=0;j<n;j++) { if (i!=j) { printf("\nEnter distance between vertex %d and vertex %d (Put 32767 if there is no edge in between):",i+1,j+1); scanf("%d",&d[i][j]); s[i][j]=j+1; } } } floyds(d,s,n); /* Print final distance matrix */ printf("\nThe output distance matrix is : \n"); for (i=0;i<n;i++) { for (j=0;j<n;j++) printf("%3d ",d[i][j]); printf("\n"); } /* Print final node sequence matrix */ printf("\nThe output node sequence matrix is : \n"); for (i=0;i<n;i++) { for (j=0;j<n;j++) printf("%3d ",s[i][j]); printf("\n"); } getch(); return 0; } void floyds(int d[10][10],int s[10][10],int n) { int i,j,k,sum;

94

for (k=0;k<n;k++) { for (i=0;i<n;i++) { if (d[i][k]<32767) for (j=0;j<n;j++) { if (d[k][j]<32767) { sum=d[k][j]+d[i][k]; if (sum<d[i][j]) { d[i][j]=sum; /* Modifying distance matrix */ s[i][j]=k+1; /* Modifying node sequence matrix */ } } } } } for (i=0;i<n;i++) { d[i][i]=0; s[i][i]=0; } } /* Making the distance 0 between same vertex */

*** Program to implement Floyd's algorithm *** Enter the number of vertices in graph:5 Enter distance between vertex 1 and vertex 2 (Put 32767 if there is no edge in between):3 Enter distance between vertex 1 and vertex 3 (Put 32767 if there is no edge in between):10 Enter distance between vertex 1 and vertex 4 (Put 32767 if there is no edge in between):32767 Enter distance between vertex 1 and vertex 5 (Put 32767 if there is no edge in between):32767 Enter distance between vertex 2 and vertex 1 (Put 32767 if there is no edge in between):3 Enter distance between vertex 2 and vertex 3 (Put 32767 if there is no edge in between):32767 Enter distance between vertex 2 and vertex 4 (Put 32767 if there is no edge in between):5 Enter distance between vertex 2 and vertex 5 (Put 32767 if there is no edge in between):32767 Enter distance between vertex 3 and vertex 1 (Put 32767 if there is no edge in between):10 Enter distance between vertex 3 and vertex 2 (Put 32767 if there is no edge in between):32767 Enter distance between vertex 3 and vertex 4 (Put 32767 if there is no edge in between):6 Enter distance between vertex 3 and vertex 5 (Put 32767 if there is no edge in between):15 Enter distance between vertex 4 and vertex 1 (Put 32767 if there is no edge in between):32767 Enter distance between vertex 4 and vertex 2 (Put 32767 if there is no edge in between):5

95

Enter distance between vertex 4 and vertex 3 (Put 32767 if there is no edge in between):6 Enter distance between vertex 4 and vertex 5 (Put 32767 if there is no edge in between):4 Enter distance between vertex 5 and vertex 1 (Put 32767 if there is no edge in between):32767 Enter distance between vertex 5 and vertex 2 (Put 32767 if there is no edge in between):32767 Enter distance between vertex 5 and vertex 3 (Put 32767 if there is no edge in between):32767 Enter distance between vertex 5 and vertex 4 (Put 32767 if there is no edge in between):4 The output distance matrix is : 0 3 10 8 12 3 0 11 5 9 10 11 0 6 10 8 5 6 0 4 12 9 10 4 0 The output node sequence matrix is : 0 2 3 2 4 1 0 4 4 4 1 4 0 4 4 2 2 3 0 5 4 4 4 4 0

DISCUSSIONS:

1. The complexity of Floyds algorithm is O( ). 2. Floyds algorithm finds the shortest path from any vertex to any vertex in a graph. 3. The number of inputs in the above program is . Thus even if the number of edges is much than we will have to put 0 for all the edges that do not exist. This is time consuming and boring. 4. Since adjacency matrix is used to represent the weighted graph, there is a possibility of sparse matrix when the number of edges is small. In those cases a great deal of space is wasted. 5. This implementation assumes cost 32767 as infinite cost. None of the costs can be greater than or equal to 32767. 6. Floyds algorithm is a solution to the travelling salesman problem. It enables the salesman to find the shortest route from the minimum spanning tree. 7. In this program, the graph is represented by an adjacency matrix. Graphs can also be represented by adjacency list.

96

ASSIGNMENT No. 17

PROGRAM STATEMENT:

Date: 27.01.2010.

Write a program to implement Dijkstras method to calculate shortest distance from one vertex to all vertices in a directed or undirected graph.

THEORY:

Dijkstra's algorithm is a graph search algorithm that solves the single-source shortest path problem for a graph with nonnegative edge path costs, producing a shortest path tree. This algorithm is often used in routing. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined. For example, if the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols. Dijkstras algorithm labels the vertices of a given connected graph. At each stage in the algorithm, some vertices have permanent labels and others temporary labels. The algorithm begins by assigning a permanent label to the starting vertex, and the temporary label to the remaining (n -1) vertices. From then on, in each iteration another vertex gets permanently label, acc ording to the following rules. 1. Every vertex j that is not yet permanently labeled gets a new temporary label whose value is given by min[old label of j, (old label of i + )], where i is the latest vertex permanent labeled in the previous iteration, and is the direct distance between vertices i and j. If i and j are not joined by an edge, then . 2. The smallest value among all the temporary label is found, and this becomes the permanent label of the corresponding vertex. In case of a tie, we select any one of the vertex for permanent labeling. Steps 1 and 2 are repeated alternately until all vertices get permanently labeled.

ALGORITHM:

Function Dijkstra(d,n,s) (* This algorithm returns the minimum distance of all other vertex from the starting vertex s. d is the weighted adjacency matrix, n is the number of vertices in the graph, and s is the starting vertex. *) Step 1: [Initialize] label=, label[s]=0, status=0, status[s]=1, i=s. Step 2: [Perform the iteration] Repeat step 3 to step 6 while TRUE. Step 3: [Check if all the labels are permanent] for k=1 to n do if status[k]=0 Go to step 4. End if. End for. Goto Step 7. Step 4: [Initialize min to infinite value] min=. Step 5: [Compute labels of all vertices that are not permanently labeled that can be reached fromvertex i]

97

for j=1 to n do if status[j]=0 z=d[i][j]+label[i]. if z<label[j] label[j]=z. end inner if. if label[j]<min min=label[j]. p=j. end inner if. end outer if. end for. Step 6: [Change the temporary label with minimum distance as permanent and assign it as the new source vertex] status[p]=1. i=p. Step 7: [Finished] Return label.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #define INFINITY 32767 void dijkstra(int [10][10], int [10], int s, int n); int main(void) { int d[10][10],i,j,n,s,label[10]; printf("*** Program to find the minimum distance between source node and every other node by Dijkstra's method *** \n\n"); /* Input part */ printf("\nEnter the number of vertices in graph:"); scanf("%d",&n); for (i=0;i<n;i++) { for (j=0;j<n;j++) { if (i!=j) { printf("\nEnter distance from vertex %d to vertex %d (Put 0 if there is no edge in between):",i+1,j+1); scanf("%d",&d[i][j]); } else d[i][j]=0; } } printf("\nEnter the source vertex:"); scanf("%d",&s); dijkstra(d,label,s,n); /* Showing output */ for (i=0;i<n;i++) if (i!=s-1) printf("\nThe minimum %d",i+1,label[i]); getch();

distance

of

vertex

%d

from

source

vertex

is

98

return 0; } void dijkstra(int d[10][10],int label[10],int s,int n) { int status[10]={0},i,j,k,min,z,p ,flag; /* Initialise labels of all nodes to infinite value */ for (i=0;i<n;i++) label[i]=INFINITY; label[s-1]=0; status[s-1]=1; i=s-1; while (1) { /* Checking whether all labels are permanent */ for (k=0;k<n;k++) { if (status[k]==0) { flag=0; break; } else flag=1; } if (flag==1) /* if all labels are permanent then return */ return; min=INFINITY; for (j=0;j<n;j++) { /* If label j is temporary & edge exists between ith and jth vertex */ if (status[j]==0 && d[i][j]!=0) { /* Compute the distance between vertex i and vertex j */ z=d[i][j]+label[i]; /* If distance computed is less than label o vertex j */ f if (z<label[j]) label[j]=z; /* Assign new distance to label j */ } /* Find minimum of all the temporary labels */ if (status[j]==0) if (label[j]<min) { min=label[j]; /* Find temporary label with minimum distance */ p=j; /* Hold the vertex with minimum distance in p */ } } status[p]=1; /* Change temporary label to permanent label */ i=p; /* p is assigned to i which is now the new starting node */ }/* end while */ }/* end function */ /* Starting node is labelled 0 */ /* Assign permanent label to starting n ode */

*** Program to find the minimum distance between source node and every other node by Dijkstra's method *** Enter the number of vertices in graph:5 Enter distance from vertex 1 to vertex 2 (Put 0 if there is no edge in between):100 Enter distance from vertex 1 to vertex 3 (Put 0 if there is no edge in between):30 Enter distance from vertex 1 to vertex 4 (Put 0 if there is no edge in between):0 Enter distance from vertex 1 to vertex 5 (Put 0 if there is no edge in between):0 Enter distance from vertex 2 to vertex 1 (Put 0 if there is no edge in between):0 Enter distance from vertex 2 to vertex 3 (Put 0 if there is no edge in between):20 Enter distance from vertex 2 to vertex 4 (Put 0 if there is no edge in between):0 Enter distance from vertex 2 to vertex 5 (Put 0 if there is no edge in between):0 Enter distance from vertex 3 to vertex 1 (Put 0 if there is no edge in between):0 Enter distance from vertex 3 to vertex 2 (Put 0 if there is no edge in between):0 Enter distance from vertex 3 to vertex 4 (Put 0 if there is no edge in between):10 Enter distance from vertex 3 to vertex 5 (Put 0 if there is no edge in between):60 Enter distance from vertex 4 to vertex 1 (Put 0 if there is no edge in between):0 Enter distance from vertex 4 to vertex 2 (Put 0 if there is no edge in between):15 Enter distance from vertex 4 to vertex 3 (Put 0 if there is no edge in between):0 Enter distance from vertex 4 to vertex 5 (Put 0 if there is no edge in between):50 Enter distance from vertex 5 to vertex 1 (Put 0 if there is no edge in between):0 Enter distance from vertex 5 to vertex 2 (Put 0 if there is no edge in between):0 Enter distance from vertex 5 to vertex 3 (Put 0 if there is no edge in between):0 Enter distance from vertex 5 to vertex 4 (Put 0 if there is no edge in between):0 Enter the source vertex:1 The minimum distance of vertex 2 from source vertex is 55 The minimum distance of vertex 3 from source vertex is 30 The minimum distance of vertex 4 from source vertex is 40 The minimum distance of vertex 5 from source vertex is 90

100 DISCUSSIONS:

1. The number of inputs in the above program is . Thus even if the number of edges is much than we will have to put 0 for all the edges that do not exist. This is time consuming and boring. 2. Since adjacency matrix is used to represent the weighted graph, there is a possibility of sparse matrix when the number of edges is small. In those cases a great deal of space is wasted. 3. The complexity of the above algorithm is O( . 4. This algorithm only works for non-negative costs.

5. This implementation assumes cost 32767 as infinite cost. None of the costs can be greater than or equal to 32767.

6. This algorithm finds minimum cost path of all vertices starting from the initial vertex. The result can be used to represent it by a spanning tree form. 7. Dijkstras algorithm is only applicable to connected graphs. 8. If the vertices of the graph represent cities and edge path costs represent driving dist nces a between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. Thus it can be used a solution to the travelling salesman problem. As a result, the shortest path first is widely used in network routing protocols.

101

ASSIGNMENT No. 18

PROGRAM STATEMENT:

Write a program to create a circular queue using an array and do the following a. Initialise the queue. b. Insert elements to the queue. c. Delete elements from the queue.

Date: 29.01.2010.

THEORY:

A queue is an ordered collection of items from which items may be deleted at one end (called the front of the queue) and into which items may be inserted at the other end (called the rear of the queue). Queues are called first-in-first-out (FIFO) data-structures. Queues can be represented in computer in various ways, usually by array or linked lists. To create a queue using array we generally maintain an array with two pointers, one pointing to the front element of the queue and other pointing to the rear element of the queue. A circular queue is a queue in which the first location of the array comes after the last location of the array. It is a more general queue and it has the advantage tha we can continue inserting t elements till the queue is full. Two operations can be applied to a queue. They are a. Inserting elements to the queue. b. Delete elements from the queue. The insert operation can always be performed, but is dependent to the upper limit of the array. When the array is full, and we try to insert a new element, it is called overflow. Similarly the result of an illegal attempt to remove an element from an empty queue is called underflow.

ALGORITHM:

The algorithm has two parts i.e. the functions QINSERT (for inserting elements) and QDELETE (for deleting elements). Now, the algorithm follows. Function QINSERT(queue,n,front,rear,item) Step 1: [Check if queue is full] if front=1 and rear=n, or if front=rear+1, then: Write: Overflow. Return. End if. Step 2: [Find new value of rear] if front=NULL, then set front=1 and rear=1. else if rear=n, then set rear=1. else set rear=rear+1. [End of if-else structure] Step 3: [Insert item to queue] Set queue[rear]=item. Step 4: [Finished] Return. Function QDELETE(queue,n,front,rear,item)

102

Step 1: [Check if queue is already empty] if front=NULL then: Write: Underflow. Return. End if. Step 2: [Delete front element of queue] Set item=queue[front]. Step 3: [Find new value of front] if front=rear, then [queue has only one element to start.] set front=NULL and rear=NULL. else if front=n, then set front=1. else set front=front+1. [End of if-else structure] Step 4: [Finished] Return.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #define MAX 5 int queue[MAX],front= -1,rear=-1; /* Global declaration of queue and its pointers front and rear are initialised to -1 */ void qinsert(int item) { /* Insert element to queue */

/* Check if queue is full */ if (front==0 && rear==MAX-1 || front==rear+1) { printf("\nCircular Queue overflow. \n"); return; } /* Find new position of front and rear */ else if (front==-1) { front=0; rear=0; } else if (rear==MAX -1) rear=0; else rear++; queue[rear]=item; } int qdelete() { /* Delete elements from queue */ /* Insert item to queue */ /* If last element points to end of queue */ /* if queue is empty */

103

int item; if (front==-1) { printf("\nCircular queue underflow. \n"); getch(); exit (0); } item=queue[front]; /* Delete front element of queue */ /* Check if queue is empty */

/* Find new positio of front and rear */ n if (front==rear) /* If there is only one element in queue */ { rear=-1; front=-1; } else if (front==MAX -1)/* If front element is at the end of the queue */ front=0; else front++; return item; } int main(void) { int ch,num,display; printf("\n\t *** Program to create a circular queue using an array ***n"); \ while (1) { printf("\n1.Insert element queue\n3.Exit\n\nEnter your choice:"); scanf("%d",&ch); if (ch==3) break; else if (ch==1) { printf("\nEnter element to insert:"); scanf("%d",&num); qinsert(num); } else if (ch==2) { display=qdelete(); printf("\nNo. deleted is %d\n",display); } to queue\n2.Delete element from

104

else printf("\nWrong key pressed."); } /* End while */ getch(); return 0; }

*** Program to create a circular queue using an array *** 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:1 Enter element to insert:1 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:1 Enter element to insert:2 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:1 Enter element to insert:3 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:1 Enter element to insert:4 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:1

105

Enter element to insert:5 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:1 Enter element to insert:6 Circular Queue overflow. 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:2 No. deleted is 1 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:2 No. deleted is 2 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:2 No. deleted is 3 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:2 No. deleted is 4 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:2

106

No. deleted is 5 1.Insert element to queue 2.Delete element from queue 3.Exit Enter your choice:2 Circular Queue underflow.

DISCUSSIONS:

1. In this program the queue size is fixed. We cannot change the size of the queue at run-time. 2. Circular Queue can also be implemented by using linked lists instead of an array. A linked circular queue has the advantage of increasing the number of elements dynamically and no space is wasted. 3. A queue is an important data structure which is often used in different algorithms.

107

ASSIGNMENT No. 19

PROGRAM STATEMENT:

Simulate different sorting technique using menu driven program: a) Quick sort (using non recursive fashion) b) Selection sort c) Insertion sort d) Bubble sort e) Merge sort (using non recursive fashion) f) Heap sort (using non recursive fashion) g) Radix sort

Date: 03.02.2010.

THEORY:

Asorting algorithm is an algorithm that puts elements of a list in a certain order. The mostused orders are numerical order and lexicographical order. Efficient sorting is important to optimizing the use of other algorithms (such as search and merge algorithms) that require sorted lists to work correctly. More formally, the output must satisfy two conditions: 1. The output is in non-decreasing order (each element is no smaller than the previous element according to the desired total order); 2. The output is a reordering of the input. The most common sorting techniques are quick sort, selection sort, insertion sort, bubble sort, merge sort, heap sort, and radix sort. They can be implemented in both recursive and non-recursive manner. They are discussed in short below. Quicksort is a divide and conquer algorithm which relies on a partition operation: to partition an array, we choose an element, called a pivot, move all smaller elements before the pivot, and move all greater elements after it. This can be done efficiently in linear time and in-place. Then we recursively sort the lesser and greater sub-lists. However it can be implemented non recursively also by maintain two stacks which keep track of the different sub-lists to be executed next. Efficient implementations of quicksort (with in-place partitioning) are typically unstable sorts and somewhat complex, but are among the fastest sorting algorithms in practice. Together with its modest O(log n) space usage, this makes quicksort one of the most popular sorting algorithms, available in many standard libraries. The most complex issue in quicksort is choosing a good pivot element; consistently poor choices of pivots can result in drastically slower O(n ) performance, but if at each step we choose the median as the pivot then it works in O(n log n). Finding the median, however, is an O(n) operation on unsorted lists, and therefore exacts its own penalty. Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.In this algorithm, we find the minimum value in the list, then swap it with the value in the first position. Then we repeat the steps above for the remainder of the list (starting at the second position and advancing each time). Insertion sort is a simple sorting algorithm that is relatively efficient for small lists and mostly-sorted lists, and often is used as part of more sophisticated algorithms. It works by taking elements from the list one by one and inserting them in their correct position into a new sorted list. In arrays, the new list and the remaining elements can share the array's space, but insertion is expensive, requiring shifting all following elements over by one.

108

Bubble sort is a straightforward and simplistic method of sorting data that is used in computer science education. The algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, then it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass. This algorithm is highly inefficient, and is rarely used,except as a simplistic example. For example, if we have 100 elements then the total number of comparisons will be 10000. Merge sort takes advantage of the ease of merging already sorted lists into a new sorted list. It starts by comparing every two elements (i.e., 1 with 2, then 3 with 4...) and swapping them if the first should come after the second. It then merges each of the resulting lists of two into lists of four, then merges those lists of four, and so on; until at last two lists are merged into the final sorted list. Of the algorithms described here, this is the first that scales well to very large lists, because its worst-case running time is O(n log n). Merge sort has seen a relatively recent surge in popularity for practical implementations. Heap sort is a much more efficient version of selection sort. It also works by determining the largest (or smallest) element of the list, placing that at the end (or beginning) of the list, then continuing with the rest of the list, but accomplishes this task efficiently by using a data structure called a heap, a special type of binary tree. Once the data list has been made into a heap, the root node is guaranteed to be the largest(or smallest) element. When it is removed and placed at the end of the list, the heap is rearranged so the largest element remaining moves to the root. Using the heap, finding the next largest element takes O(log n) time, instead of O(n) for a linear scan as in simple selection sort. This allows Heap sort to run in O(n log n) time, and this is also the worst case complexity. Radix sort is an algorithm that sorts a list of fixed-size numbers of length k in O(n k) time by treating them as bit strings. We first sort the list by the least significant bit while preserving their relative order using a stable sort. Then we sort them by the next bit, and so on from right to left, and the list will end up sorted. Most often, the counting sort algorithm is used to accomplish the bitwise sorting, since the number of values a bit can have is minimal - only '1' or '0'. The efficiency of each sorting algorithm depends on the number of items in the list, and in what order the elements are already in the list. Now we give the algorithm of these sorting techniques for arranging a numbers in ascending order below.

ALGORITHM:

(* In all the sorting algorithms below A is the array of elements and n is the number of elements in array. *) Quick sort Function quicksort(A, n) Step 1: [Initialize stack counter] top=0. Step 2: [Insert the first position and last position of the array to two stack] lower[1]=1, upper[1]=n. Step 3: [Perform the iteration to continue partitioning of list until the stack is empty] Repeat while top0. Step 4: [Pop partition from stack] beg=lower[top]. end=upper[top]. top=top-1. Step 5: [Find correct position of a particular element within the popped partition] pos=quick(A,beg,end).

109

Step 6: [Push partition to left of pos to stack if it contains more than one element] if beg<pos-1 top=top+1. lower[top]=beg. upper[top]=pos-1. End if. Step 7: [Push partition to right of pos to stack if it contains more than one element] if pos<end-1 top=top+1. lower[top]=pos+1. upper[top]=end. End if. [End of step 3 loop]. Step 8: [Finished] Return. Function quick(A, left, right) Step 1: [Select pivot element] pos=left. Step 2: [Find the correct position of the pivot element] Repeat while TRUE. Step 3: [Scan partition from right to left] while (A[pos]<A[right] AND posright) do right=right-1. End while. Step 4: [If correct position of pivot element is found then return the position else interchange A[pos] and A[right] and assign right as the new position of pivot element] if pos=right Go to step 7. else Swap(A[pos],A[right]). pos=right. End of if-else. Step 5: [Scan partition from left to right] while (A[pos]>=A[left] AND posleft) do left=left+1. End while. Step 6: [If correct position of pivot element is found then return the position else interchange A[pos] and A[left] and assign right as the new position of pivot element] if pos=left Go to step 7. else Swap(A[pos],A[left]). pos=left. End of if-else. [End of step 2 loop] Step 7: [Finished] Return pos. Selection sort Function ssort(A, n)

110

Step 1: [Initialize] i=1. Step 2: [Find the actual element to be placed at position i] Repeat while i<n. Step 3: [Initialize min to ith element] min=a[i], pos=i. Step 4: [Find the minimum element of the rest of list starting from position i] for j=i+1 to n do if A[j]<min min=A[j]. pos=j. end if. end for. Step 5: [Swap the minimum element with ith element] temp=A[i]. A[i]=A[pos]. A[pos]=temp. Step 6: [Update counter] i=i+1. [End of Step 2 loop] Step 7: [Finished] Return. Insertion sort Function isort(A, n) Step 1: [Initialize] k=2. Step 2: [Select k-th element] Repeat while k<=n. Step 3: [Hold the value of k-th element in a temporary variable] Temp=A[k]. Step 4: [Move i-th element to (i+1)th position till the actual position of temp is found] for i=k-1 down to 1 if temp<A[i] A[i+1]=A[i]. else Go to step 5. End if. End for. Step 5: [Insert temp into its new position] A[i+1]=temp. Step 6: [Update element counter] k=k+1. [End of step 2 loop] Step 7: [Finished] Return. Bubble sort Function bsort(A, n) Step 1: [Initialize]

111

flag=1,i=1. Step 2: [Execute each pass] Repeat while i<=n-1 AND flag=1. Step 3: [Initialize flag to 0 at beginning of pass] flag=0. Step 4: [Compare j-th and (j+1)th element in pass I and swap if they are not in order] for j=1 to n-i-1 if A[j+1]<A[j] flag=1. Swap(A[j+1],A[j]). End if. End for. Step 5: [Update pass counter] i=i+1. [End of step 2 loop] Step 6: [Finished] Return. Merge sort Function mergesort(A, n) Step 1: [Initialize size of each file to 1] size=1. Step 2: [Continue merging files till size of each file becomes equal to or greater than n] Repeat while size<n. Step 3: [Initialize lower boundary of first file and index of temporary array] l1=1, k=1. Step 4: [Check to see if there are two files to merge and merge them] Repeat while l1+size<n. Step 5: [Compute lower boundary of second file to merge] l2=l1+size. Step 6: [Compute upper boundary of first file to merge] u1=l2-1. Step 7: [Compute upper boundary of second file to merge] if l2+size-1<n u2=l2+size-1. else u2=n-1. End of if else. Step 8: [Initialize] i=l1, j=l2. Step 9: [Merge two files till one sub file gets exhausted] Repeat while i<=u1 AND j<=u2. Step 10: [Insert smaller element of the elements of two files to temporary array and update counter] if A[i]<A[j] temp[k]=A[i]. k=k+1. i=i+1. else temp[k]=A[j]. k=k+1.

112

j=j+1. End if else. [End of Step 9 loop]. Step 11: [Copy remaining contents of first file, if any] while i<=u1 temp[k]=A[i]. k=k+1. i=i+1. End while. Step 12: [Copy remaining contents of second file, if any] while j<=u2 temp[k]=A[j]. k=k+1. j=j+1. End while. Step 13: [Compute lower bound of first file of next two files to be merged] l1=u2+1. [End of step 4 loop] Step 14: [Copy any remaining single file] i=l1. while k<=n temp[k]=A[i]. k=k+1. i=i+1. End while. Step 15: [Copy contents of temporary array back to original array] for i=1 to n do A[i]=temp[i]. End for. Step 16: [Increase size of each file] size=size2. [End of step 2 loop] Step 17: [Finished] Return. Heap sort Function heapsort(A, n) Step 1: [Create heap structure] buildheap(A, n) Step 2: [Generate sorted structure] while TRUE do Swap(A[1],A[n]) n=n-1. if n=1 Return. Reheap(A, n). End while. Step 3: [Finished] Return. Function buildheap(A, n)

113

Step 1: [Insert all elements starting from 2nd element to the respective heaps] k=2. Repeat step 2 to step 3 while k<=n do. Step 2: [Insert the current element] i=k. while TRUE do p=I/2. if A[p]>A[i] Go to step 3. End if. Swap(A[p],A[i]). If p=1 Go to step 3. End if. i=p. End while. Step 3: [Increase element index] k=k+1. Step 4: [Finished] Return. Function Reheap(A,n) Step 1: [Perform reheap operation] i=1. while TRUE do if n>=2i if n<=2i+1 if A[i]>A[2i] AND A[i]>A[2i+1] return. End if. else if A[2i]>A[2i+1] swap(A[2i],A[i]). i=2i. End if. else Swap(A[2i+1],A[I]). i=2i+1. End of if else. End if. else if A[i]>A[2i] Return. else swap(A[i],A[2i+1]). Return. End if else. else Return. End if else. End while.

114

Step 2: [Finished] Return. Radix sort Function radixsort(A, n) Step 1: [Initialize] max=0, exp=1. Step 2: [Find maximum element of list] for i=1 to n do if A[i]>max max=A[i]. end if. End for. Step 3: [Perform each iteration] Repeat while m/exp>0. Step 4: [Initialize all elements of bucket to 0] for i=1 to 10 do bucket[i]=0. End for. Step 5: [Find the number of elements to be inserted in each bucket] for i=1 to n do bucket[a[i]/(exp%10)]= bucket[a[i]/(exp%10)]+1. End for. Step 6: [Find total number of elements entered in all buckets before bucket[i] and add bucket[i] to it] for i=2 to 10 do bucket[i]=bucket[i]+bucket[i-1]. End for. Step 7: [Insert elements in their respective position from bucket] for i=n down to 1 do bucket[A[i]/(exp%10)]=bucket[A[i]/(exp%10)]-1. b[bucket[A[i]/(exp%10)]]=A[i]. Step 8: [Copy contents of b back to a] for i=1 to n do A[i]=b[i]. End for. Step 9: [Increment exp] exp=exp10. [End of step 3 loop] Step 10: [Finished] Return.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #define MAX 100 void quicksort(int [],int); int quick(int [],int,int); void ssort(int [],int); void isort(int [],int);

115

void bsort(int [],int); void mergesort(int [],int); void heapsort(int [],int); void swap(int *,int *); void radixsort(int [],int); int main(void) { int a[MAX],n,i,ch; printf("*** This program sorts n no. of elements by different sorting

techniques ***\n"); /* Input the number of elements */ printf("\nEnter the number of elements:"); scanf("%d",&n); /* Input each element */ for (i=0;i<n;i++) { printf("\nEnter element %d:",i+1); scanf("%d",&a[i]); } printf("\nChoose method to sort:\n\n1.Quick Sort\n2.Selection Sort\n3.Insertion sort\n4.Bubble Sort\n5.Merge Sort\n6.Heap Sort\n7.Radix Sort\n\nEnter your choice:"); scanf("%d",&ch); switch (ch) { case 1: quicksort(a,n); break; case 2: ssort(a,n); break; 3: isort(a,n); break; 4: bsort(a,n); break; 5: mergesort(a,n); break; 6: heapsort(a,n); break; case 7:

case

case

case

case

116

radixsort(a,n); break; default: printf("\nWrong choice entered!"); getch(); return 1; } /* Print output */ printf("\nThe numbers in the sorted order are: \n\n"); for (i=0;i<n;i++) printf("%d ",a[i]); getch(); return 0; } void quicksort(int x[],int n) { int beg,end,lower[50],upper[50],top= -1,pos; lower[0]=0; upper[0]=n-1; top++; while (top!=-1) { beg=lower[top]; stack */ end=upper[top]; top--; /* Pop end index of each partition from upper stack */ /* Decrement top to point to next values */ /* Call quick function to find the exact position /* Pop beginning index of each partition from lower /* Lower index of 1st partition is set to 0 */ /* Upper index of 1st partition is set to n */ -1 /* Increment top to point to new values in stack */ /* Continue partioning untill stack is empty */

/* Push left partition to stack if it has more than 1 element */ if (beg<pos-1) { top++; lower[top]=beg; upper[top]=pos-1; }/* End if */ /* Push right partition to stack if it has more than 1 element */ if (pos<end-1) { top++; lower[top]=pos+1; upper[top]=end; }/* End if */

117

}/* End while */ }/* End quicksort */ int quick(int x[],int left, int right) { int pos,temp; pos=left; do { /* Select position of pivot element */ /* Continue till the actual position of pivot element is found */

while (x[pos]<x[right] && pos!=right) /* Scan partition fr m right to left */ o right--; if (pos==right) /* If all elements in right of pivot element are greater then the actual position is found */ return pos; else { temp=x[pos]; x[pos]=x[right]; x[right]=temp; pos=right; } while (x[pos]>=x[left] && pos!=left) left++; the actual position is found */ return pos; else { /* Interchange x[pos] and x[left] */ /* Scan partition from left to right */ /* Interchange x[pos] and x[right] */

temp=x[pos]; x[pos]=x[left]; x[left]=temp; pos=left; }/* End of if-else structure */ }while (1); }/* End quick */ void ssort(int x[], int n) { int i,j,temp,min,pos; for (i=0;i<n-1;i++) { min=x[i]; pos=i; /* Select position i */

/* Find minimum element and its position in rest of list */ for (j=i+1;j<n;j++) if (x[j]<min)

118

{ min=x[j]; pos=j; } /* Swap ith element and minimum element of remaining list */ temp=x[i]; x[i]=x[pos]; } } x[pos]=temp; /* End for */

/* End ssort */

void isort(int x[],int n) { int i,k,temp; for (k=1;k<n;k++) { temp=x[k]; /* Store the element k in a te mporary variable */ /* Select element k */

/* Move ith element to (i+1)th position till actual position of temp is found */ for (i=k-1;i>=0 && temp<x[i];i --) x[i+1]=x[i]; x[i+1]=temp; }/* End for */ }/* End isort */ void bsort(int x[], int n) { int i,j,temp,flag=1; for (i=0;i<n-1 && flag==1;i++) { flag=0; /* Execute each pass */ /* Insert temp in its new position */

/* Initialise flag to 0 in each pass */ /* Compare jth and (j+1)th element in pass i */

/* If any two elements are interchanged, change flag to 1 */ flag=1; /* Swapping jth and (j+1)th element */ temp=x[j+1]; x[j+1]=x[j]; x[j]=temp; } } } /* End if */ /* End of comparison loop */

119

} /* End of bsort function */

void mergesort(int x[], int n) { int i,j,k,l1,u1,l2,u2,size,temp[MAX]; size=1; /* Initial size of each file is 1 */

/* Continue merging untill size of each file becomes equal to greater than n */ while (size<n) { l1=0; k=0; /* Initialise lower bound of first file */ /* k maintains the index of temporary array */ /* Check to see if there are two files to merge */ /* Compute lower bound of second file to merge */

u1=l2-1; /* Compute upper bound of first file to merge */ u2=(l2+size-1<n)?(l2+size-1):(n-1); /* Check if size of last sub file is lesser than previous file and compute upper bound of second file to merge accordingly */ /* Merge the two files and copy to temporary array */ for (i=l1,j=l2;i<=u1 && j<=u2;k++) if (x[i]<=x[j]) temp[k]=x[i++]; else temp[k]=x[j++]; /* At this point atleast one subfile gets exhausted, so we copy the contents of the other file to the temporary array */ for (;i<=u1;k++) temp[k]=x[i++]; for (;j<=u2;k++) temp[k]=x[j++]; l1=u2+1; /* l1 now denotes lower bound of first file of the

next two files to be merged */ }/* End while */ /* Copy any remaining single file */ for (i=l1;k<n;i++) temp[k++]=x[i]; /* Copy the contents of the temporary array to original array */ for (i=0;i<n;i++) x[i]=temp[i]; size*=2; }/* End while */ /* Increase size of each file */

120

}/* End mergesort */ void heapsort(int x[],int n) { int i,j,k,h; for(h=0;h<n;h++) { for(i=1;i<n-h;i++) { j=i; while(j>0) { k=(int)((j-1)/2); if(x[k]<x[j]) { swap(&x[k],&x[j]); j=k; } else break; }/* end while */ }/* end inner for */ swap(&x[0],&x[n-(h+1)]); }/* end outer for */ }/* end of function */ void swap(int *x,int *y) { int p=*x; *x=*y; *y=p; } void radixsort(int a[],int n) { int i,b[MAX],m=0,exp=1; /* Find maximum element of list */ for(i=0;i<n;i++) { if(a[i]>m) m=a[i]; } while(m/exp>0) { int bucket[10]={0}; /* To find no. of elements in each bucket */

121

for(i=0;i<n;i++) bucket[a[i]/exp%10]++; /* Find total no. of elements entered in all buckets before bucket[i] and add bucket[i] to it */ for(i=1;i<10;i++) bucket[i]+=bucket[i-1]; /* Insert elements in their respective position from bucket */ for(i=n-1;i>=0;i--) b[--bucket[a[i]/exp%10]]=a[i]; /* Copy contents of b back to a */ for(i=0;i<n;i++) a[i]=b[i]; exp*=10; }/* End while */ }/* End function */

1. *** This program sorts n no. of elements by different sorting techniques *** Enter the number of elements:5 Enter element 1:6 Enter element 2:3 Enter element 3:-4 Enter element 4:7 Enter element 5:1 Choose method to sort: 1.Quick Sort 2.Selection Sort 3.Insertion sort 4.Bubble Sort 5.Merge Sort 6.Heap Sort 7.Radix Sort Enter your choice:1 The numbers in the sorted order are:

122

-4 1 3 6 7 2. *** This program sorts n no. of elements by different sorting techniques *** Enter the number of elements:5 Enter element 1:7 Enter element 2:-2 Enter element 3:-4 Enter element 4:3 Enter element 5:1 Choose method to sort: 1.Quick Sort 2.Selection Sort 3.Insertion sort 4.Bubble Sort 5.Merge Sort 6.Heap Sort 7.Radix Sort Enter your choice:2 The numbers in the sorted order are: -4 -2 1 3 7 3. *** This program sorts n no. of elements by different sorting techniques *** Enter the number of elements:5 Enter element 1:7 Enter element 2:-2 Enter element 3:-4 Enter element 4:3 Enter element 5:1 Choose method to sort:

123

1.Quick Sort 2.Selection Sort 3.Insertion sort 4.Bubble Sort 5.Merge Sort 6.Heap Sort 7.Radix Sort Enter your choice:3 The numbers in the sorted order are: -4 -2 1 3 7 4. *** This program sorts n no. of elements by different sorting techniques *** Enter the number of elements:5 Enter element 1:6 Enter element 2:3 Enter element 3:-4 Enter element 4:7 Enter element 5:1 Choose method to sort: 1.Quick Sort 2.Selection Sort 3.Insertion sort 4.Bubble Sort 5.Merge Sort 6.Heap Sort 7.Radix Sort Enter your choice:4 The numbers in the sorted order are: -4 1 3 6 7 5. *** This program sorts n no. of elements by different sorting techniques *** Enter the number of elements:5

124

Enter element 1:2 Enter element 2:3 Enter element 3:-4 Enter element 4:-6 Enter element 5:1 Choose method to sort: 1.Quick Sort 2.Selection Sort 3.Insertion sort 4.Bubble Sort 5.Merge Sort 6.Heap Sort 7.Radix Sort Enter your choice:5 The numbers in the sorted order are: -6 -4 1 2 3 6. *** This program sorts n no. of elements by different sorting techniques *** Enter the number of elements:5 Enter element 1:2 Enter element 2:3 Enter element 3:-4 Enter element 4:-6 Enter element 5:1 Choose method to sort: 1.Quick Sort 2.Selection Sort 3.Insertion sort 4.Bubble Sort 5.Merge Sort 6.Heap Sort 7.Radix Sort

125

Enter your choice:6 The numbers in the sorted order are: -6 -4 1 2 3 7. *** This program sorts n no. of elements by different sorting techniques *** Enter the number of elements:5 Enter element 1:683 Enter element 2:562 Enter element 3:495 Enter element 4:582 Enter element 5:134 Choose method to sort: 1.Quick Sort 2.Selection Sort 3.Insertion sort 4.Bubble Sort 5.Merge Sort 6.Heap Sort 7.Radix Sort Enter your choice:7 The numbers in the sorted order are: 134 495 562 582 683

DISCUSSIONS:

1. In this program, the numbers are sorted in ascending order for each algorithm. Numbers can also be sorted in descending order by a slight change in each of the algorithms. 2. The switch-case structure creates the menu to simulate the different sorting techniques and allow the user to choose any one technique to sort the elements. 3. All the sorting process are implemented using arrays. They can also be implemented by link lists, but proper modification needs to be done, except for heap sort. Heap sort is impossible to be implemented by link lists. 4. All the sorting process except radix sort can be implemented for non -numeric data also, though here we used only signed integer type data. 5. Since quick sort is implemented in non-recursive fashion, we used two stacks lower and upper to keep track of the sub lists which are created after finding the position of a pivot element.

126

6. In quick sort algorithm, the first element is chose as the pivot element for each partition. Consequently, the complexity of this algorithm in worst case is O(n ). However, in average case and best case the complexity of the algorithm is O(n log n). 7. It is called as quick sort because this algorithm shows best performance in case of highly unsorted list but shows worst situation in case of sorted or partially sorted list than the other algorithms so it is called as Quick Sort. 8. Quick sort algorithm works only for the data structures inside memory so it is called an internal sorting algorithm. 9. Quick sort algorithm is not a stable sorting algorithm. 10. Quick sort is a divide and conquer algorithm. 11. Quick sort tends to make excellent usage of the memory hierarchy, taking perfect advantage of virtual memory and available caches. 12. The complexity of selection sort algorithm is O(n ) in worst case. Thus it is rarely used, except for small lists. Its only advantage is in its simplicity and can be implemented very easily. 13. It is called selection sort because in first pass, we select the minimum element in the list, and place it in the first position. In second pass, we select the minimum element in the rest of the list and place it in second position, and so on. 14. The complexity of insertion sort algorithm is O(n ) in worst case when the given elements are in opposite order. During each iteration, the first remaining element of the input is compared with all the elements of the sorted subsection of the array.In best case, when all the elements are sorted, insertion sort runs with complexity of O(n). During each iteration, the first remaining element of the input is only compared with the right-most element of the sorted subsection of the array. 15. It is called insertion sort because, in each pass, it inserts a new element in sorted order in a previously sorted array. 16. Insertion sort is not an efficient sorting algorithm, but it is used for small data sets. 17. Insertion sort's advantage over selection sort is that it only scans as many elements as it needs in order to place the k + 1st element, while selection sort must scan all remaining elements to find the k + 1st element. 18. Insertion sort is a stable sorting algorithm i.e. does not change the relative order of elements with equal keys. 19. Simple calculation shows that insertion sort will therefore usually perform about half as many comparisons as selection sort, although it can perform just as many or far fewer depending on the order the array was in prior to sorting. It can be seen as an advantage for some real-time applications that selection sort will perform identically regardless of the order of the array, while insertion sort's running time can vary considerably. However, this is more often an advantage for insertion sort in that it runs much more efficiently if the array is already sorted or close to sorted. 20. The complexity of bubble sort in worst case and average case is O(n ). However, in best case, when all the elements are sorted, this implementation of bubble sort runs with complexity of O(n). 21. Bubble sort and insertion sort has the advantage over all other sorting algorithms in the best case, when all the elements are already sorted. 22. The name bubble sort came from the way smaller elements "bubble" to the top of the list. 23. The advantage of this implementation of selection sort, called straight selection sort, over bubble sort is that the number of swapping operations on elements of the array is more. In case of selection sort only n swapping operations are performed, whereas in bubble sort there are n swapping operations performed.

127

24. The complexity of merge sort in worst case and average case is O(n log n). In the best case, if the input is already sorted, its complexity falls to O(n). 25. Merge sort is a divide and conquer algorithm. 26. Merge sort is often the best choice for sorting a linked list; in this situation it is relatively easy to implement a merge sort in such a way that it requires only (1) extra space, and the slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heap sort) completely impossible. 27. Merge sort is a stable sorting algorithm. 28. The name of the algorithm is merge sort because it merges two sorted lists to form a third list. 29. In the worst case, merge sort does about 39% fewer comparisons than quicksort does in the average case; merge sort always makes fewer comparisons than quicksort, except in extremely rare cases, when they tie, where merge sort's worst case is found simultaneously with quicksort's best case. In terms of moves, merge sort's worst case complexity is O(n log n)the same complexity as quicksort's best case, and merge sort's best case takes about half as many iterations as the worst case. 30. In heap sort, a max heap is created to sort the data. A min heap could have also been used to sort the elements. 31. The complexity of heap sort in worst case and average case in O(n log n). 32. Although heap sort has the same time bounds as merge sort, it requires only (1) auxiliary space instead of merge sort's (n), and is often faster in practical implementations. 33. Heap sort is assumed to be in average somewhat slower than quicksort. This is still debated and in research, with some publications indicating the opposite. 34. The worst case complexity of radix sort is O(n ). 35. If d is the maximum number of digits in the highest number, then in best case the complexity of radix sort is O(n log n) where d is the order of the log. 36. This implementation of radix sort only works correctly only for positive integers. For giving correct result for negative integers also, sufficient modification must be done to sort negative numbers also. 37. Implementing radix sort for floating point numbers is also difficult, but can be implemented. 38. A drawback of radix sort is that one may need dn memory locations. This comes from the fact that all the items may be sent to the same bucket during a given pass. This drawback may be minimised by using linked lists rather than arrays to store the items during a given pass. However, it still requires 2n memory locations. 39. Radix sort is an efficient sorting method when the number of digits in each number is small.

128

ASSIGNMENT No. 20

PROGRAM STATEMENT:

Date: 05.02.2010.

Write a program to build a binary search tree having characters as the content of each node. Visit the tree in preorder, inorder and postorder sequence. Display the output in suitable format.

THEORY:

A binary tree is a finite set of elements that is either empty or is partitioned into three disjoint subsets. The first subset contains a single element called the root of the tree. The other two subsets are themselves binary trees, called the left and right sub-trees of the original tree. A left or right sub-tree can be empty. Each element of a binary tree is called a node of the tree. A binary tree which has the property that, all the elements in the left sub-tree of a node N are less than the contents of N, and all the elements in the right sub-tree of N are greater than or equal to the contents of N, then the binary tree is called a binary search tree. Traversing a binary search tree means to visit the nodes of the tree starting from the root of the tree and by following the left and right links in some order, visiting each node exactly once. Visiting a node means to process the data of the node in some way. In the simplest example the value at the node can be printed when Binary Search Tree could be mainly traversed in three ways, preorder, inorder, and postorder operations. The only difference between among these methods is the order in which the different nodes of the tree visited. In each of these methods, nothing needs to be done to traverse an empty binary search tree. If the binary search tree is traversed in inorder, then the contents of each node is printed in ascending order. To traverse a non-empty binary tree in preorder, we perform the following three operations: 1. Visit the root. 2. Visit the left sub-tree in preorder. 3. Visit the right sub-tree in preorder. To traverse a non-empty binary tree in inorder, we perform the following three operations: 1. Visit the left sub-tree in inorder. 2. Visit the root. 3. Visit the right sub-tree in inorder. To traverse a non-empty binary tree in postorder, we perform the following three operations: 1. Visit the left sub-tree in postorder. 2. Visit the right sub-tree in postorder. 3. Visit the root.

ALGORITHM:

The algorithm for implementing the program has four parts, i.e. creation of the binary search tree, traversal in preorder, inorder and postorder. We consider that the tree is created in memory in linked list format. Each node of the tree has 3 parts, namely data part containing the data of the node, and the left and right pointers, pointing to left child and right child of the current node. Let the pointer to the root node of the tree is denoted by root. We use the function InsertTree() to insert each successive node to the tree and create the tree. Function InsertTree(root, newnode) (* This function inserts a node to the binary search tree which has a root node. newnode is the node to be inserted *) Step 1: [Check if data of root node is greater or lesser than new node]

129

if root->data>newnode->data Go to step 2. else Go to step 3. End of if else structure. Step 2: [If there is no left child of root then insert new node, otherwise recursively call function with left child as root node] if root->left=NULL root->left=newnode. else insert(root->left,newnode). End of if else structure. Step 3: [If there is no right child of root then insert new node, otherwise recursively call function with right child as root node] if root->right=NULL root->right=newnode. else insert(root->right,newnode). End of if else structure. Step 4: [Finished] Return. Function Preorder(root) Step 1: if root!=NULL Process (root->data) Preorder(root->left) Preorder(root->right) end if. Function Inorder(root) Step 1: if root!=NULL Inorder(root->left) Process (root->data) Inorder(root->right) end if.

[Process current node] [Recursively call function with left child] [Recursively call function with right child]

[Recursively call function with left child] [Process current node] [Recursively call function with right child]

Function Postorder(root) Step 1: if root!=NULL Postorder(root->left) [Recursively call function with left child] Postorder(root->right) [Recursively call function with right child] Process (root->data) [Process current node] end if.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> typedef struct tree { struct tree *left; /* Create structure for each node of tree*/ /* Points to left child of current node*/

130

char data; /* Contains data of current node */

struct tree *right; /* Points to right child of current node*/ }node; /* Denote struct tree by node */ node *getnode(char item) { node *ptr; /* pointer ptr of type node is declared */ ptr=(node *)malloc(sizeof(node)); /* Allocate space for new node */ ptr->data=item; /* Insert item to data part o new node */ f ptr->left=NULL; /* left pointer of new node is assigned to null */ ptr->right=NULL; /* right pointer of new node is assigned to null */ return ptr; } void preorder(node *root) /* Visits tree in preorder sequence */ { if (root!=NULL) { printf("%c, ",root->data); /* Print current node */ preorder(root->left); preorder(root->right); } } void inorder(node *root) /* Visits tree in inorder sequence */ { if (root!=NULL) { inorder(root->left); /* Recursively call function with left child */ printf("%c, ",root->data); /* Print current node */ inorder(root->right); /* Recursively call function with right child */ } } void postorder(node * root) { if (root!=NULL) { postorder(root->left); postorder(root->right); } } void insert(node *roo t, node *newnode) { if (root->data>newnode->data) /* If data of new node is less than root node */ { if (root->left==NULL) root->left=newnode; /* If there is no left node of root node */ /* Insert new node as left node of root node */ /* Inserts a new node to the BST */ /* Visits tree in postorder sequence */ /* Recursively call function with left child */ /* Recursively call function with right child */ /* pointer ptr is returned which points to new node */ /* Function getnode creates a new node of tree */

/* Recursively call function with left child */ /* Recursively call function with right child */

131

else insert(root->left,newnode);/* Recursively call function with left child as root node */ } else { if (root->right==NULL) root->right=newnode; else /* If there is no right node of root node */ /* Insert new node as right node of root node */ /* If data of new node is greater than root node */

insert(root->right,newnode);/* Recursively call function with right child as root node */ } } int main(void) { char item; node *root,*newnode; printf("*** Program to build a binary search tree having characters as the content of each node *** \n"); printf("\nEnter root element in binary search tree:"); fflush(stdin); scanf("%c",&item); root=getnode(item); do { printf("\nEnter character element to insert in binary search tree (# to stop):"); fflush(stdin); scanf("%c",&item); if (item=='#') break; /* Check for termination condition */ /* Create root node */

/* Create new node */ /* Call insert function to insert new node to BST */

printf("\nElements in the tree are:\n"); printf("\nPreorder: "); preorder(root); printf("\nInorder: "); inorder(root);

132

*** Program to build a binary search tree having characters as the content of each node *** Enter root element in binary search tree:G Enter character element to insert in binary search tree (# to stop):A Enter character element to insert in binary search tree (# to stop):U Enter character element to insert in binary search tree (# to stop):R Enter character element to insert in binary search tree (# to stop):B Enter character element to insert in binary search tree (# to stop):K Enter character element to insert in binary search tree (# to stop):# Elements in the tree are: Preorder: G, A, B, U, R, K, Inorder: A, B, G, K, R, U, Postorder: B, A, K, R, U, G,

DISCUSSIONS:

1. The fflush(stdin) function is used to clear the character buffer before a new character is inputted. 2. The tree could have been loaded into memory using an array instead of a link list. But since the no. of nodes in the tree to be created is unknown, array is not used. At runtime, we dynamically choose the number of nodes to be created and no space is wasted. 3. The traversal functions preorder(), inorder(), postorder() are written in recursive manner to make the program coding shorter. There is a non-recursive version for each of the above traversal algorithms. 4. A separate function getnode() is used to create each node of the tree. 5. The inorder traversal of a binary search tree always gives the elements in sorted order. So creation of a binary search tree with random elements and then traversing it in inorder may be used as a method for sorting elements in ascending order.

133

ASSIGNMENT No. 21

PROGRAM STATEMENT:

Date: 10.02.2010.

Create a binary tree using C and then traverse the tree in Preorder, Inorder, and Postorder traversal.

THEORY:

A binary tree is a finite set of elements that is either empty or is partitioned into three disjoint subsets. The first subset contains a single element called the root of the tree. The other two subsets are themselves binary trees, called the left and right sub-trees of the original tree. A left or right subtree can be empty. Each element of a binary tree is called a node of the tree. Traversing a binary tree means to visit the nodes of the tree starting from the root of the tree and by following the left and right links in some order, visiting each node exactly once. Visiting a node means to process the data of the node in some way. In the simplest example the value at the node can be printed when Binary Tree could be mainly traversed in three ways, preorder, in order, and postorder operations. The only difference between among these methods is the order in which the different nodes of the tree visited. In each of these methods, nothing needs to be done to traverse an empty binary tree. To traverse a non-empty binary tree in preorder, we perform the following three operations: 4. Visit the root. 5. Visit the left sub-tree in preorder. 6. Visit the right sub-tree in preorder. To traverse a non-empty binary tree in inorder, we perform the following three operations: 4. Visit the left sub-tree in inorder. 5. Visit the root. 6. Visit the right sub-tree in inorder. To traverse a non-empty binary tree in postorder, we perform the following three operations: 4. Visit the left sub-tree in postorder. 5. Visit the right sub-tree in postorder. 6. Visit the root.

ALGORITHM:

The algorithm for implementing the program has four parts, i.e. creating of the binary tree, traversal in preorder, inorder and postorder. In creation of the binary tree, we use a queue to keep track of the nodes whose children are not yet inputted by the user. We consider that the tree is created in memory in linked list format. Each node of the tree has 3 parts, namely data part containing the data of the node, and the left and right pointers, pointing to left child and right child of the current node. We also use a function in the following algorithm getnode(item) which returns a new node with data part equal to item and the left and right pointers being null. Function CreateTree() Step 1: [Create root node] root=getnode(item) Step 2: [Insert root node to queue] queue[front]=root Step 3: [Create node until queue is empty] Repeat while front<=rear Step 4: [Delete front element of queue] ptr=queue[front]

134

front=front+1 Step 5: [Create node for left child of ptr and insert it to queue] if (item!=NULL) ptr->left=getnode(itemleft) rear=rear+1 queue[rear]=ptr->left end if. Step 6: [Create node for right child of ptr and insert it to queue] if (item!=NULL) ptr->right=getnode(itemright) rear=rear+1 queue[rear]=ptr->right end if. [End of Step 3 loop]. Step 7: [Finished] End. Function Preorder(root) Step 1: if root!=NULL Process (root->data) Preorder(root->left) Preorder(root->right) end if. Function Inorder(root) Step 1: if root!=NULL Inorder(root->left) Process (root->data) Inorder(root->right) end if.

[Process current node] [Recursively call function with left child] [Recursively call function with right child]

[Recursively call function with left child] [Process current node] [Recursively call function with right child]

Function Postorder(root) Step 1: if root!=NULL Postorder(root->left) [Recursively call function with left child] Postorder(root->right) [Recursively call function with right child] Process (root->data) [Process current node] end if.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<process.h> typedef struct tree { int data; /* Create structure for each node of tree */

struct tree *left; /* Points to left child of current node*/ /* Contains data of c urrent node */ struct tree *right; /* Points to right child of current node*/ }node; /* Denote struct tree by node */

135

node *getnode(int item)/* Function getnode creates a new node of the binary tree */ { node *ptr; /* pointer ptr of type node is declared */ ptr=(node *)malloc(sizeof(node)); /* Allocate space for new node */ ptr->data=item; /* Insert item to data part of new node */ ptr->left=NULL; return ptr; } void preorder(node *root) /* Visits tree in preorder sequence */ { if (root!=NULL) { printf("%d, ",root->data); /* Print current node */ preorder(root->left); preorder(root->right); } } void inorder(node *root) /* Visits tree in inorder sequence */ { if (root!=NULL) { inorder(root->left); /* Recursively call function with left child */ printf("%d, ",root->data); /* Print current node */ inorder(root->right); } } void postorder(node * root) { if (root!=NULL) { postorder(root->left); /* Recursively call function with left child */ postorder(root->right); /* Recursively call function with right child */ printf("%d, ",root->data); /* Print current node */ } } int main(void) { node *ptr,*queue[50],*root; int item,front=0,rear=0; printf("\n* Program to create a inorder, and postorder form * \n"); /* Input root item of tree */ printf("\nEnter root node of binary tree:"); binary tree and traverse it in preorder, /* Visits tree in postorder sequence */ /* Recursively call function with right child */ /* Recursively call function with left child */ /* Recursively call function with right child */ /* left pointer of new node is assigned to null */ /* pointer ptr is returned which points to new node */ ptr->right=NULL; /* right pointer of new node is assigned to null */

136

scanf("%d",&item); root=getnode(item); queue[front]=root; root node */ while (front<=rear) { ptr=queue[front]; front++; /* Delete front element of queue */ /* Continue untill queue is empty */ /* create root node of the tree */ /* front element of queue is set to pointer pointing to

/* Inout data for left child of ptr */ printf("\nEnter left element of %d ( -999 for none):",ptr ->data); scanf("%d",&item); /* Create node for left child of ptr and insert it to queue */ if (item!=-999) { ptr->left=getnode(item); rear++; queue[rear]=ptr->left; } /* Input data for right child of ptr */ printf("\nEnter right element of %d ( -999 for none):",ptr->data); scanf("%d",&item); /* Create node for right child of ptr and insert it to queue */ if (item!=-999) { ptr->right=getnode(item); rear++; queue[rear]=ptr->right; } } printf("\nElements in the tree are: \n"); printf("\nPreorder: "); preorder(root); printf("\nInorder: "); inorder(root); printf("\nPostorder: "); postorder(root); getch(); return 0; }

Enter root node of binary tree:5 Enter left element of 5 (-999 for none):9 Enter right element of 5 (-999 for none):3 Enter left element of 9 (-999 for none):6 Enter right element of 9 (-999 for none):4 Enter left element of 3 (-999 for none):-999 Enter right element of 3 (-999 for none):-999 Enter left element of 6 (-999 for none):-999 Enter right element of 6 (-999 for none):-999 Enter left element of 4 (-999 for none):-999 Enter right element of 4 (-999 for none):-999 Elements in the tree are: Preorder: 5, 9, 6, 4, 3, Inorder: 6, 9, 4, 5, 3, Postorder: 6, 4, 9, 3, 5,

DISCUSSIONS:

1. A stack could have also been used instead of a queue to track the nodes whose children are not yet inputted. 2. The tree could have been loaded into memory using an array instead of a link list. But since the no. of nodes in the tree to be created is unknown, array is not used. At runtime, we dynamically choose the number of nodes to be created and no space is wasted. 3. The traversal functions preorder(), inorder(), postorder() are written in recursive manner to make the program coding shorter. There is a non-recursive version for each of the above traversal algorithms. 4. A separate function getnode() is used to create each node of the tree.

138

ASSIGNMENT No. 22

PROGRAM STATEMENT:

Date: 17.02.2010.

Write a program to accept a string of parentheses and checks whether the string is valid in algebraic sense. (Example: {()()}[{}] is valid but {(})[] is invalid).

THEORY:

All the symbols [, {, (, ), }, ] are called parenthesis. A string of parentheses consists of a number of these parentheses one beside other. The braces [],{},(), forms individual set of parentheses. In each set, the first member is called opening parentheses and second member is c alled closing parentheses. In algebraic sense, a string of parentheses is valid, if the parentheses are in order of algebra. Otherwise it is invalid. Example: {([])}(){[]} is valid but {(}[()]) is invalid. To find whether a string is valid or invalid, we use a data-structure called stack. A stack is an ordered collection of items into which new items may be inserted and from which items can be deleted at one end, called the top of the stack. A stack is a Last-In-First-Out (LIFO) data structure. A stack can have any abstract data type as its element. Stack is characterized by two fundamental operations: push and pop. The push operation adds to the top of the list, hiding any items already on the stack, or initializing the stack if it is empty. The pop operation removes an item from the top of the list, and returns this value to the caller. A pop either reveals previously concealed items, or results in an empty list. A stack is a restricted data structure, because only a small number of operations are performed on it. The nature of the pop and push operations also mean that stack elements have a natural order. Elements are removed from the stack in the reverse order to the order of their addition: therefore, the lower elements are typically those that have been in the list the longest.

ALGORITHM:

Function ParenCheck(par) (* This function returns 1 if string of parentheses par is valid, and 0 otherwise. top denotes the pointer to the top of stack *) Step 1: [Initialize] i=0. Step 2: [Traverse through each character of string] Repeat step 3 to step 4 while par[i]NULL. Step 3: [Push opening braces to stack and if closing brace is encountered then pop from stack and compare] if par[i]=`(` OR par[i]=`{` OR par[i]=`[` then push(par[i]). else x=pop(). if par[i]=`(` AND x=`)` then flag=0. End if. if par[i]=`{` AND x=`}` then flag=0. End if. if par[i]=`[` AND x=`]` then flag=0. else flag=1.

139

Go to Step 6. end of inner if-else structure. End of outer if-else structure. Step 4: [Update counter] i=i+1. Step 5: [Find whether string is valid and return accordingly] if top=0 AND flag=0 Return 1. else Return 0. Function push(x) (* This function push an item x to stack. Let n be the size of stack. *) Step 1: [Check if stack is full] if top>=n Write Stack is full Return. Step 2: [Increment top] top=top+1. Step 3: [Push item to top position of stack] stack[top]=x. Step 4: [Finished] Return. Function pop(x) (* This function pop an item x from stack. *) Step 1: [Check if stack is empty] if top<=0 Write Stack is empty. Return. Step 2: [Decrement top] top=top-1. Step 3: [Push item to top position of stack] x=stack[top]. Step 4: [Finished] Return x.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #define MAX 50 char stack[MAX]; int top=-1; void push(char x) { if (top>=MAX) { printf("Stack overflow"); getch(); /* Global declaration of stack and its pointer top */

140

} top++; stack[top]=x; return; } int pop() { if (top==-1) { printf("Stack underflow"); getch(); } return stack[top--]; } int main(void) { char par[MAX],x; int i,flag; printf("*** Program to check algebraic sense ***\n"); printf("\nEnter the string of parenthesis:"); gets(par); for (i=0;par[i]!='\0';i++) { /* If opening braces are found then push to stack */ if (par[i]=='(' || par[i]=='{' || par[i]=='[') push(par[i]); else { /* Pop from stack */ x=pop(); /* If closing brace match with popped brace make flag 0*/ if ((par[i]==')' && x=='(') || (par[i]=='}' && x=='{') || (par[i]==']' && x=='[')) flag=0; else /* Closing brace does not match with popped brace */ { flag=1; break; } } } /* If all parenthesis are in order and the stack is empty then the string is valid, else invalid*/ if (flag==0 && top==-1) printf("\nThe string of parenthesis is valid in algebraic sense."); whether a string of parenthesis is valid in /* Pop element from stack */

141

else printf("\nThe string of parenthesis is not valid in algebraic sense."); getch(); return 0; }

1. *** Program to check whether a string of parenthesis is valid in algebraic sense *** Enter the string of parenthesis:({[({})]}){}()[{}] The string of parenthesis is valid in algebraic sense. 2. *** Program to check whether a string of parenthesis is valid in algebraic sense *** Enter the string of parenthesis:({[])}({}) The string of parenthesis is not valid in algebraic sense.

DISCUSSIONS:

1. In this program, stack is used to check whether the string is valid. Stacks also find application to different other algorithms in computer science and it is a very important data structure. 2. Creation of stack required much memory space, which is a drawback. If the program was coded in a different way without using stack, then less space might have been used. 3. Most CPUs have registers that can be used as stack pointers.

142

ASSIGNMENT No. 23

PROGRAM STATEMENT:

Date: 19.02.2010.

Write a program which converts numbers in the decimal system to Roman numerals with the following notations: I=1, V=5, X=10, L=50, C=100, D=500, M=1000.

THEORY:

Roman numerals are a numeral system of ancient Rome based on letters of the alphabet. The Roman numeral system is decimal but not directly positional and does not include a zero and negatives. Roman numerals are commonly used in numbered lists (such as the outline format of an article), clock faces, pages preceding the main body of a book, dated notices of copyright, months of the year, successive political leaders or children with identical names, the numbering of annual events, etc. Roman numerals are based on seven symbols: a stroke (identified with the letter I) for a unit, a chevron (identified with the letter V) for a five, a cross-stroke (identified with the letter X) for a ten, a C (identified as an abbreviation of Centum) for a hundred, etc. For large numbers (4,000 and above), a bar can be placed above a base numeral, or parentheses placed around it, to indicate multiplication by 1,000. Since a bar is difficult to output, we write the program for decimal numbers less than 4000 and get correct equivalent Roman numeral of it. For example, the decimal number 14 is equivalent to XIV, the decimal number 231 is equivalent to CCXXI, and 1521 is equivalent to MDXXI and so on.

ALGORITHM:

Function Roman (n) (* This function returns a string containing roman equivalent of a positive decimal number n. *) Step 1: [Initialize] i=0. Step 2: [Perform the iteration to find each successive Roman numeral] Repeat step 3 to step 8 while TRUE. Step 3: [Update counter] i=i+1. Step 4: [Find the roman numeral(s) equivalent of decimal digit in thousandth place] if n>=1000 then r[i]=M. n=n-1000. Go to step 2. End if. Step 5: [Find the roman numeral(s) equivalent of decimal digit in hundredth place] if n>=500 then r[i]=D. n=n-500. Go to step 2. End if. if n>=100 then r[i]=C. n=n-100. Go to step 2. End if.

143

Step 6: [Find the roman numeral(s) equivalent of decimal digit in tenth place] if n>=50 then r[i]=L. n=n-50. Go to step 2. End if. if n>=10 then r[i]=X. n=n-10. Go to step 2. End if. Step 7: [Find the roman numeral(s) equivalent of decimal digit in unit place] if n>=5 then if n=9 then r[i]=I. n=n+1. Go to step 2. End inner if. r[i]=V. n=n-5. Go to step 2. End outer if. if n>=1 then r[i]=I. if n=4 then n=n+1. Go to step 2. End inner if. n=n-1. Go to step 2. End outer if. Step 8: [Check if all roman numerals of the number are found] if n=0 r[i+1]=NULL. Go to step 9. End if. Step 9: [Finished] Return r.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #define MAX 30 void roman(int, char [MAX]); int main(void) { int num; char r[MAX];

144

printf("*** Program to find the Roman equivalent of a decimal number *** \n"); /* Continue loop untill valid input is entered */ do { printf("\nEnter number in decimal system (less than 4000):"); scanf("%d",&num); if (num>=4000 || num<1) /* Check for validity of number */ printf("\nWrong value entered! \n"); } while (num>=4000 || num<1); roman(num,r); /* Show output */ printf("\nThe roman equivalent of %d is %s.",num,r); getch(); return 0; } void roman(int n, char r[MAX]) { int i,j; /* for each successive roman digit */ for (i=0;i<MAX;i++) { /* for decimal digits in thousandth place */ if (n>=1000) { r[i]='M'; n=n-1000; continue; } /* for decimal digits in hundredth place */ else if (n>=500) { r[i]='D'; n=n-500; continue; } else if (n>=100) { r[i]='C'; n=n-100; continue; } /* for decimal digits in tenth place */ else if (n>=50) { r[i]='L';

145

n=n-50; continue; } else if (n>=10) { r[i]='X'; n=n-10; continue; } /* for decimal digits in unit place */ else if (n>=5) { if (n==9) { r[i]='I'; n=n+1; continue; } r[i]='V'; n=n-5; continue; } else if (n>=1) { r[i]='I'; if (n==4) { n=n+1; continue; } n=n-1; continue; } else break; } r[i]='\0'; }

1. *** Program to find the Roman equivalent of a decimal number *** Enter number in decimal system (less than 4000):794 The roman equivalent of 794 is DCCLXXXXIV. 2. *** Program to find the Roman equivalent of a decimal number *** Enter number in decimal system (less than 4000):3989 The roman equivalent of 3989 is MMMDCCCCLXXXIX.

DISCUSSIONS:

1. This program finds the roman equivalent of decimal numbers between 1 and 3999. For higher decimal numbers, the equivalent roman numbers contains bars for higher Roman numeral digits. Representing a number with a bar is difficult to implement in C. 2. Instead of directly printing in the screen, a character array is used to store the roman numerals before printing. Thus using this array and modifying the program we can do more work with the roman equivalent of the number. 3. Roman numerals are commonly used in numbered lists (such as the outline format of an article), clock faces, pages preceding the main body of a book, dated notices of copyright, months of the year, successive political leaders or children with identical names, the numbering of annual events, etc.

147

ASSIGNMENT No. 24

PROGRAM STATEMENT:

Date: 24.02.2010.

Write a C program to find the age of people. (Input will be one birth date and output will be corresponding age)

THEORY:

Age refers to the length of time that an organism has lived. In other words age is the span of time between the current date and the date of birth of the organism. To find the age of people, in this program we ask the user to enter the date of birth and output the corresponding age. We get the current date by using the getdate( ) function in C. We first separately find the difference between the years, month and day of the two dates, the date of birth and the current date. Next we check if any of the field is negative. If the day field is negative, we add 30 to it and subtract one month from the month field. If the month field is negative, we add 12 to it and subtract one year from the year field. But if the year field is negative, it implies that the date of birth entered occurs after the current, thus we display appropriate error message. Next, while displaying we ignore whichever field is zero, and displays only non-negative fields.

ALGORITHM:

Procedure ShowAge( D1, D2) (* This procedure calculates the difference between two dates and hence shows the age. D1 the given date of birth, D2 the current date. *) Step 1 : [Find the difference between each field] day=day(D2) day(D1) (*day- difference of days *) mth=month(D2) - month(D1) (*mth- difference of months *) yrs=year(D2) year(D1) (*yrs- difference of years *) Step 2 : [Checking if any of the field is negative] if(day<0) then day=day+30 mth=mth-1 end if. if(mth<0) then mth=mth+12 yrs=yrs-1 end if. if(yrs<0) then Write "The person has not born yet!" Goto step 4. end if. Step 3 : [Display each field] Write(Age is : ) If(yrs>0) then Write (yrs years) If(mth>0) then Write (mth month) If(day>0) then

148

Write (day days) Step 4 :[Finished] Return.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<dos.h> typedef struct date DATE; void ShowAge(DATE D1,DATE D2) { int day,mth,yrs; /* Find difference of two dates */ day=D2.da_day-D1.da_day; mth=D2.da_mon-D1.da_mon; yrs=D2.da_year-D1.da_year; /* If current day is less than birth day */ if(day<0) { day+=30; mth--; } /* If current month is less than birth month */ if(mth<0) { mth+=12; yrs--; } /* If current year is less than b irth year */ if(yrs<0) { printf("\nThe person has not born yet!"); return; } /* Show output */ printf("\nAge is : "); if(yrs) printf(" %d years",yrs); if(mth) printf(" %d months",mth); if(day) printf(" %d days",day); } int main() { DATE CurD,BD; clrscr(); printf("\t*** Program to find the age of people *** \n\n"); /* Input birthday */ printf("Date of birth [DD -MM-YYYY] : "); scanf("%d-%d-%d",&BD.da_day,&BD.da_mon,&BD.da_year); getdate(&CurD); /* Get current date from getdate function */ ShowAge(BD,CurD); /* Show the age */ getch(); return 0; }

1. *** Program to find the age of people *** Date of birth [DD-MM-YYYY] : 28-08-1989 Age is : 20 years 11 months 3 days 2. *** Program to find the age of people *** Date of birth [DD-MM-YYYY] : 09-07-2011 The person has not born yet!

DISCUSSIONS:

1. The current date is obtained from the getdate() function which is under dos.h. Thus we avoid inputting the current date by using the library function. 2. The structure used to keep the date of birth and the current date is DATE which is defined in the library file dos.h. So, to keep date, we need not declare a structure ourselves. 3. The program checks whether the date of birth is after the current date. If it is, then it shows the appropriate error message.

150

ASSIGNMENT No. 25

PROGRAM STATEMENT:

Date: 05.03.2010.

Write a C program that accepts three text files (say f1, f2, f3) as command line arguments and merge lines alternately from two files f1 and f2 and writes the results into the third file f3. If one of the two files is finished earlier then the remaining lines from the larger file will be simply copied to the third file f3. Finally print all the three files.

THEORY:

A text file (sometimes spelled "textfile": an old alternate name is "flatfile") is a kind of computer file that is structured as a sequence of lines. A text file exists within a computer file system. The end of a text file is often denoted by placing one or more special characters, known as an end-offile marker, after the last line in a text file..txt is a filename extension for files consisting of text usually containing very little formatting (ex: no italics). The precise definition of the .txt format is not specified, but typically matches the format accepted by the system terminal or simple text editor. Files with the .txt extension can easily be read or opened by any program that reads text and, for that reason, are considered universal (or platform independent). In C it is possible to accept command line arguments. Command-line arguments are given after the name of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the operating system. To use command line arguments in your program, we must first understand the full declaration of the main function, which previously has accepted no arguments. In fact, main can actually accept two arguments: one argument is number of command line arguments, and the other argument is a full list of all of the command line arguments. A full declaration of main look like this: int main ( int argc, char *argv[] ) The integer, argc is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program. The array of character pointers is the listing of all the arguments. argv[0] is the name of the program, or an empty string if the name is not available. After that, every element number less than argc is a command line argument. We can use each argv element just like a string, or use argv as a two dimensional array. argv[argc] is a null pointer.

ALGORITHM:

Procedure filecopy( ) (* The source files f1 and f2 are opened in read mode by the file pointers fp1 and fp2 and the destination file f3 is opened in write mode by a file pointer fp3. *) Step 1: [Check for file opening error] if (fp1=NULL or fp2=NULL or fp3=NULL) Write The given job is not possible to implement. End if. Step 2: [initialize] i=0, j=0. Step 3: [ch1 is the character which is read from the source file f1] while ((ch1<> end of file) do if(ch1= New line character) then sm1[i][j]= New line character. i=i+1. j=0. else sm1[i][j]=ch1. j=j+1.

151

end if else. End while. sm1[i][j]= End of string Step 4: [Initialize] l=0, m=0. Step 5: [ch2 is the character which is read from the source file f2] while ((ch2<>end of file) do if (ch2= New line character) then sm2[l][m]= End of string. l=l+1. m=0. else sm2[l][m]=ch2. m=m+1. end if-else. End while. sm2[l][m]= End of string Step 6: [initialize] u=0,v=0. Step 7: [Write alternately lines from f1 and f2 to f3] while (u<=i and v<=l) do Write the content of the array sm1 at index u i.e. sm1[u] into the file f3. Go to a new line in the file. Write the content of the array sm2 at index v i.e. sm2[v] into the file f3. Go to a new line in the file. u=u+1. v=v+1. end while. Step 8: [if the first file is still not empty] while (u<=i) do Write the content of the array sm1 at index u i.e. sm1[u] into the file f3. Go to the next line in the file. u=u+1. end while. Step 9: [if the second file is still not empty] while (v<=l) do Write the content of the array sm2 at index v i.e. sm2[v] into the file f3. Go to the next line in the file. v=v +1. end while. Step 10: Move the file pointers fp1, fp2 and fp3 to the beginning of the files f1,f2 and f3. Step 11: [Print file f1] while (ch1<>end of file) do Write ch1. End while. Step 12: [Print file f2] while (ch2<>end of file) Write ch2. End while. Step 13: [Print file f3] while (ch3<>end of file) Write ch3. end while. Step 14: [Finished] Stop.

152

PROGRAM CODE:

#include<stdio.h> #include<conio.h> #include<string.h> #include<stdlib.h> int main(int argc,char *argv[]) { int i,j,l,m,u,v; char ch1,ch2,sm1[10][80],sm2[10][80]; FILE *fp1,*fp2,*fp3; if(argc!=4) { printf("\nInvalid no. of arguments"); getch(); } /*opening files*/ fp1=fopen(argv[1],"r"); fp2=fopen(argv[2],"r"); fp3=fopen(argv[3],"w+"); if(fp1==NULL || fp2==NULL ||fp3==NULL) { printf("\nError in opening file!"); exit(0); } i=0,j=0; /* copying entire content of the first file */ while((ch1=fgetc(fp1))!=EOF) { if(ch1=='\n') { sm1[i][j]='\0'; i++;j=0; } else { sm1[i][j]=ch1; j++; } } sm1[i][j]='\0'; l=0;m=0; /* copying entire content the second file */ while((ch2=fgetc(fp2))!=EOF)

153

{ if(ch2=='\n') { sm2[l][m]='\0'; l++;m=0; } else { sm2[l][m]=ch2; m++; } } sm2[l][m]='\0'; u=0,v=0; /* copying lines alternatively into the third file */ while(u<=i && v<=l) { fprintf(fp3,"%s",sm1[u]); fprintf(fp3,"\n\n"); fprintf(fp3,"%s",sm2[v]); fprintf(fp3,"\n\n"); u++; v++; } /*if the first file is still not empty */ while(u<=i) { fprintf(fp3,"%s",sm1[u]); fprintf(fp3,"\n\n"); u++; } /* if the second file is still not empty */ while(v<=l) { fprintf(fp3,"%s",sm2[v]); fprintf(fp3,"\n\n"); v++; } rewind(fp1); rewind(fp2); rewind(fp3); /* displaying content of all the files*/ printf("\n Content of the first file is:\n"); while((ch1=fgetc(fp1))!=EOF) printf("%c",ch1);

154

printf("\n\n\n"); printf("\n Content of the second file is: \n"); while((ch2=fgetc(fp2))!=EOF) printf("%c",ch2); printf("\n\n\n"); printf("\n Content of the merged file is: \n"); while((ch1=fgetc(fp3))!=EOF) printf("%c",ch1); fclose(fp1); fclose(fp2); fclose(fp3); getch(); return 0; }

Content of the first file is: I am a second year student. I read in Asutosh College. Content of the second file is: I study computer science honours course. I want to become a good scientist. I want to work for my country. Content of the merged file is: I am a second year student. I study computer science honours course. I read in Asutosh College. I want to become a good scientist. I want to work for my country.

DISCUSSIONS:

1. This program checks for error at time of opening each file. If error occurs it shows appropriate error message and ends. 2. The program accepts the three files as command line arguments. 3. The rewind() function is used to point file pointers to beginning of file. 4. Merging algorithm is used to implement the program.

155

ASSIGNMENT No. 26

PROGRAM STATEMENT:

Write a program to evaluate the following triangle (Pascal Triangle): 1 1 1 1 2 1 1 3 3 1 ..Up to n level.

Date: 10.03.2010.

THEORY:

In mathematics, Pascal's triangle is a geometric arrangement of the binomial coefficients in a triangle.The rows of Pascal's triangle are conventionally enumerated starting with row 0, and the numbers in each row are usually staggered relative to the numbers in the adjacent rows. A simple construction of the triangle proceeds in the following manner. On row 0, write only the number 1. Then, to construct the elements of following rows, add the number directly above and to the left with the number directly above and to the right to find the new value. If either the number to the right or left is not present, substitute a zero in its place. For example, the first number in the first row is 0 + 1 = 1, whereas the numbers 1 and 3 in the third row are added to produce the number 4 in the fourth row. Thus we are required to generate the following triangle in the screen. 1 1 1 1 2 1 1 3 3 1 ..Up to n level. The level n should be given at run-time. To generate this type of triangle we use multiple loops to traverse through each line of the program, to compute the elements, to compute the spaces, to print the elements, etc.

ALGORITHM:

Function Pascal(n) (* n is the number of lines in the pattern *) Step 1: [Initialize line counter] k=1. Step 2: [Print each line] Repeat while k<=n. Step 3: [Compute each element in the line] for i=1 to k do if i=1 OR i=k b[i]=1. else b[i]=a[i-1]+a[i]. end if else. End for. Step 4: [Copy contents of array b to array a] for j=1 to k do A[j]=b[j]. End for. Step 5: [Compute and print the spaces] for i=n down to k+1 Write .

156

End for. Step 6: [Print each element] for j=1 to k do Write a[j] End for. Step 7: [Go to next line] Go to new line. [End of Step 2 loop] Step 8: [Finished] Return.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> int main(void) { int a[100],b[100],i,j,k,n; printf("\t*** Program to evaluate Pascal triangle *** \n"); printf("\nEnter the number of lines to print: "); scanf("%d",&n); for(k=1;k<=n;k++) { printf("\n\n"); for(i=1;i<=k;i++) { if(i==1||i==k) /* for first and last element of each line */ b[i]=1; else b[i]=a[i-1]+a[i]; } for(j=1;j<=k;j++) a[j]=b[j]; for(i=n;i>k;i--) printf(" "); for(j=1;j<=k;j++) } getch(); return 0; } /* Print spaces */ /* Print each element */ /* Copy contents to a */ /* for intermediate elements of each line */ /* Traverse through each line */

printf("%6d",a[j]);

*** Program to evaluate Pascal triangle *** Enter the number of lines to print: 10

1 1 1 1 1 1 1 3 4 5 6 1 1 1 8 9 28 36 3 6 10 15 7 56 84 1 2 1 4 10 20 21 70 126 1 5 15 35 56 126 1 6 35 28 84 1 21 8 36 7 1 9 1 1 1

DISCUSSIONS:

1. Pascals triangle is actually the geometric arrangement of the binomial coefficients in a triangle. 2. We have not evaluated all the binomial coefficient by their formula, and thus avoided factorial calculation. We computed each successive term as the sum of the two intermediate terms in last level. 3. Efficient use of for loop is done to print numbers or spaces which are in some order.

158

ASSIGNMENT No. 27

PROGRAM STATEMENT:

Date: 12.03.2010.

Write a program to generate the following pattern: 1 1 12 21 12321 12 21 1 1 (The highest number within the pattern will be given at the run time. Here this is 3.

THEORY:

We are required to generate the following pattern in the screen. 1 1 12 21 12321 12 21 1 1 The highest number in the pattern will be entered by the user at run-time. This type of pattern of numbers can be generated by using multiple loops up to desired range as given input by the user.

ALGORITHM:

Function Pattern(n) (* n is the highest number in the pattern *) Step 1: [Print upto line which contains highest number in the pattern] for i=1 to n do for j=1 to i do [Print numbers] Print j. end inner for. for j=2n-2i-1 down to 1 [Print spaces] Print . end inner for. for j=i down to 1 [Print numbers] if (j!=n) Print j. end if. end inner for. Go to new line. end outer for. Step 2: [Print rest of the pattern] for i=n+1 to 2n-1 do for j=1 to 2n-i do [Print numbers] Print j. end inner for. for j=2i-2n-1 down to 1 [Print spaces] Print . end inner for. for j=2n-i down to 1 [Print numbers] Print j.

159

end inner for. Go to new line. end outer for. Step 3: [Finished] Return.

PROGRAM CODE:

#include<stdio.h> #include<conio.h> int main(void) { int i,j,k,n; printf("\nEnter the highest number within the pattern (<=9):"); scanf("%d",&n); printf("\nThe pattern with highest number %d is: \n\n",n); /* Print upto line which contain highest number */ for (i=1;i<=n;i++) { /* Print numbers */ for (j=1;j<=i;j++) printf("%d",j); /* Print spaces */ for (j=2*n-2*i-1;j>=1;j--) printf(" "); /* Print numbers */ for (j=i;j>=1;j--) if (j!=n) printf("%d",j); printf("\n"); } /* Print rest of the pattern */ for (;i<2*n;i++) { /* Print numbers */ for (j=1;j<=2*n-i;j++) printf("%d",j); /* Print spaces */ for (j=2*i-2*n-1;j>=1;j--) printf(" "); /* Print numbers */

160

for (j=2*n-i;j>=1;j--) printf("%d",j); printf("\n"); } getch(); return 0; }

Enter the highest number within the pattern:9 The pattern with highest number 9 is: 1 1 12 21 123 3 21 1234 4321 12345 54321 123456 654321 1234567 7654321 12345678 87654321 12345678987654321 12345678 87654321 1234567 7654321 123456 654321 12345 54321 1234 4321 123 321 12 21 1 1

DISCUSSIONS:

1. The program generates the pattern correctly when the highest number in the pattern is 9. If the highest number is greater than 9, then alignment needs to be done. 2. We divided the pattern into two parts in implementation. The first part prints the upper portion of the pattern i.e. up to the line which contains the highest number. The second part prints the rest of the pattern. 3. Each for loop is used to print numbers or spaces which are in some order.

- 6.11.18 css2.docxUploaded byCkreedlyf de los Santos
- Tcloud Handbuch EnUploaded byjluckhaus3145
- MacUploaded bycadcam wetech
- Manual So Touch Air Presenter PlusUploaded bykennydee
- Very Useful Commands for Registry EditorUploaded byDheeraj
- Read Me Crane Girder 20041110Uploaded byJayPatel
- CapabilitiesUploaded byPauline Alinas Mendoza
- Essential WindowsUploaded byMuhammad Idris
- TPSC-SI37461Uploaded bySatyajit Ray
- Using Your GmailUploaded byNishant Jee
- Excel Lessons IntermediateUploaded bybhell29
- (GROUP 7) MATLAB (1)Uploaded byMikhail Hasanuddin
- Flow sheet Development.docxUploaded byMehran Rasheed Goraya
- Computer for AllUploaded byntah84
- 35011929 3 en TerraStationUserGuideUploaded byมะขาม หวาน
- 1.IntroUploaded byMuhammad Adam Lim
- CAUploaded byranjit343
- Data Extraction MacroUploaded byBrian Verdine
- A Computer is a Device That Accepts InformationUploaded bykent101
- Windows Hacking Page 2 3Uploaded byarun5918
- Environments Intro 2Uploaded byCynthia Solomon
- Computer SystemUploaded bySushant Shrestha
- 6EDU342AYUploaded byAdil Akbar Janjua
- Lecture 01 Introduction to ItUploaded byfarah12345678
- Tricks in Windows 7Uploaded byFeroze Ahmed
- IBX1.1_EN_00Uploaded byChristian Fisher
- 07404-Work Zone Lane Closure Analysis ModelUploaded byMario Segura
- Chapter Guideline for thesis studyUploaded byhakira21
- The Parts of Your Computer0Uploaded bySubashini Thanikachalam D
- CSE_syllUploaded byAshish Kumar

- Meteornorm 7 - Handbook Part I - SoftwareUploaded byclubmailus
- Release NotesUploaded byTran My Le
- nevel netwareUploaded byP.s. Dhiman
- Priv Pub DriveUploaded byfifster
- Hfss10 Full BookUploaded byhoanglonghvktqs
- X-Plane Quickstart Guide EngUploaded bymacmonty
- SAG 10 User Manual V310Uploaded byasheesh_k_singh1190
- Arma2SQFScriptingGuide.pdfUploaded byt1029
- INC0708en.pdfUploaded byPaul
- Software Fluke 810Uploaded byPaulo
- Accesswave Series Upgrade Guide 7.1x or 7.2.1 to 7.3.1 a00 EnUploaded bySyar Arif
- Validation Program EnUploaded byMuhammad Ilham WH Al-Balawi
- Sekaiju App EnglishUploaded byJaki Jaziman
- Text Pad TutorialUploaded byjehora_17
- Mini Remote Control RefUploaded byJavi Ñavis
- How to Manually Uninstall Symantec Endpoint Protection 12Uploaded byLeonel Cesar
- Working With PipelinesUploaded byapi-3720097
- MR-1CP-MVSCSP_Lab_Guide_R30_.pdfUploaded byny94
- Standar Oprasional ProsedurUploaded byIlham Malik
- WD Sharespace User GuideUploaded byPriyo Sanyoto
- Age of Sail2 Pb ManualUploaded bysocratesabroad
- WindowsXP TipsUploaded byvictor_radulescu
- S Process PowerPointUploaded byBryan Boyle
- Trouble Shooting WincattUploaded byIrfan Siddique
- Oppo Forums Content R819Uploaded byHelmi Gusmindra
- DNS-320_B1_Manual_v1-00(WW)Uploaded byvenkat_nz
- 4X Pip Snager Trading Systems New VersionUploaded byRene Zeestraten
- Ringtone Conversion ProcedureUploaded bySohel Hirani
- Monrec 80 Administrator User Guide CiscoUploaded byDustinWooldridge
- Explorer InterfacesUploaded byVilciu Constantin