Sunteți pe pagina 1din 93

Ex No: 1

HISTORY OF UNIX

Most discussions of UNIX begin with the history of UNIX without explaining why the history of UNIX is important to understanding UNIX. The remainder of this document will describe some strengths and weaknesses of UNIX and attempt to explain why UNIX is becoming popular. All of UNIX's strengths and weaknesses can be directly related to the history of its development, hence a discussion of history is very useful. UNIX was originally developed at Bell Laboratories as a private research project by a small group of people starting in 1969. This group had experience with a number of different operating systems research efforts in the 1970's. The goals of the group were to design an operating system to satisfy the following objectives: 1) Simple and elegant 2) Written in a high level language rather than assembly language 3) Allow re-use of code Typical vendor operating systems of the time were extremely large and all written in assembly language. UNIX had a relatively small amount of code written in assembly language (this is called the kernel) and the remaining code for the operating system was written in a high level language called C. The group worked primarily in the high level language in developing the operating system. As this development continued, small changes were necessary in the kernel and the language to allow the operating system to be completed. Through this evolution the kernel and associated software were extended until a complete operating system was written on top of the kernel in the language C. UNIX APPLICATION PROGRAMMING INTERFACE Many proprietary operating systems have a simplified view of application behavior. The typical application reads some data from disk, tape or a terminal and does some processing. Output is produced onto disk, tape, tape, terminal, or printer. The operating systems generally provide easy to use well-implemented facilities to support these types of facilities.

As applications become more sophisticated they need new features such as network access, multi-tasking, and interprocess communications. In traditional operating systems, these features are often hard to use, not well documented, and only callable from assembly language. When a program makes use of these features, the program may be much more complex and much more difficult to maintain. In UNIX because the C language was written to be used to implement an operating system rather than a traditional "input-processing-output" application, use of these sophisticated features is quite easily done from the C language without writing any assembly language. In addition, the documentation for these sophisticated features is in the same format and location as the documentation for the normal application calls. When UNIX was distributed, users could write applications in C and easily make use of all of the operating system facilities. This allowed application developers to quickly develop much more sophisticated applications using these facilities. The pattern of development in UNIX when adding new features such as networking is to provide an application program interface from the C language to access the new features. In general UNIX system developers and application developers program in the same language using the same application programming interface. In typical proprietary operating systems, the operating systems programmers are programming in assembly language and have access to a many capabilities which are not available to the application developer. UNIX NETWORKING In 1984, the University of California at Berkeley released version 4.2BSD which included a complete implementation of the TCP/IP networking protocols. Systems based on this and later BSD releases provided a multi-vendor networking capability based on Ethernet networking. The networking support included, remote login, file transfer, electronic mail, and other important features. As UNIX was ported onto more and more different types of computer hardware the UNIX networking allowed many different types of systems to share and mutually use data. Networks consisting of many different systems could be used as a large distributed system.

When SUN Microsystems added NFS (Network File System), this ability to share and mutually use data was significantly enhanced. UNIX POPULARITY At this point, the reader might be asking, "This document is designed for first time UNIX users. Why all of this discussion about programming and system programming?" The answer is because the document is using the history of UNIX to explain why UNIX is so popular. The application portability and system programming issues have caused many hardware and software vendors to choose UNIX. The effect of many vendors choosing UNIX is that there is a wide variety of UNIX systems available to users at attractive prices. There are three primary causes for UNIX's popularity (and none is user interface): Only a very small amount of code in UNIX is written in assembly language. This makes it relatively easy for a computer vendor to get UNIX running on their system. UNIX is nearly the unanimous choice of operating system for computer companies started since 1985. The user benefit which results from this is that UNIX runs on a wide variety of computer systems. Many traditional vendors have made UNIX available on their systems in addition to their proprietary operating systems. The application program interface allows many different types of applications to be easily implemented under UNIX without writing assembly language. These applications are relatively portable across multiple vendor hardware platforms. Third party software vendors can save costs by supporting a single UNIX version of their software rather than four completely different vendor specific versions requiring four times the maintenance. Vendor-independent networking allows users to easily network multiple systems from many different vendors. These features of UNIX have contributed to its rise in popularity since the mid 1980's

USER INTERFACE So far, there has been no mention of the user interface for UNIX. UNIX is a good operating system for experienced programmers. The operating system was designed and implemented by experienced programmers so everything which the experienced programmer needs is present but not much else. A perfect example of this is the on-line documentation called "man-pages" or manual pages. The material is completely reference oriented with very little tutorial information. Experienced programmers find the man pages very useful but the beginning user often finds them overwhelming. In the last few years, there has been extensive work to improve the user interface to UNIX. The most dramatic effort has been the addition of windowing interfaces on top of UNIX such as Xwindows, Suntools, NextStep, Motif, OpenLook, etc. These windowing interfaces do not change UNIX itself but are built on top of UNIX to provide a more intuitive interface to UNIX. Each of the different user interfaces has some advantages and some disadvantages. Currently intensive development effort is being done on all of these Graphical User Interfaces (GUIs). Vendors providing UNIX also have done a work to improve the user interface of their particular versions of UNIX for users without windowing interfaces. Even with all of these efforts, UNIX is weak in the end-user interface area. USER PORTABILITY Even with a relatively poor user interface, UNIX has a following of non-programmer users. The primary reason for this is because UNIX runs on so many different computer systems ranging from small desktops to the largest computers in the world. Once a user has learned UNIX, the skills can be used on many different systems. This ability for a user to work on many different makes of computer systems without re-training is called "user portability". Many users of other operating systems have converted to using UNIX because they felt that UNIX would be the "last" operating system they would have to learn.

OPEN SYSTEMS There is a recent effort to define what is an "open system" in the international standards area. An open system is a system which allows application portability, system interoperability, and user portability between many different computer vendor hardware platforms. UNIX is a good example of the advantages to the user having an "open system".

Ex No: 2

BASIC COMMANDS IN UNIX

AIM: To study the basic commands in Linux. COMMANDS: 1. TASK COMMAND SYNTAX EXPLANATION OUTPUT 2. TASK COMMAND SYNTAX EXPLANATION OUTPUT 3. TASK COMMAND SYNTAX EXPLANATION OUTPUT 4. TASK COMMAND SYNTAX OUTPUT : To display the system date and time. : date. : date. : displays the current system date and time on the screen. : Tue Jun 19 11:37:17 GMT 2007. : To display the current month. : date. : date +%m. : This command displays the current month on the screen. : 06. : To display the name of the current month. : date. : date +%h. : This command displays the name of the current month on the screen. : Jun. : To display the current system date. : date. : date +%d. : 19.

EXPLANATION : This command displays the current system date on the screen.

5. TASK COMMAND SYNTAX OUTPUT 6. TASK COMMAND SYNTAX

: To display the current system date (year). : date. : date +%y. : 07. : To display the current system time. : date. : date +%H. screen.

EXPLANATION: This command displays the current year on the screen.

EXPLANATION: This command displays the current system time (in hours) on the OUTPUT 7. TASK COMMAND SYNTAX : 11. : To display the current system time. : date. : date +%M. screen. OUTPUT 8. TASK COMMAND SYNTAX : 43. : To display the current system time. : date. : date +%S. screen. OUTPUT 9. TASK COMMAND SYNTAX : 15. : To display the calendar of the current month. : calendar. : cal.

EXPLANATION: This command displays the current system time (in minutes) on the

EXPLANATION: This command displays the current system time (in seconds) on the

EXPLANATION: This command displays the calendar of the current month on the screen. OUTPUT S 3 10 17 24 10. TASK COMMAND SYNTAX : M 4 11 18 25 T 5 12 19 26 Jun 07 W 6 13 20 27 T 7 14 21 28 F 1 8 15 22 29 S 2 9 16 23 30

: To display user-defined message. : echo. : echo message. command.

EXPLANATION: This command displays on the screen the argument of the echo OUTPUT : echo OS. OS 11. TASK COMMAND SYNTAX : To display the details of all users. : who. : who. logged on to that system. OUTPUT : root :0 root pts/0 12. TASK COMMAND SYNTAX 2009-02-18 11:26 2009-02-18 11:56 (:0.0)

EXPLANATION: This command lists the information about all the users who have

: To display the user detail. : who. : whoami. system on the screen.

EXPLANATION: This command displays information about the current user of the OUTPUT : root.

13. TASK COMMAND SYNTAX

: To create a directory. : make directory. : mkdir. name.

EXPLANATION : This command is used to create a new directory with the specified EXAMPLE OUTPUT : mkdir student. : The directory student is created.

14. TASK COMMAND SYNTAX EXAMPLE OUTPUT 15. TASK COMMAND SYNTAX EXAMPLE OUTPUT 16. TASK COMMAND SYNTAX OUTPUT

: To change directory. : change directory. : cd directory name. : cd staff. : The directory staff is switched onto. : To delete a directory. : remove directory. : rmdir directory name : rmdir student. : The student directory is deleted. : To come out of a sub-directory. : change directory. : cd .. : [root@localhost ~]$ cd .. [root@localhost home]$ cd ~ [root@localhost ~]$

EXPLANATION : This command is used to switch from one directory to another.

EXPLANATION : This command is used to delete the specified directory.

EXPLANATION : This command helps in switching to the main directory.

17. TASK COMMAND SYNTAX OUTPUT

: To list all the files and directories. : list. : ls. :[root@localhost ~]$ ls add.c case.sh ADD.C ex3.c func4.c reverse.c Templates concatefile.sh fact.sh leap.sh storage1.c

EXPLANATION : This command displays all the files and directories of the system.

18. TASK COMMAND SYNTAX

: To create a file. : cat. : cat> file name. file name and contents.

EXPLANATION: This command leads to the creation of a new file with the specified EXAMPLE OUTPUT 19. TASK COMMAND SYNTAX EXAMPLE OUTPUT 20. TASK COMMAND SYNTAX : cat> wind. : A null file called wind is created. : To view a file. : cat. : cat file name. : cat wind. : Contents of the file called wind will be displayed on the screen. : To copy a file. : copy. : cp sourcefile destinationfile. the specified destination file by overwriting its previous contents. EXAMPLE OUTPUT : cp sun moon. : The contents of sun file will be copied to the moon file.

EXPLANATION : This command displays the contents of the specified file.

EXPLANATION : This command produces a copy of the source file and is stored in

10

21. TASK COMMAND SYNTAX

: To move a file. : move. : mv sourcefile destinationfile. the source file is deleted.

EXPLANATION : After moving the contents of the source file into destination file, EXAMPLE OUTPUT : mv sun moon. : After copying contents from the sun file to moon file, the sun file is deleted. 22. TASK COMMAND SYNTAX : To display / cut a column from a file. : cut. : cut c no. file name. specified file. EXAMPLE OUTPUT : cut c3 moon. : Those characters occurring in the 3rd column of the file called moon are displayed. 23. TASK COMMAND SYNTAX EXPLANATION EXAMPLE OUTPUT 24. TASK COMMAND SYNTAX : To delete a file. : remove. : rm file name. : This command deletes the specified file from the directory. : rm sun. : The file called sun will be deleted. : To retrieve a part of a file. : head. : head -no. of rows file name. of the specified file.

EXPLANATION : This command displays the characters of a particular column in the

EXPLANATION: This command displays the specified no. of rows form the top

11

EXAMPLE OUTPU 25. TASK COMMAND SYNTAX EXPLANATION EXAMPLE OUTPUT 26. TASK COMMAND SYNTAX EXPLANATION EXAMPLE OUTPUT

: head -1 sun. : The first row of the file called sun is displayed. : To retrieve a file. : tail. : tail -no. of rows file name. : This command displays the specified no. of rows form the bottom of the specified file. : tail -1 moon. : The last row of the file called moon is displayed. : To sort the contents of a file. : sort. : sort file name. : This command helps in sorting the contents of a file in ascending order. : sort win. : The contents of the file win are displayed on the screen in a sorted order.

27. TASK COMMAND SYNTAX EXPLANATION EXAMPLE OUTPUT

: To display the no. of characters in a file. : word count. : wc file name. : This command displays on the screen the no. of rows, words, and the sum of no. of characters and words. : wc ball. : The no. of rows, words, and no. of characters present in the file ball are displayed.

28. TASK COMMAND

: To display the calendar of a year. : cal.

12

SYNTAX

: cal year. year.

EXPLANATION : This command displays on the screen the calendar of the specified EXAMPLE OUTPUT 29. Manual command. man man This is help command, and will explains you about online manual pages you can also use man in conjunction with any command to learn more about that command for example.

: cal 2007. : The calendar of the year 2007 will be displayed.

man ls will explain about the ls command and how you can use it. man -k pattern command will search for the pattern in given command.

30. Clear command clear command clears the screen and puts cursor at beginning of first line. 31. Tty command Tty command will display your terminal. Syntax is tty options Options

-l will print the synchronous line number. -s will return only the codes: 0 (a terminal), 1 (not a terminal), 2 (invalid options) (good for scripts)

13

Ex No: 3 General Introduction

UNIX: VI EDITOR

The VI editor (short for visual editor) is a screen editor which is available on almost all Unix systems. Once you have learned vi, you will find that it is a fast and powerful editor. VI has no menus but instead uses combinations of keystrokes in order to accomplish commands. Starting VI To start using VI, at the UNIX prompt type VI followed by a file name. If you wish to edit an existing file, type in its name; if you are creating a new file, type in the name you wish to give to the new file. %vi filename Then hit Return. You will see a screen similar to the one below which shows blank lines with tildes and the name and status of the file. ~ ~ "myfile" [New file] VIs Modes and Moods VI has two modes: the command mode and the insert mode. It is essential that you know which mode you are in at any given point in time. When you are in command mode, letters of the keyboard will be interpreted as commands. When you are in insert mode the same letters of the keyboard will type or edit text. vi always starts out in command mode. When you wish to move between the two modes, keep these things in mind. You can type i to enter the insert mode. If you wish to leave insert mode and return to the command mode, hit the ESC key. If you're not sure where you are, hit ESC a couple of times and that should put you back in command mode.\ General Command Information As mentioned previously, VI uses letters as commands. It is important to note that in general vi commands:

14

are case sensitive - lowercase and uppercase command letters do different things are not displayed on the screen when you type them Generally do not require a Return after you type the command.

You will see some commands which start with a colon (:). These commands are ex commands which are used by the ex editor. ex is the true editor which lies underneath vi -- in other words, vi is the interface for the ex editor. Entering Text To begin entering text in an empty file, you must first change from the command mode to the insert mode. To do this, type the letter I. When you start typing, anything you type will be entered into the file. Type a few short lines and hit Return at the end of each of line. Unlike word processors, vi does not use word wrap. It will break a line at the edge of the screen. If you make a mistake, you can use the Backspace key to remove your errors. If the Backspace key doesn't work properly on your system, try using the Ctrl h key combination. Moving One Character at a Time Try using your direction keys to move up, down, left and right in your file. Sometimes, you may find that the direction keys don't work. If that is the case, to move the cursor one character at the time, you may use the h, j, k, and l keys. These keys move you in the following directions: h j beep. Moving among Words and Lines While these four keys (or your direction keys) can move you just about anywhere you want to go in your file, there are some shortcut keys that you can use to move a little more quickly through a document. To move more quickly among words, you might use the following: w b moves the cursor forward one word moves the cursor backward one word (if in the middle of a word, b will move you to the beginning of the current word). left one space down one space l k right one space up one space

If you move the cursor as far as you can in any direction, you may see a screen flash or hear a

15

moves to the end of a word. To build on this further, you can precede these commands with a number for greater

movement. For example, 5w would move you forward five words; 12b would move you backwards twelve words. [You can also use numbers with the commands mentioned earlier. For example, 5j would move you down 5 characters.] Shortcuts Two short cuts for moving quickly on a line include the $ and the 0 (zero) keys. The $ key will move you to the end of a line, while the 0 will move you quickly to the beginning of a line. Screen Movement To move the cursor to a line within your current screen uses the following keys: H M L Ctrl-f Ctrl-b Ctrl-u Ctrl-d moves the cursor to the top line of the screen. moves the cursor to the middle line of the screen. moves the cursor to the last line of the screen. To scroll through the file and see other screens use: scrolls down one screen scrolls up one screen scrolls up a half a screen scrolls down a half a screen Two other useful commands for moving quickly from one end to the other of a document are G to move to the end of the file and 1G to move to the beginning of the file. If you precede G with a number, you can move to a specific line in the document (e.g. 15G would move you to line 15). Moving by Searching One method for moving quickly to a particular spot in your file is to search for specific text. When you are in command mode, type a / followed the text you wish to search for. When you press Return, the cursor will move to the first incidence of that string of text. You can repeat the search by typing n or search in a backwards direction by using N.

16

Basic Editing To issue editing commands, you must be in command mode. As mentioned before, commands will be interpreted differently depending upon whether they are issued in lower or upper case. Also, many of the editing commands can be preceded by a number to indicate a repetition of the command. Deleting (or Cutting) Characters, Words, and Lines To delete a character, first place your cursor on that character. Then, you may use any of the following commands: x X dw dd D deletes the character under the cursor. deletes the character to the left of your cursor. deletes from the character selected to the end of the word. deletes all the current line. deletes from the current character to the end of the line. Preceding the command with a number will delete multiple characters. For example, 10x will delete the character selected and the next 9 characters; 10X will delete the 10 characters to the left of the currently selected character. The command 5dw will delete 5 words, while 4dd deletes four lines. Pasting Text using Put Often, when you delete or cut text, you may wish to reinsert it in another location of the document. The Put command will paste in the last portion of text that was deleted since deleted text is stored in a buffer. To use this command, place the cursor where you wish the deleted text to appear. Then use p to reinsert the text. If you are inserting a line or paragraph use the lower case p to insert on the line below the cursor or upper case P to place in on the line above the cursor. Copying Text with Yank If you wish to make a duplicate copy of existing text, you may use the yank and put commands to accomplish this function. Yank copies the selected text into a buffer and holds it until another yank or deletion occurs. Yank is usually used in combination with a word or line object such as the ones shown below: 17

yw yy

copies a word into a buffer (7yw copies 7 words) copies a line into a buffer (3yy will copy 3 lines) Once the desired text is yanked, place the cursor in the spot in which you wish to insert the

text and then use the put command ( p for line below or P for line above) to insert the contents of the buffer. Replacing or Changing Characters, Words, and Lines When you are using the following commands to replace text, you will be put temporarily into insert mode so that you can change a character, word, line, or paragraph of text. r R cw replaces the current character with the next character you enter/type. Once you enter the character you are returned to command mode. puts you in overtype mode until you hit ESC which will then return you to command mode. changes and replaces the current word with text that you type. A dollar sign marks the end of the text you're changing. Pressing ESC when you finish will return you to command mode. Inserting Text If you wish to insert new text in a line, first position the cursor to the right of where you wish the inserted text to appear. Type i to get into insert mode and then type in the desired text (note that the text is inserted before the cursor). Press ESC to return to command mode. Inserting a Blank Line To insert a blank line below the line your cursor is currently located on, use the o key and then hit ESC to return to the command mode. Use O to insert a line above the line the cursor is located on. Appending Text You can use the append command to add text at any place in your file. Append ( a) works very much like Insert (i) except that it insert text after the cursor rather than before it. Append is probably used most often for adding text to the end of a line. Simply place your cursor where you wish to append text and press a. Once you've finished appending, press ESC to go back to command mode. 18

Joining Lines Since vi does not use automatic word wrap, it is not unusual in editing lines to end up with lines that are too short and that might be improved if joined together. To do this, place your cursor on the first line to be joined and type J. As with other commands, you can precede J with a number to join multiple lines (4J joins 4 lines). Undoing Be sure to remember this command. When you make a mistake you can undo it. DO NOT move the cursor from the line where you made the change. Then try using one of the following two commands: u U undoes the last change you made anywhere in the file. Using u again will "undo the undo". undoes all recent changes to the current line. You can not have moved from the line to recover the original line. Closing and Saving Files When you edit a file in vi, you are actually editing a copy of the file rather than the original. The following sections describe methods you might use when closing a file, quitting vi, or both. Quitting and Saving a File The command ZZ (notice that it is in uppercase) will allow you to quit vi and save the edits made to a file. You will then return to a Unix prompt. Note that you can also use the following commands: :w :q :wq to save your file but not quit vi (this is good to do periodically in case of machine crash!). to quit if you haven't made any edits. to quit and save edits (basically the same as ZZ).

Quitting without Saving Edits Sometimes, when you create a mess (when you first start using vi this is easy to do!) you may wish to erase all edits made to the file and either start over or quit. To do this, you can choose 19

from the following two commands:

:e! :q!

Reads the original file back in so that you can start over. Wipes out all edits and allows you to exit from vi. More about Combining Commands, Objects, and Numbers

Now that you've learned some basic vi commands you might wish to expand your skills by trying some fancy combination steps. Some commands are generally used in combination with a text object. We've already seen some examples of this. For example, when you use the command dw to delete a word, that combines the delete (d) command with the word (w) text object. When you wish to delete multiple words, you might add a number to this combination. If you wished to delete 2 words you might use 2dw or d2w. Either of these combinations would work. So, as you can see, the general format for a command can be (number) (command) (text object) or (command) (number) (text object) You might wish to try out some of the following combinations of commands and objects: Command d (delete) y (yank/copy) c (change) Text Object w (word to the left) b (word to the right or backward) e (end of word) H (top of the screen) L (bottom of the screen) M (middle of the screen) 0 (zero - first character on a line) $ (end of a line) ( (previous sentence) ) (next sentence) [ (previous section) ] (next section) Repeating a Command If you are doing repetitive editing, you may wish to use the same command over and over. vi will allow you to use the dot (.) to repeat the last basic command you issued. If for example, you 20

wished to deleted several lines, you could use dd and then . (dot) in quick succession to delete a few lines.

Useful vi Commands Cut/Paste Commands: x dw dd D d$ :u p,P J "[a-z]nyy "[a-z]p/P delete one character (destructive backspace) delete the current word (Note: ndw deletes n numbered words) delete the current line (Note: ndd deletes n numbered lines) delete all content to the right of the cursor same as above undo last command paste line starting one line below/above current cursor location combine the contents of two lines yank next n lines into named buffer [a-z] place the contents of selected buffer below/above the current line

Extensions to the Above Commands: :3,18d 16,25m30 23,29co62 delete lines 3 through 18 move lines 16 through 25 to after line 30 copy specified lines and place after line 62

Cursor Relocation commands: :[n] shift g h/l/j/k ^f/^b ^u/^d $ 0 goto line [n] place cursor on last line of text move cursor left, right, down and up move forward, backward in text, one page move up, down one half page move to end of line move to beginning of line

Extensions to the Above: b move backwards one word (Note: nb moves back n number of words) 21

move to end of current word

( )

move to beginning of curent block move to the end of current block

Searching and Substitution commands: / [string] search forward for string ? [string] search backwards for string n N cw c$ c0 :1,$s/s1/s2/g r repeat last search repeat search in opposite direction change the contents of the current word, (use ESC to stop replacement mode) Replace all content to the right of cursor (exit replacement mode with ESC) Replace all content to the left of cursor (exit with ESC) (Yow!) global replacement of string1 with string2 replace current character with next character typed

Entering the Insert Mode: i I a A o/O ESC Begin inserting text at current cursor location Begin inserting text at the beginning of the current line Begin appending text, one character to the right of current cursor location Begin appending text at the end of the current line Begin entering text one line below\above current line Exit insertion mode and return to command mode

Exiting and Entering VI ZZ :wq save file and exit VI same as above 22

:e!

return to last saved version of current file

:q :w Fancy Stuff: :1,10w file :340,$w >> file :sh ^d :![command] :r![command] :r[filename] :$r newfile :r !sort file :n :^g :set number :set showinsert :set all :set ai

quit without save, (Note :q! is required if changes have been made) write without exit (:w! to force write) write lines 1 through 10 to file newfile write lines 340 through the end of the file and append to file newfile escape temporarily to a shell return from shell to VI execute UNIX command without leaving VI read output of command into VI read filename into VI read in newfile and attach at the end of current document read in contents of file after it has been passed through the UNIX sort open next file (works with wildcard filenames, ex: vi file*) list current line number show line numbers show flag ("I") at bottom of screen when in insert mode display current values of VI variables set autoindent; after this enter the insert mode and tab, from this point on VI will indent each line to this location. Use ESC to stop the indentations.

^T ^D :set tabstop=n >> <<

set the autoindent tab one tab stop to the right set the autoindent tab one stop to the left sets default tab space to number n shift contents of line one tab stop to the right shift contents of line one tab stop to the left

23

Ex No: 4

SHELL PROGRAMMING

A Linux shell is a command language interpreter, the primary purpose of which is to translate the command lines typed at the terminal into system actions. The shell itself is a program, through which other programs are invoked What is a shell script? A shell script is a file containing a list of commands to be executed by the Linux shell. shell script provides the ability to create your own customized Linux commands Linux shell have sophisticated programming capabilities which makes shell script powerful Linux tools How to work with shell? Step1: In the dollar prompt type $ vi < file name> Where vi is the editor, it will open a new window in which you can type the program you want Step2: After typing the program press ESC and : together then at the bottom of the vi screen you can see i.e. prompt .In that type as wq which means write and quit i.e. the content what is typed will be written and saved into that file that has been created Step3: Once wq is typed at the: prompt, the prompt would change to $ symbol in which you have to do the following $ sh < file name > 24

Sh

command is used to run the shell program

<file name> - is the name of the file for which the output is to be got Basically to print a text in the your shell programs echo command is used SYNTAX FOR LOOPING STATEMENTS IF THEN-ELSE CONSTRUCT if [ condition] then else statements fi (end of if) WHILE while <condition> do <statements> Done <action>

25

CASE Case $<option> in 4) <statements>;; 5) <statements>;; 6) .. 7) . . . *) <error statement>;; esac For loop For(( intitialization;condition;incremetation/decrementation))

26

AREA OF RECTANGLE

AIM: To write a shell script to find the area of the rectangle.

ALGORITHM: Step1: Step2: Step3: Step4: Step5: Start the program Read l and b Calculate AREA = l x b Print the Area Stop the program

PROGRAM: [student@localhost ~]$ vi area.sh echo Enter the length and breadth read l b let area=$l*$b echo The area is "$area"

27

OUTPUT: [student@localhost ~]$ sh area.sh Enter the length and breadth 46 The area is 24

RESULT: Thus the shell script to print the area of rectangle is successfully completed and verified. 28

GREATEST AMONG THREE NUMBERS.

AIM: To write a shell script to find the greatest among three numbers.

ALGORITHM: Step1: Step2: Step3: Step4: Step5: Start the program Read a,b,c Check wheather a (or) b (or) c is greater Print a (or) b (or) c Stop the program

PROGRAM: [student@localhost ~]$ vi big.sh echo enter three numbers read a b c if [ $a -gt $b -a $a -gt $c ] then echo "a is big" elif [ $b -gt $c ] then echo " b is big" else echo " c is big" fi

29

OUTPUT: [student@localhost ~]$ sh big.sh enter three numbers 11 2 3 a is big [student@localhost ~]$ sh big.sh enter three numbers 12 33 22 b is big [student@localhost ~]$ sh big.sh enter three numbers 11 22 33 c is big

RESULT: Thus the shell script has been written and the output is verified successfully. 30

PRINT NUMBERS USING WHILE LOOP

AIM: To print natural numbers up to n using while loop.

ALGORITHM: Step1: Step2: Step3: Step4: Step5: Step6: Step7: Start the program Read the value for n Enter the upper limit Consider i = i and calculate [$i-lt$n] i =i+1 Print i Stop the program

PROGRAM: [student@localhost ~]$ vi while1.sh echo enter upper limit read n let i=1 while [ $i -lt $n ] do echo "$i" let i=i+1 done

31

OUTPUT: [student@localhost ~]$ sh while1.sh enter upper limit 5 1 2 3 4

RESULT: Thus the shell script has been written and the output is verified successfully. 32

MULTIPLICATION TABLE

AIM: To write a shell script to display the multiplication table.

ALGORITHM: Step1: Start the program Step2: Read a =1; b =1 Step3: Calculate while [$a!=5] for b in 1 2 3 4 5 6 7 8 9 10 u =$a*$b, b =$b+1, a =$b+1, a =$a+1 Step4: Display the Multiplication table Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi table.sh let a=1; let b=1; while [ $a != 4 ] do for b in 1 2 3 4 5 6 7 8 9 10 do let u=$a*$b echo $b X $a = $u let b=$b+1 done let a=$a+1 echo " " done

33

OUTPUT: [student@localhost ~]$ sh table.sh 1X1=1 2X1=2 3X1=3 4X1=4 5X1=5 6X1=6 7X1=7 8X1=8 9X1=9 10 X 1 = 10 1X2=2 2X2=4 3X2=6 4X2=8 5 X 2 = 10 6 X 2 = 12 7 X 2 = 14 8 X 2 = 16 9 X 2 = 18 10 X 2 = 20 1X3=3 2X3=6 3X3=9 4 X 3 = 12 5 X 3 = 15 6 X 3 = 18 7 X 3 = 21 8 X 3 = 24 9 X 3 = 27 10 X 3 = 30

RESULT: 34

Thus the shell script has been written and the output is verified successfully.

PRINT NATURAL NUMBERS USING FOR LOOP

AIM: To write a shell script to print the number using for loop.

ALGORITHM: Step1: Step2: Step3: Step4: Step5: Start the program Read i as 1, 2, 3, 4, 5 Calculate i as 1, 2, 3, 4, 5 Print 1, 2, 3, 4, 5 Stop the program

PROGRAM: [student@localhost ~]$ vi for.sh for i in 1 2 3 4 5 do echo $i done

35

OUTPUT: [student@localhost ~]$ sh for.sh 1 2 3 4 5

RESULT: Thus the shell script has been written and the output is verified successfully. 36

FINDING ODD POSITION

AIM: To write a shell script to find the odd position in a five digit number.

ALGORITHM: Step1: Start the program Step2: Read a Step3: Calculate b =$a%10 a =$i%2 Step4: If [$c! =0] Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi find.sh echo enter the number read a for i in 1 2 3 4 5 { let b=$a%10 let c=$i%2 if [ $c != 0 ] then echo $b fi let a=$a/10 }

37

OUTPUT: [student@localhost ~]$ sh find.sh enter the number 12345 5 3 1

RESULT: Thus a shell script has been written and output is successfully verified. 38

ARITHMETIC CALCULATOR

AIM: To write a shell script to design an arithmetic calculator.

ALGORITHM: Step1: Step2: Step3: Step4: Strat the program Read a and b Select 1.Add, 2.Sub, 3.Mul, 4.Div Calculate c=a+b, c=a-b, c=a*b, c=a/b Step5: Print c. Step6: Stop the program.

PROGRAM: [student@localhost ~]$ vi case.sh echo "enter two numbers" read a b echo "1.add 2.sub 3.mul 4.div" read op case $op in 1) let x=$a+$b echo $x ;; 2) let x=$a-$b echo $x ;; 3) let x=$a*$b echo $x ;; 4) let x=$a/$b echo $x 39

;; 5) exit esac

OUTPUT: [student@localhost ~]$ sh case.sh enter two numbers 11 11 1.add 2.sub 3.mul 4.div 1 22 [student@localhost ~]$ sh case.sh enter two numbers 34 23 1.add 2.sub 3.mul 4.div 2 11 [student@localhost ~]$ sh case.sh enter two numbers 23 4 1.add 2.sub 3.mul 4.div 3 92 [student@localhost ~]$ sh case.sh enter two numbers 24 12 1.add 2.sub 3.mul 4.div 4 [student@localhost ~]$ sh case.sh enter two numbers 36 12 1.add 2.sub 3.mul 4.div 4 3 [student@localhost ~]$ exit RESULT: 40

Thus the shell script has been written and the output has been verified successfully.

SUM OF FIVE DIGIT NUMBER

AIM: To write a shell script to find the sum of five numbers.

ALGORITHM: Step1: Step2: Step3: Step4: Start the program Read a Calculate i as 1, 2, 3, 4, 5 Calculate b =a%10 sum = sum+b a =a/10 Step5: Print the sum Step6: Stop the program

PROGRAM: [student@localhost ~]$ vi sumofdigits.sh echo Enter a five digit number read a for i in 1 2 3 4 5 do let b=$a%10 let sum=$sum+$b a=$a/10 if [ $i == 5 ] then echo The sum is "$sum" fi done

41

OUTPUT: [student@localhost ~]$ sh sumofdigits.sh Enter a five digit number 23456 The sum is 20

RESULT: Thus the shell program has been written and the output is verified successfully. 42

FACTORIAL OF A GIVEN NUMBER

AIM: To write a shell script to find the factorial of a given number.

ALGORITHM: Step1: Start the program Step2: Read a Step3: Calculate a =a * i i =i-1 Step4: Print the factorial of the number Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi fact.sh echo Enter the number read a let b=$a let i=$b-1 while [ $i -gt 0 ] do let a=$a*$i let i=$i-1 done echo The factorial of the number is $a

43

OUTPUT: [student@localhost ~]$ sh fact.sh Enter the number 5 The factorial of the number is 120

RESULT: Thus the shell script has been written and the output is verified successfully. 44

LEAP YEAR OR NOT

AIM: To write a shell script to find whether the given year is leap year or not.

ALGORITHM: Step1: Step2: Step3: Step4: Start the program Read the year Print whether the year is leap or not Stop the program

PROGRAM: [student@localhost ~]$ vi leap.sh echo enter year read year let x=$year%100 let y=$year%400 let z=$year%4 if [ $x -eq 0 ] then if [ $y -eq 0 ] then echo $year is a leap year else echo $year is not leap year fi else if [ $z -eq 0 ] then echo $year is a leap year else echo $year is not a leap year fi fi 45

OUTPUT: [student@localhost ~]$ sh leap.sh enter year 2008 2008 is a leap year [student@localhost ~]$ sh leap.sh enter year 2003 2003 is not a leap year

RESULT: 46

Thus the shell script has been written and the output s verified successfully.

CONCATENATION OF TWO STRINGs

AIM: To write a shell script to concatenate and find the length of the given two strings.

ALGORITHM: Step1: Step2: Step3: Step4: Step5: Start the program Read str1, str2 Calculate len =a1+a2 Display the length of the concatenated string and concatenated string. Stop the program

PROGRAM: [student@localhost ~]$ vi concatstr.sh echo enter the string read str1 let a1=${#str1} echo enter the string read str2 let a2=${#str2} let len=$a1+$a2 echo the length of the concatenated string is $len echo the concatenated string is $str1$str2

47

OUTPUT: [student@localhost ~]$ sh concatstr.sh enter the string wel enter the string come the length of the concatenated string is 7 the concatenated string is welcome

RESULT: Thus the shell script has been written and the output is verified successfully. 48

MATCHING THE SUB-STRING IN A STRING

AIM: To write a shell script to find and match the position of a sub-string in a string.

ALGORITHM: Step1: Step2: Step3: Step4: Step5: Step6: Step7: Start the program Read str1, str2 Calculate len1 =${#str1}-1, b =0, c =0 while [$c1 =$len1] If [$str2 =${str1:$c:2} Display the position matched at $d and not matched with string Stop the program

PROGRAM: [student@localhost ~]$ vi substr.sh echo enter the string read str1 echo enter the substring read str2 let len1=${#str1}-1 let b=0 let c=0 while [ $c != $len1 ] do if [ $str2 == ${str1:$c:2} ] then let d=$c let d=$d+1 echo position matched at $d break else let b=$b+1 fi let c=$c+1 done 49

let d=$d+1 if [ $b == $len1 ] then echo not match with string fi

OUTPUT: [student@localhost ~]$ sh substr.sh enter the string welcome enter the substring me position matched at 6 [student@localhost ~]$ sh substr.sh enter the string welcome enter the substring wl not match with string

RESULT: Thus the shell script has been written and the output has been verified successfully. 50

CONCATENATION OF TWO FILES

AIM: To write a shell script to concatenate two files.

ALGORITHM: Step1: Step2: Step3: Step4: Step5: Start the program Read str1, str2 Cat $str1 >> $str2 Display str1, str2 Stop the program

PROGRAM: [student@localhost ~]$ vi concatefile.sh echo enter a file read str1 echo enter second file read str2 echo $str1 cat $str1>>$str2

51

OUTPUT: [student@localhost ~]$ cat >> xx hello welcome [student@localhost ~]$ cat >> yy hai [student@localhost ~]$ sh concatefile.sh enter a file xx enter second file yy xx [student@localhost ~]$ cat yy hai hello welcome

RESULT: Thus the shell script has been written and the output is verified successfully. 52

STRING EQUALITY

AIM: To write a shell script to find whether the strings are equal or not.

ALGORITHM: Step1: Step2: Step3: Step4: Step5: Start the program Read s1, s2 Calculate if [$s1 =$s2] Display the given strings are equal or not Stop the program

PROGRAM: [student@localhost ~]$ vi string.sh echo enter string 1 read s1 echo enter string 2 read s2 if [ $s1 == $s2 ] then echo The given string are equal else echo The given strings are not equal fi

53

OUTPUT: [student@localhost ~]$ sh string.sh enter string 1 hello enter string2 hai The given strings are not equal [student@localhost ~]$ sh string.sh enter string 1 welcome enter string2 welcome The given string are equal

RESULT: Thus the shell script has been written and the output has been verified successfully. 54

SWAPPING OF TWO VARIABLES

AIM: To write a shell script to swap two variable.

ALGORITHM: Step1: Step2: Step3: Step4: Step5: Start the program Read a, b Calculate c =$a; a =$b; b =$c Display the swapped numbers Stop the program

PROGRAM: [student@localhost ~]$ vi swap.sh echo Enter any two numbers: read a read b echo The numbers are $a and $b let c=$a let a=$b let b=$c echo The swapped numbers are $a and $b

55

OUTPUT: [student@localhost ~]$ sh swap.sh Enter any two numbers: 1 2 The numbers are 1 and 2 The swapped numbers are 2 and 1

RESULT: 56

Thus the shell script has been written and the output is verified successfully.

INTERCHANGING THE VALUES USING IF STATEMENT

AIM: To write a C program to interchange the values of two variables using simple if statement.

ALGORITHM: Step1: Start the program Step2: Read the values of a,m,n Step3: Calculate if(m>n) a=m m=n n=a Step4: Print the interchanged values of n,m Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi ex1.c #include <stdio.h> main() { int m,n,a; printf("enter two numbers"); scanf("%d%d",&m,&n); if(m>n) { a=m; m=n; n=a; } printf("the interchanged value is:%d\n%d\n",n,m); }

57

OUTPUT: [student@localhost ~]$ cc ex1.c [student@localhost ~]$ ./a.out enter two numbers56 34 the interchanged value is:34 56

RESULT: 58

Thus the C program has been written and the output is verified successfully.

GREATEST AMONG TWO NUMBERS USING IF-ELSE AIM: To write a C program to find the greatest among two numbers using if-else statement.

ALGORITHM: Step1: Start the program Step2: Read the values i,j,big Step3: Calculate if (big>j);if(i>j) Step4: Print the biggest of two numbers Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi big2.c #include<stdio.h> main() { int i,j,big; printf("enter two values"); scanf("%d%d",&i,&j); big=i; if(big<j) { big=j; } printf("biggest of two numbers is%d\n",big); if(i<j) { big=j; } else { big=i; } printf("biggest of two numbers is%d\n",big); } 59

OUTPUT: [student@localhost ~]$ cc big2.c [student@localhost ~]$ ./a.out enter two values 45 34 biggest of two numbers is45 biggest of two numbers is45 [student@localhost ~]$ ./a.out enter two values34 12 biggest of two numbers is34 biggest of two numbers is34

RESULT: Thus the C program has been written and the output is verified successfully. 60

ILLUSTRATION OF GAMES USING NESTED IF-ELSE

AIM: To write a C program to illustrate the game using nested if- else concept.

ALGORITHM: Step1: Start the program Step2: Read the value of n Step3: Calaulate if(n=1) else if (n=2) Step4: Print the games Step5: Stop the program

PROGRAM: [sudent@localhost ~]$ vi ex3.c #include<stdio.h> main() { int n; printf("\n enter a number\n1.foot ball\n2.cricket"); scanf("%d",&n); if(n==1) printf("\n play football"); else { if(n==2) printf("\n play cricket"); else printf("dont play"); } }

61

OUTPUT: [student@localhost ~]$ cc ex3.c [student@localhost ~]$ ./a.out enter a number 1.foot ball 2.cricket 1 play football [student@localhost ~]$ ./a.out enter a number 1.foot ball 2.cricket 2 play cricket [student@localhost ~]$ ./a.out enter a number 1.foot ball 2.cricket 3 dont play

62

RESULT: Thus the C program has been written and the output is verified successfully.

REVERSE THE GIVEN NUMBER USING WHILE LOOP

AIM: To write a C program to reverse the given number using while loop.

ALGORITHM: Step1: Start the program Step2: Read numbers,digit,rev=0 Step3: Calculate while (number!=0),digit =number%10;rev=rev*10+digit;number=number/10 Step4: Display the rev Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi reverse.c #include<stdio.h> main() { int number,digit,rev=0; printf("enter the number"); scanf("%i",&number); while(number!=0) { digit=number%10; rev=rev*10+digit; number=number/10; } printf("%d",rev); }

63

OUTPUT: [student@localhost ~]$ cc reverse.c [student@localhost ~]$ ./a.out enter the number12345 54321

RESULT: 64

Thus the C program has been written and the output is verified successfully.

ADDITION OF 10 NUMBERS USING DO-WHILE LOOP.

AIM: To write a C program to add numbers upto 10 using do-while loop.

ALGORITHM: Step1: Start the program Step2: Initialize i=1, sum=0 Step3: Calculate sum=sum+i Increment i. Step4: Print the sum of numbers upto 10 Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi add.c #include<stdio.h> main() { int i=1,sum=0; do { sum=sum+i; i++; } while(i<=10); printf("sum of the numbers upto 10 is...%d\n",sum); }

65

OUTPUT: [student@localhost ~]$ cc add.c [student@localhost ~]$ ./a.out sum of the numbers upto 10 is...55

RESULT: Thus the C program has been written and the output has been verified successfully. 66

PRINT THE NUMBERS IN DECREASING AND INCREASING ORDER

AIM: To write a C program to print the numbers in increasing and decreasing order.

ALGORITHM: Step1: Start the program Step2: Initialize n,x,y Step3: Assume x=y=n Step4: Calculate for(;;(x++,y--)) Step5: Print y and x Step6: Stop the program

PROGRAM: [student@localhost ~]$ vi for.c #include<stdio.h> main() { int n,x,y; printf("enter a number"); scanf("%d",&n); x=y=n; printf("-------------\n"); printf("(--) (++) \n"); printf("-------------\n"); for(;;(x++,y--)) { printf("%d\t%d\n",y,x); if(y==0) break; } } 67

OUTPUT: [student@localhost ~]$ cc for.c [student@localhost ~]$ ./a.out enter a number10 ------------(--) (++) ------------10 10 9 11 8 12 7 13 6 14 5 15 4 16 3 17 2 18 1 19 0 20

RESULT: 68

Thus the C program has been written and the output has been verified successfully.

STUDENTS MARK LIST AND AVERAGE

AIM: To write a C program to display student mark and average using for loop.

ALGORITHM: Step1: Start the program Step2: Read the values of a,b,c,d,e,total =0,i,m,avg Step3: Calculate total=a+b+c+d+e Avg=total/5 Step4: Print the total and average Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi student.c #include<stdio.h> main() { int a,b,c,d,e,total=0,i,m; float avg; printf("enter number of student"); scanf("%d",&m); printf("enter the marks of five subjects.\n"); for(i=1;i<=m;i++) { printf("[%d]student: ",i); if(scanf("%d%d%d%d%d",&a,&b,&c,&d,&e)==5) { total=a+b+c+d+e; avg=total/5; printf("total marks of the student: %d\n",total); printf("average marks of the student: %f\n",avg); } 69

else { printf("entered data is invalid"); } } }

OUTPUT: [student@localhost ~]$ cc student.c [student@localhost ~]$ ./a.out enter number of student2 enter the marks of five subjects. [1]student: 89 78 80 90 89 total marks of the student: 426 average marks of the student: 85.000000 [2]student: 56 76 87 45 65 total marks of the student: 329 average marks of the student: 65.000000

RESULT: 70

Thus the C program has been written and the output is verified successfully.

ODD OR EVEN

AIM: To write a C program to check whether the given number is odd or even.

ALGORITHM: Step1: Start the program Step2: Read the values of i,n Step3: Calculate for (i=1;i<=n;i=i+1) Step4: Print the even or odd numbers Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi switch.c #include<stdio.h> main() { int i,n; printf("enter a number"); scanf("%d",&n); for(i=1;i<=n;i=i+1) { switch(i%2) { case 0: printf("the number %d is even\n",i); break; case 1: printf("the number %d is odd\n",i); break; } } } 71

OUTPUT: [student@localhost ~]$ cc switch.c [student@localhost ~]$ ./a.out enter a number5 the number 1 is odd the number 2 is even the number 3 is odd the number 4 is even the number 5 is odd

RESULT: 72

Thus the C program has been written and the output is verified successfully.

ARITHMETIC CALCULATOR

AIM: To write a C program to design an arithmetic calculator.

ALGORITHM: Step1: Start the program Step2: Read the values of a, b, c=0, op Step3: Calculate: addition, subtraction, multiplication and division of c Step4: Print the value of c Step5: Stop the program PROGRAM: [student@localhost ~]$ vi calci.c #include<stdio.h> main() { int a,b,c=0; char op; printf("CALCULATION CODE"); printf("\n + ADD\n - SUB\n * MUL\n / DIV\n"); printf("Enter code..."); scanf("%c",&op); printf("enter values...."); scanf("%d%d",&a,&b); switch(op) { case '+': c=a+b; break; case '-': c=a-b; break; case '*': c=a*b; break; 73

case '/': c=a/b; break; } printf("\n result is... %d",c); }

OUTPUT: [student@localhost ~]$ cc calci.c [student@localhost ~]$ ./a.out CALCULATION CODE + ADD - SUB * MUL / DIV Enter code...+ enter values....12 12 result is... 24 [student@localhost ~]$ ./a.out CALCULATION CODE + ADD - SUB * MUL / DIV Enter code...enter values....45 56 result is... -11 [student@localhost ~]$ ./a.out CALCULATION CODE + ADD - SUB * MUL / DIV Enter code...* enter values....12 5 result is... 60 [student@localhost ~]$ ./a.out CALCULATION CODE + ADD - SUB * MUL / DIV Enter code.../ enter values....24 12 result is... 2 74

RESULT: Thus the C program has been written and the output has been verified successfully.

PRINTING VARIABLES FROM MEMORY ADDRESS

AIM: To write a C program to print variables from a memory address.

ALGORITHM: Step1: Start the program Step2: Read the values of *a,*n,size Step3: Calculate n=(int*),malloc(size*size of int) for(a=n;a<n+s;a++) for(a=n+size-1;a>=n;a--) Step4: Print the values and the address where values are stored Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi storage1.c #include<stdio.h> #include<stdlib.h> main() { int *a,*n,size; printf("enter the size"); scanf("%d",&size); n=(int *)malloc(size * sizeof(int)); printf("address of the first byte is.... %u\n",n); printf("enter the values..."); for(a=n;a<n+size;a++) scanf("%d",a); printf("printing the values...\n"); for(a=n+size-1;a>=n;a--) printf("%d is stored in address %u\n",*a,a); }

75

OUTPUT: [student@localhost ~]$ cc storage1.c [student@localhost ~]$ ./a.out enter the size5 address of the first byte is.... 164458504 enter the values...1 2 3 4 5 printing the values... 5 is stored in address 164458520 4 is stored in address 164458516 3 is stored in address 164458512 2 is stored in address 164458508 1 is stored in address 164458504

RESULT: 76

Thus the C program has been written and the output is verified successfully.

ALTERING CONTENTS OF ANALLOCATED MEMORY

AIM: To write a C program to alter the content of an allocated memory.

ALGORITHM: Step1: Start the program Step2: Initialize p=(char*)malloc(6) Step3: Calculate strcpy(p.madras) Strcpy(p.chennai) Step4: Display p Step5: Stop the program

PROGRAM: [aarthi@localhost ~]$ vi storage2.c #include<stdio.h> #include<stdlib.h> #include<string.h> main() { char *p; p=(char *)malloc(6); strcpy(p,"MADRAS"); printf("Memory contains:%s\n",p); p=(char *)realloc(p,7); strcpy(p,"CHENNAI"); printf("Memory now contains:%s\n",p); free(p); }

77

OUTPUT: [student@localhost ~]$ cc storage2.c [student@localhost ~]$ ./a.out Memory contains:MADRAS Memory now contains:CHENNAI

RESULT: 78

Thus the C program has been written and the output is verified successfully.

PRINTING ADRESS AND VALUE OF THE VARIABLE USING POINTERS

AIM: To write a C program to print the address and value of the variable using pointers.

ALGORITHM: Step1: Start the program Step2: Initialize the values x=22,*a Step3: Assume that the a=&x Step4: Print values of x,address of x and value at address Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi pointer1.c #include<stdio.h> #include<stdlib.h> main() { int x = 22; int *a; a = &x; printf("\n value of x=%d",*a); printf("\n address of x=%u",&x); printf("\n value at address %u = %d", &x, *(&x)); }

79

OUTPUT: [student@localhost ~]$ cc pointer1.c [student@localhost ~]$ ./a.out value of x=22 address of x=3218743884 value at address 3218743884 = 22

RESULT: Thus the C program has been written and the output is verified successfully. 80

ACCESSING VARIABLE USING POINTERS

AIM: To write a C program for accessing variable using pointer.

ALGORITHM: Step1: Start the program Step2: Initialize the values for x=33,*a,y=2.25 and *b Step3: Assume that a=&x and b=&y Step4: Print value of a and b Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi pointer2.c #include<stdio.h> main() { int x=33,*a; float y=2.25,*b; a=&x; b=&y; printf("\n value of a=%d",*a); printf("\n value of b=%f",*b); }

81

OUTPUT: [student@localhost ~]$ cc pointer2.c [student@localhost ~]$ ./a.out value of a=33 value of b=2.250000

RESULT: 82

Thus the C program has been written and the output is verified successfully.

ILLUSTRATION OF POINTER TO POINTER

AIM: To write a C program to illustrate the pointer to pointer concept.

ALGORITHM: Step1: Start the program Step2: Initialize a=22, *b, **c Step3: Assume b=&a and c=&b Step4: Print the values of a, b, c and address of a, b, c Step5: Stop the program.

PROGRAM: [aarthi@localhost ~]$ vi pointer3.c #include<stdio.h> main() { int a=22; int *b; int **c; b=&a; c=&b; printf("\n value of a is %d",a); printf("\n value of a is %d",*(&a)); printf("\n value of a is %d",*b); printf("\n value of a is %d",**c); printf("\n value of b and address of a is %u",b); printf("\n value of c and address of b is %u",c); printf("\n address of a is %u",&a); printf("\n address of b is %u",&b); printf("\n address of a is %u",*c); printf("\n address of b is %u",&b); printf("\n address of b is %u",c); printf("\n address of c is %u",&c); }

83

OUTPUT: [student@localhost ~]$ cc pointer3.c [student@localhost ~]$ ./a.out value of a is 22 value of a is 22 value of a is 22 value of a is 22 value of b and address of a is 3215705968 value of c and address of b is 3215705964 address of a is 3215705968 address of b is 3215705964 address of a is 3215705968 address of b is 3215705964 address of b is 3215705964 address of c is 3215705960

RESLUT: 84

Thus the C program has been written and the output is verified successfully.

ARITHMETIC CALCULATIONS

AIM: To write a C program to print addition, subtraction and multiplication.

PROGRAM: [student@localhost ~]$ vi func1.c #include<stdio.h> main() { void add(),sub(),mul(); add(); sub(); mul(); } void add() { int a=10,b=5; printf("The addition value is:%d\n",a+b); } void sub() { int a=10,b=5; printf("The subtracted value is:%d\n",a-b); } void mul() { int a=10,b=5; printf("The multiplication value is:%d\n",a*b); }

85

OUTPUT: [student@localhost ~]$ cc func1.c [student@localhost ~]$ ./a.out The addition value is: 15 The subtracted value is: 5 The multiplication value is: 50

86

RESULT: Thus the C program has been written and the output is verified successfully.

CUBE OF A GIVEN VALUE

AIM: To write a C program to find the cube of a given value.

ALGORITHM: Step1: Start the program Step2: Declare the function cube Step3: Print enter the value of n Step4: Read the value of n Step5: Calculate x=x*x*x Step6: Display cube value Step7: Stop the program

PROGRAM: [student@localhost ~]$ vi func2.c #include<stdio.h> int cube(int x); main() { int n; printf("enter the value of n="); scanf("%d",&n); printf("cube of %d is..%d\n",n,cube(n)); } int cube(int x) { x=x*x*x; return (x); }

87

OUTPUT: [student@localhost ~]$ cc func2.c [student@localhost ~]$ ./a.out enter the value of n=6 cube of 6 is..216

RESULT: 88

Thus the C program has been written and the output is verified successfully.

INTERCHANGING TWO VALUES

AIM: To write a C program to interchanging two values.

ALGORITHM: Step1: Start the program Step2: Declare the fun interchange Step3: Print I and j values before interchanging Step4: Print i and j values after interchange Step5: Stop the program

PROGRAM: [student@localhost ~]$ vi func3.c #include<stdio.h> void interchange(int *a,int *b); main() { int i=5,j=10; printf("i and j values before interchanging: %d\t%d \n",i,j); interchange(&i,&j); printf("i and j values after interchange :%d\t%d \n",i,j); printf("i and j values after interchange in the main(): %d\t%d\n",i,j); } void interchange(int *a,int *b) { int t; t=*a; *a=*b; *b=t; }

89

OUTPUT: [student@localhost ~]$ cc func3.c [student@localhost ~]$ ./a.out i and j values before interchanging: 5 10 i and j values after interchange :10 5 i and j values after interchange in the main(): 10

RESLUT: Thus the C program has been written and the output is verified successfully. 90

READ CHARACTERS AND PRINT REVERSELY

AIM: To write a C program to read characters and print reversely.

ALGORITHM: Step1: Start the program Step2: Declare fun reverse Step3: Print enter line of text Step4: The character is reversed using if((c=getchar))!=\n) Step5: Print the reversed character Step6: Stop the program

PROGRAM: [student@localhost ~]$ vi func4.c #include<stdio.h> main() { void reverse(); printf("enter line of text... ln\t"); reverse(); } void reverse() { char c; if((c=getchar())!='\n') reverse(); putchar(c); }

91

OUTPUT: [student@localhost ~]$ cc func4.c [student@localhost ~]$ ./a.out enter line of text... ln iah olleh hello hai

RESULT: 92

Thus the C program has been written and the output is verified successfully.

93

S-ar putea să vă placă și