CP II lab manual for engineers

download CP II lab manual for engineers

of 93

Transcript of CP II lab manual for engineers

  • 7/30/2019 CP II lab manual for engineers

    1/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.

    1

  • 7/30/2019 CP II lab manual for engineers

    2/93

    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.

    2

  • 7/30/2019 CP II lab manual for engineers

    3/93

    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 computersystems. 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

    3

  • 7/30/2019 CP II lab manual for engineers

    4/93

    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 X-

    windows, 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.

    4

  • 7/30/2019 CP II lab manual for engineers

    5/93

    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".

    5

  • 7/30/2019 CP II lab manual for engineers

    6/93

    Ex No: 2 BASIC COMMANDS IN UNIX

    AIM: To study the basic commands in Linux.

    COMMANDS:

    1. TASK : To display the system date and time.

    COMMAND : date.SYNTAX : date.

    EXPLANATION : displays the current system date and time on the screen.

    OUTPUT : Tue Jun 19 11:37:17 GMT 2007.

    2. TASK : To display the current month.

    COMMAND : date.

    SYNTAX : date +%m.

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

    OUTPUT : 06.

    3. TASK : To display the name of the current month.

    COMMAND : date.

    SYNTAX : date +%h.

    EXPLANATION : This command displays the name of the current month on the

    screen.

    OUTPUT : Jun.

    4. TASK : To display the current system date.

    COMMAND : date.

    SYNTAX : date +%d.

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

    OUTPUT : 19.

    6

  • 7/30/2019 CP II lab manual for engineers

    7/93

    5. TASK : To display the current system date (year).

    COMMAND : date.

    SYNTAX : date +%y.

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

    OUTPUT : 07.

    6. TASK : To display the current system time.

    COMMAND : date.

    SYNTAX : date +%H.

    EXPLANATION: This command displays the current system time (in hours) on thescreen.

    OUTPUT : 11.

    7. TASK : To display the current system time.

    COMMAND : date.

    SYNTAX : date +%M.

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

    screen.

    OUTPUT : 43.

    8. TASK : To display the current system time.

    COMMAND : date.

    SYNTAX : date +%S.

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

    screen.

    OUTPUT : 15.

    9. TASK : To display the calendar of the current month.

    COMMAND : calendar.

    SYNTAX : cal.

    7

  • 7/30/2019 CP II lab manual for engineers

    8/93

    EXPLANATION: This command displays the calendar of the current month on the

    screen.

    OUTPUT : Jun 07

    S M T W T F S

    1 2

    3 4 5 6 7 8 9

    10 11 12 13 14 15 16

    17 18 19 20 21 22 23

    24 25 26 27 28 29 30

    10. TASK : To display user-defined message.

    COMMAND : echo.

    SYNTAX : echo message.

    EXPLANATION: This command displays on the screen the argument of the echo

    command.

    OUTPUT : echo OS.

    OS

    11. TASK : To display the details of all users.

    COMMAND : who.

    SYNTAX : who.

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

    logged on to that system.

    OUTPUT : root :0 2009-02-18 11:26

    root pts/0 2009-02-18 11:56 (:0.0)

    12. TASK : To display the user detail.

    COMMAND : who.

    SYNTAX : whoami.

    EXPLANATION: This command displays information about the current user of the

    system on the screen.

    OUTPUT : root.

    8

  • 7/30/2019 CP II lab manual for engineers

    9/93

    13. TASK : To create a directory.

    COMMAND : make directory.

    SYNTAX : mkdir.

    EXPLANATION : This command is used to create a new directory with the specified

    name.

    EXAMPLE : mkdir student.

    OUTPUT : The directory student is created.

    14. TASK : To change directory.COMMAND : change directory.

    SYNTAX :cd directory name.

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

    EXAMPLE : cd staff.

    OUTPUT : The directory staff is switched onto.

    15. TASK : To delete a directory.

    COMMAND : remove directory.

    SYNTAX :rmdir directory name

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

    EXAMPLE : rmdir student.

    OUTPUT : The student directory is deleted.

    16. TASK : To come out of a sub-directory.

    COMMAND : change directory.

    SYNTAX : cd ..

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

    OUTPUT : [root@localhost ~]$ cd ..

    [root@localhost home]$ cd ~

    [root@localhost ~]$

    9

  • 7/30/2019 CP II lab manual for engineers

    10/93

    17. TASK : To list all the files and directories.

    COMMAND : list.

    SYNTAX :ls.

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

    OUTPUT :[root@localhost ~]$ ls

    add.c case.sh ex3.c func4.c reverse.c Templates

    ADD.C concatefile.sh fact.sh leap.sh storage1.c

    18. TASK : To create a file.

    COMMAND : cat.SYNTAX :cat> file name.

    EXPLANATION: This command leads to the creation of a new file with the specified

    file name and contents.

    EXAMPLE : cat> wind.

    OUTPUT : A null file called windis created.

    19. TASK : To view a file.

    COMMAND : cat.

    SYNTAX :cat file name.

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

    EXAMPLE : cat wind.

    OUTPUT : Contents of the file called wind will be displayed on the screen.

    20. TASK : To copy a file.

    COMMAND : copy.

    SYNTAX :cp sourcefile destinationfile.

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

    the specified destination file by overwriting its previous

    contents.

    EXAMPLE : cp sun moon.

    OUTPUT : The contents of sun file will be copied to the moon file.

    10

  • 7/30/2019 CP II lab manual for engineers

    11/93

    21. TASK : To move a file.

    COMMAND : move.

    SYNTAX :mv sourcefile destinationfile.

    EXPLANATION : After moving the contents of the source file into destination file,

    the source file is deleted.

    EXAMPLE : mv sun moon.

    OUTPUT : After copying contents from the sun file to moon file, the

    sun file is deleted.

    22. TASK : To display / cut a column from a file.COMMAND : cut.

    SYNTAX :cut c no. file name.

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

    specified file.

    EXAMPLE :cut c3 moon.

    OUTPUT : Those characters occurring in the 3rd column of the file called

    moon are displayed.

    23. TASK : To delete a file.

    COMMAND : remove.

    SYNTAX :rm file name.

    EXPLANATION : This command deletes the specified file from the directory.

    EXAMPLE : rm sun.

    OUTPUT : The file called sun will be deleted.

    24. TASK : To retrieve a part of a file.

    COMMAND : head.

    SYNTAX :head -no. of rows file name.EXPLANATION: This command displays the specified no. of rows form the top

    of the specified file.

    11

  • 7/30/2019 CP II lab manual for engineers

    12/93

    EXAMPLE : head -1 sun.

    OUTPU : The first row of the file called sun is displayed.

    25. TASK : To retrieve a file.

    COMMAND : tail.

    SYNTAX : tail -no. of rows file name.EXPLANATION : This command displays the specified no. of rows form the bottom

    of the specified file.

    EXAMPLE : tail -1 moon.

    OUTPUT : The last row of the file called moon is displayed.

    26. TASK : To sort the contents of a file.

    COMMAND : sort.

    SYNTAX : sort file name.

    EXPLANATION : This command helps in sorting the contents of a file in ascending

    order.

    EXAMPLE : sort win.

    OUTPUT : The contents of the file win are displayed on the screen in a

    sorted order.

    27. TASK : To display the no. of characters in a file.

    COMMAND : word count.

    SYNTAX :wc file name.

    EXPLANATION : This command displays on the screen the no. of rows, words, and

    the sum of no. of characters and words.

    EXAMPLE : wc ball.

    OUTPUT : The no. of rows, words, and no. of characters present in the file

    ball are displayed.

    28. TASK : To display the calendar of a year.

    COMMAND : cal.

    12

  • 7/30/2019 CP II lab manual for engineers

    13/93

    SYNTAX :cal year.

    EXPLANATION : This command displays on the screen the calendar of the specified

    year.

    EXAMPLE : cal 2007.

    OUTPUT : The calendar of the year2007 will be displayed.

    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.

    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 istty 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

  • 7/30/2019 CP II lab manual for engineers

    14/93

    Ex No: 3 UNIX: VI EDITOR

    General Introduction

    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 tothe 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 youwish 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

  • 7/30/2019 CP II lab manual for engineers

    15/93

    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 letterI. When you start typing, anything you type will be enteredinto 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, youmay 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 left one space l right one space

    j down one space k 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

    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 moves the cursor forward one word

    b moves the cursor backward one word (if in the middle of a

    word, b will move you to the beginning of the current word).

    15

  • 7/30/2019 CP II lab manual for engineers

    16/93

    e 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 moves the cursor to the top line of the screen.

    M moves the cursor to the middle line of the screen.

    L moves the cursor to the last line of the screen.

    To scroll through the file and see other screens use:

    Ctrl-f scrolls down one screen

    Ctrl-b scrolls up one screen

    Ctrl-u scrolls up a half a screen

    Ctrl-d 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

  • 7/30/2019 CP II lab manual for engineers

    17/93

    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 thefollowing commands:

    x deletes the character under the cursor.

    X deletes the character to the left of your cursor.

    dw deletes from the character selected to the end of the word.

    dd deletes all the current line.

    D 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

  • 7/30/2019 CP II lab manual for engineers

    18/93

    yw copies a word into a buffer (7yw copies 7 words)

    yy 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 orP 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 temporarilyinto insert mode so that you can change a character, word, line, or paragraph of text.

    r replaces the current character with the next character you enter/type.

    Once you enter the character you are returned to command mode.

    R puts you in overtype mode until you hit ESC which will then return

    you to command mode.

    cw 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

  • 7/30/2019 CP II lab manual for engineers

    19/93

    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 NOTmove the cursor from the line where you made the change. Then try using one of the following two

    commands:

    u undoes the last change you made anywhere in the file. Using u again

    will "undo the undo".

    U 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 to save your file but not quit vi (this is good to do periodically in

    case of machine crash!).

    :q to quit if you haven't made any edits.

    :wq 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

  • 7/30/2019 CP II lab manual for engineers

    20/93

    from the following two commands:

    :e! Reads the original file back in so that you can start over.

    :q! 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 todelete 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 ord2w. 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 Text Object

    d (delete) w (word to the left)

    y (yank/copy) b (word to the right or backward)

    c (change) 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

  • 7/30/2019 CP II lab manual for engineers

    21/93

    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 delete one character (destructive backspace)

    dw delete the current word (Note: ndw deletes n numbered words)

    dd delete the current line (Note: ndd deletes n numbered lines)

    D delete all content to the right of the cursor d$ same as above

    :u undo last command

    p,P paste line starting one line below/above current cursor location

    J combine the contents of two lines

    "[a-z]nyy yank next n lines into named buffer [a-z]

    "[a-z]p/P place the contents of selected buffer below/above the current line

    Extensions to the Above Commands:

    :3,18d delete lines 3 through 18

    16,25m30 move lines 16 through 25 to after line 30

    23,29co62 copy specified lines and place after line 62

    Cursor Relocation commands:

    :[n] goto line [n]

    shift g place cursor on last line of text

    h/l/j/k move cursor left, right, down and up

    ^f/^b move forward, backward in text, one page

    ^u/^d move up, down one half page

    $ move to end of line

    0 move to beginning of line

    Extensions to the Above:

    b move backwards one word (Note: nb moves back n number of words)

    21

  • 7/30/2019 CP II lab manual for engineers

    22/93

    e 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 repeat last searchN repeat search in opposite direction

    cw change the contents of the current word, (use ESC to stop

    replacement mode)

    c$ Replace all content to the right of cursor (exit replacement

    mode with ESC)

    c0 Replace all content to the left of cursor (exit with ESC)

    :1,$s/s1/s2/g (Yow!) global replacement of string1 with string2

    r replace current character with next character typed

    Entering the Insert Mode:

    i Begin inserting text at current cursor location

    I Begin inserting text at the beginning of the current line

    a Begin appending text, one character to the right of current

    cursor location

    A Begin appending text at the end of the current line

    o/O Begin entering text one line below\above current line

    ESC Exit insertion mode and return to command mode

    Exiting and Entering VI

    ZZ save file and exit VI

    :wq same as above

    22

  • 7/30/2019 CP II lab manual for engineers

    23/93

    :e! return to last saved version of current file

    :q quit without save, (Note :q! is required if changes have been made)

    :w write without exit (:w! to force write)

    Fancy Stuff:

    :1,10w file write lines 1 through 10 to file newfile

    :340,$w >> file write lines 340 through the end of the file and append

    to file newfile

    :sh escape temporarily to a shell^d return from shell to VI

    :![command] execute UNIX command without leaving VI

    :r![command] read output of command into VI

    :r[filename] read filename into VI

    :$r newfile read in newfile and attach at the end of current document

    :r !sort file read in contents of file after it has been passed through

    the UNIX sort

    :n open next file (works with wildcard filenames,

    ex: vi file*)

    :^g list current line number

    :set number show line numbers

    :set showinsert show flag ("I") at bottom of screen when in insert mode

    :set all display current values of VI variables

    :set ai 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 set the autoindent tab one tab stop to the right

    ^D set the autoindent tab one stop to the left

    :set tabstop=n sets default tab space to number n

    >> shift contents of line one tab stop to the right

  • 7/30/2019 CP II lab manual for engineers

    24/93

    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

  • 7/30/2019 CP II lab manual for engineers

    25/93

    Sh command is used to run the shell program

    - 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

    do

    Done

    25

  • 7/30/2019 CP II lab manual for engineers

    26/93

    CASE

    Case $ in

    4) ;;

    5) ;;

    6) ..7)

    .

    .

    .

    *) ;;

    esac

    For loop

    For(( intitialization;condition;incremetation/decrementation))

    26

  • 7/30/2019 CP II lab manual for engineers

    27/93

    AREA OF RECTANGLE

    AIM:

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

    ALGORITHM:

    Step1: Start the programStep2: Read l and bStep3: Calculate AREA = l x bStep4: Print the AreaStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi area.sh

    echo Enter the length and breadthread l blet area=$l*$becho The area is "$area"

    27

  • 7/30/2019 CP II lab manual for engineers

    28/93

    OUTPUT:

    [student@localhost ~]$ sh area.shEnter the length and breadth4 6The area is 24

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

    28

  • 7/30/2019 CP II lab manual for engineers

    29/93

    GREATEST AMONG THREE NUMBERS.

    AIM:

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

    ALGORITHM:

    Step1: Start the programStep2: Read a,b,cStep3: Check wheather a (or) b (or) c is greaterStep4: Print a (or) b (or) cStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi big.sh

    echo enter three numbersread a b cif [ $a -gt $b -a $a -gt $c ]thenecho "a is big"elif [ $b -gt $c ]

    thenecho " b is big"elseecho " c is big"fi

    29

  • 7/30/2019 CP II lab manual for engineers

    30/93

    OUTPUT:

    [student@localhost ~]$ sh big.sh

    enter three numbers11 2 3a is big

    [student@localhost ~]$ sh big.sh

    enter three numbers12 33 22

    b is big

    [student@localhost ~]$ sh big.sh

    enter three numbers11 22 33c is big

    RESULT:

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

    30

  • 7/30/2019 CP II lab manual for engineers

    31/93

    PRINT NUMBERS USING WHILE LOOP

    AIM:

    To print natural numbers up to n using while loop.

    ALGORITHM:

    Step1: Start the programStep2: Read the value for nStep3: Enter the upper limitStep4: Consider i = i and calculate [$i-lt$n]Step5: i =i+1Step6: Print iStep7: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi while1.sh

    echo enter upper limitread nlet i=1while [ $i -lt $n ]

    doecho "$i"let i=i+1done

    31

  • 7/30/2019 CP II lab manual for engineers

    32/93

    OUTPUT:

    [student@localhost ~]$ sh while1.shenter upper limit5123

    4

    RESULT:

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

    32

  • 7/30/2019 CP II lab manual for engineers

    33/93

    MULTIPLICATION TABLE

    AIM:

    To write a shell script to display the multiplication table.

    ALGORITHM:

    Step1: Start the programStep2: Read a =1; b =1Step3: Calculate while [$a!=5]

    for b in 1 2 3 4 5 6 7 8 9 10u =$a*$b, b =$b+1, a =$b+1, a =$a+1

    Step4: Display the Multiplication tableStep5: 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 10dolet u=$a*$becho $b X $a = $ulet b=$b+1donelet a=$a+1echo " "done

    33

  • 7/30/2019 CP II lab manual for engineers

    34/93

    OUTPUT:

    [student@localhost ~]$ sh table.sh

    1 X 1 = 12 X 1 = 23 X 1 = 34 X 1 = 4

    5 X 1 = 56 X 1 = 67 X 1 = 78 X 1 = 89 X 1 = 910 X 1 = 10

    1 X 2 = 22 X 2 = 43 X 2 = 64 X 2 = 85 X 2 = 106 X 2 = 127 X 2 = 148 X 2 = 169 X 2 = 1810 X 2 = 20

    1 X 3 = 32 X 3 = 63 X 3 = 9

    4 X 3 = 125 X 3 = 156 X 3 = 187 X 3 = 218 X 3 = 249 X 3 = 2710 X 3 = 30

    RESULT:

    34

  • 7/30/2019 CP II lab manual for engineers

    35/93

    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: Start the programStep2: Read i as 1, 2, 3, 4, 5Step3: Calculate i as 1, 2, 3, 4, 5Step4: Print 1, 2, 3, 4, 5Step5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi for.sh

    for i in 1 2 3 4 5doecho $idone

    35

  • 7/30/2019 CP II lab manual for engineers

    36/93

    OUTPUT:

    [student@localhost ~]$ sh for.sh

    123

    45

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

    36

  • 7/30/2019 CP II lab manual for engineers

    37/93

    FINDING ODD POSITION

    AIM:

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

    ALGORITHM:

    Step1: Start the programStep2: Read aStep3: Calculate b =$a%10

    a =$i%2Step4: If [$c! =0]Step5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi find.sh

    echo enter the numberread afor i in 1 2 3 4 5{let b=$a%10

    let c=$i%2if [ $c != 0 ]thenecho $bfilet a=$a/10}

    37

  • 7/30/2019 CP II lab manual for engineers

    38/93

    OUTPUT:

    [student@localhost ~]$ sh find.sh

    enter the number12345531

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

    38

  • 7/30/2019 CP II lab manual for engineers

    39/93

    ARITHMETIC CALCULATOR

    AIM:

    To write a shell script to design an arithmetic calculator.

    ALGORITHM:

    Step1: Strat the programStep2: Read a and bStep3: Select 1.Add, 2.Sub, 3.Mul, 4.DivStep4: 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 opcase $op in1) let x=$a+$becho $x;;

    2) let x=$a-$becho $x;;3) let x=$a*$becho $x

    ;;4) let x=$a/$becho $x

    39

  • 7/30/2019 CP II lab manual for engineers

    40/93

    ;;5) exitesac

    OUTPUT:

    [student@localhost ~]$ sh case.sh

    enter two numbers11 111.add 2.sub 3.mul 4.div1

    22

    [student@localhost ~]$ sh case.sh

    enter two numbers34 231.add 2.sub 3.mul 4.div211

    [student@localhost ~]$ sh case.sh

    enter two numbers23 41.add 2.sub 3.mul 4.div392

    [student@localhost ~]$ sh case.sh

    enter two numbers

    24 121.add 2.sub 3.mul 4.div4

    [student@localhost ~]$ sh case.sh

    enter two numbers36 121.add 2.sub 3.mul 4.div43

    [student@localhost ~]$ exitRESULT:

    40

  • 7/30/2019 CP II lab manual for engineers

    41/93

    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: Start the programStep2: Read aStep3: Calculate i as 1, 2, 3, 4, 5Step4: Calculate

    b =a%10sum = sum+ba =a/10

    Step5: Print the sumStep6: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi sumofdigits.sh

    echo Enter a five digit numberread a

    for i in 1 2 3 4 5dolet b=$a%10let sum=$sum+$ba=$a/10if [ $i == 5 ]thenecho The sum is "$sum"fidone

    41

  • 7/30/2019 CP II lab manual for engineers

    42/93

    OUTPUT:

    [student@localhost ~]$ sh sumofdigits.sh

    Enter a five digit number2 3 4 5 6The sum is 20

    RESULT:

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

    42

  • 7/30/2019 CP II lab manual for engineers

    43/93

    FACTORIAL OF A GIVEN NUMBER

    AIM:

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

    ALGORITHM:

    Step1: Start the programStep2: Read aStep3: Calculate a =a * i

    i =i-1Step4: Print the factorial of the numberStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi fact.sh

    echo Enter the numberread alet b=$alet i=$b-1while [ $i -gt 0 ]

    dolet a=$a*$ilet i=$i-1doneecho The factorial of the number is $a

    43

  • 7/30/2019 CP II lab manual for engineers

    44/93

    OUTPUT:

    [student@localhost ~]$ sh fact.sh

    Enter the number5The factorial of the number is 120

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

    44

  • 7/30/2019 CP II lab manual for engineers

    45/93

    LEAP YEAR OR NOT

    AIM:

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

    ALGORITHM:

    Step1: Start the programStep2: Read the yearStep3: Print whether the year is leap or notStep4: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi leap.sh

    echo enter yearread yearlet x=$year%100let y=$year%400let z=$year%4if [ $x -eq 0 ]then

    if [ $y -eq 0 ]thenecho $year is a leap yearelseecho $year is not leap yearfielseif [ $z -eq 0 ]thenecho $year is a leap yearelse

    echo $year is not a leap yearfifi

    45

  • 7/30/2019 CP II lab manual for engineers

    46/93

    OUTPUT:

    [student@localhost ~]$ sh leap.sh

    enter year20082008 is a leap year

    [student@localhost ~]$ sh leap.sh

    enter year20032003 is not a leap year

    RESULT:

    46

  • 7/30/2019 CP II lab manual for engineers

    47/93

    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: Start the programStep2: Read str1, str2Step3: Calculate len =a1+a2Step4: Display the length of the concatenated string and concatenated string.Step5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi concatstr.sh

    echo enter the stringread str1let a1=${#str1}echo enter the stringread str2let a2=${#str2}

    let len=$a1+$a2echo the length of the concatenated string is $lenecho the concatenated string is $str1$str2

    47

  • 7/30/2019 CP II lab manual for engineers

    48/93

    OUTPUT:

    [student@localhost ~]$ sh concatstr.sh

    enter the stringwelenter the stringcomethe 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

  • 7/30/2019 CP II lab manual for engineers

    49/93

    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: Start the programStep2: Read str1, str2Step3: Calculate len1 =${#str1}-1, b =0, c =0Step4: while [$c1 =$len1]Step5: If [$str2 =${str1:$c:2}Step6: Display the position matched at $d and not matched with stringStep7: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi substr.sh

    echo enter the stringread str1echo enter the substringread str2let len1=${#str1}-1let b=0

    let c=0while [ $c != $len1 ]doif [ $str2 == ${str1:$c:2} ]thenlet d=$clet d=$d+1echo position matched at $d

    breakelselet b=$b+1

    filet c=$c+1done

    49

  • 7/30/2019 CP II lab manual for engineers

    50/93

    let d=$d+1if [ $b == $len1 ]thenecho not match with stringfi

    OUTPUT:

    [student@localhost ~]$ sh substr.shenter the stringwelcomeenter the substringme

    position matched at 6

    [student@localhost ~]$ sh substr.shenter the stringwelcomeenter the substringwlnot match with string

    RESULT:

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

    50

  • 7/30/2019 CP II lab manual for engineers

    51/93

    CONCATENATION OF TWO FILES

    AIM:

    To write a shell script to concatenate two files.

    ALGORITHM:

    Step1: Start the programStep2: Read str1, str2Step3: Cat $str1 >> $str2Step4: Display str1, str2Step5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi concatefile.sh

    echo enter a fileread str1echo enter second fileread str2echo $str1cat $str1>>$str2

    51

  • 7/30/2019 CP II lab manual for engineers

    52/93

    OUTPUT:

    [student@localhost ~]$ cat >> xxhellowelcome

    [student@localhost ~]$ cat >> yyhai

    [student@localhost ~]$ sh concatefile.sh

    enter a filexxenter second fileyyxx

    [student@localhost ~]$ cat yyhaihellowelcome

    RESULT:

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

    52

  • 7/30/2019 CP II lab manual for engineers

    53/93

    STRING EQUALITY

    AIM:

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

    ALGORITHM:

    Step1: Start the programStep2: Read s1, s2Step3: Calculate if [$s1 =$s2]Step4: Display the given strings are equal or notStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi string.sh

    echo enter string 1read s1echo enter string 2read s2if [ $s1 == $s2 ]thenecho The given string are equal

    elseecho The given strings are not equalfi

    53

  • 7/30/2019 CP II lab manual for engineers

    54/93

    OUTPUT:

    [student@localhost ~]$ sh string.shenter string 1helloenter string2haiThe given strings are not equal

    [student@localhost ~]$ sh string.shenter string 1welcomeenter string2welcomeThe given string are equal

    RESULT:

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

    54

  • 7/30/2019 CP II lab manual for engineers

    55/93

    SWAPPING OF TWO VARIABLES

    AIM:

    To write a shell script to swap two variable.

    ALGORITHM:

    Step1: Start the programStep2: Read a, bStep3: Calculate c =$a; a =$b; b =$cStep4: Display the swapped numbersStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi swap.sh

    echo Enter any two numbers:read aread becho The numbers are $a and $blet c=$alet a=$blet b=$c

    echo The swapped numbers are $a and $b

    55

  • 7/30/2019 CP II lab manual for engineers

    56/93

    OUTPUT:

    [student@localhost ~]$ sh swap.sh

    Enter any two numbers:12The numbers are 1 and 2

    The swapped numbers are 2 and 1

    RESULT:

    56

  • 7/30/2019 CP II lab manual for engineers

    57/93

    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 programStep2: Read the values of a,m,nStep3: Calculate if(m>n)

    a=mm=nn=a

    Step4: Print the interchanged values of n,mStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi ex1.c

    #include 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

  • 7/30/2019 CP II lab manual for engineers

    58/93

    OUTPUT:

    [student@localhost ~]$ cc ex1.c[student@localhost ~]$ ./a.out

    enter two numbers56 34the interchanged value is:3456

    RESULT:

    58

  • 7/30/2019 CP II lab manual for engineers

    59/93

    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 programStep2: Read the values i,j,bigStep3: Calculate if (big>j);if(i>j)Step4: Print the biggest of two numbersStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi big2.c

    #includemain(){int i,j,big;

    printf("enter two values");scanf("%d%d",&i,&j);

    big=i;if(big

  • 7/30/2019 CP II lab manual for engineers

    60/93

    OUTPUT:

    [student@localhost ~]$ cc big2.c[student@localhost ~]$ ./a.out

    enter two values 45 34biggest of two numbers is45biggest of two numbers is45

    [student@localhost ~]$ ./a.outenter two values34 12

    biggest of two numbers is34biggest of two numbers is34

    RESULT:

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

    60

  • 7/30/2019 CP II lab manual for engineers

    61/93

    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 programStep2: Read the value of nStep3: Calaulate if(n=1)

    else if (n=2)Step4: Print the gamesStep5: Stop the program

    PROGRAM:

    [sudent@localhost ~]$ vi ex3.c

    #includemain(){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

  • 7/30/2019 CP II lab manual for engineers

    62/93

    OUTPUT:

    [student@localhost ~]$ cc ex3.c[student@localhost ~]$ ./a.out

    enter a number1.foot ball2.cricket

    1

    play football

    [student@localhost ~]$ ./a.out

    enter a number1.foot ball2.cricket2

    play cricket

    [student@localhost ~]$ ./a.out

    enter a number1.foot ball2.cricket3dont play

    62

  • 7/30/2019 CP II lab manual for engineers

    63/93

    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 programStep2: Read numbers,digit,rev=0Step3: Calculate while (number!=0),digit =number%10;rev=rev*10+digit;number=number/10Step4: Display the revStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi reverse.c

    #includemain(){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

  • 7/30/2019 CP II lab manual for engineers

    64/93

    OUTPUT:

    [student@localhost ~]$ cc reverse.c[student@localhost ~]$ ./a.out

    enter the number12345

    54321

    RESULT:

    64

  • 7/30/2019 CP II lab manual for engineers

    65/93

    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 programStep2: Initialize i=1, sum=0Step3: Calculate sum=sum+i

    Increment i.Step4: Print the sum of numbers upto 10Step5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi add.c

    #includemain(){int i=1,sum=0;

    do{sum=sum+i;i++;}while(i

  • 7/30/2019 CP II lab manual for engineers

    66/93

    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

  • 7/30/2019 CP II lab manual for engineers

    67/93

    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 programStep2: Initialize n,x,yStep3: Assume x=y=nStep4: Calculate for(;;(x++,y--))Step5: Print y and xStep6: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi for.c

    #includemain(){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

  • 7/30/2019 CP II lab manual for engineers

    68/93

    OUTPUT:

    [student@localhost ~]$ cc for.c[student@localhost ~]$ ./a.out

    enter a number10-------------

    (--) (++)-------------10 109 118 127 136 145 154 163 172 181 190 20

    RESULT:

    68

  • 7/30/2019 CP II lab manual for engineers

    69/93

    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 programStep2: Read the values of a,b,c,d,e,total =0,i,m,avgStep3: Calculate total=a+b+c+d+e

    Avg=total/5Step4: Print the total and averageStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi student.c

    #includemain(){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

  • 7/30/2019 CP II lab manual for engineers

    70/93

    else{

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

    OUTPUT:

    [student@localhost ~]$ cc student.c[student@localhost ~]$ ./a.out

    enter number of student2enter the marks of five subjects.

    [1]student: 8978809089total marks of the student: 426average marks of the student: 85.000000[2]student: 5676874565total marks of the student: 329average marks of the student: 65.000000

    RESULT:

    70

  • 7/30/2019 CP II lab manual for engineers

    71/93

    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 programStep2: Read the values of i,nStep3: Calculate for (i=1;i

  • 7/30/2019 CP II lab manual for engineers

    72/93

    OUTPUT:

    [student@localhost ~]$ cc switch.c[student@localhost ~]$ ./a.out

    enter a number5the number 1 is oddthe number 2 is even

    the number 3 is oddthe number 4 is eventhe number 5 is odd

    RESULT:

    72

  • 7/30/2019 CP II lab manual for engineers

    73/93

    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 programStep2: Read the values of a, b, c=0, opStep3: Calculate: addition, subtraction, multiplication and division of cStep4: Print the value of cStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi calci.c

    #includemain(){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

  • 7/30/2019 CP II lab manual for engineers

    74/93

    case '/':c=a/b;

    break;}

    printf("\n result is... %d",c);}

    OUTPUT:

    [student@localhost ~]$ cc calci.c[student@localhost ~]$ ./a.outCALCULATION CODE+ ADD- SUB* MUL/ DIV

    Enter code...+enter values....12 12

    result is... 24[student@localhost ~]$ ./a.outCALCULATION CODE+ ADD- SUB* MUL/ DIV

    Enter code...-enter values....45 56

    result is... -11[student@localhost ~]$ ./a.outCALCULATION CODE+ ADD- SUB* MUL/ DIV

    Enter code...*

    enter values....12 5

    result is... 60[student@localhost ~]$ ./a.outCALCULATION CODE+ ADD- SUB* MUL/ DIV

    Enter code.../enter values....24 12

    result is... 2

    74

  • 7/30/2019 CP II lab manual for engineers

    75/93

    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 programStep2: Read the values of *a,*n,sizeStep3: Calculate n=(int*),malloc(size*size of int)

    for(a=n;a=n;a--)

    Step4: Print the values and the address where values are storedStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi storage1.c

    #include#includemain(){

    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;a--)

    printf("%d is stored in address %u\n",*a,a);

    }

    75

  • 7/30/2019 CP II lab manual for engineers

    76/93

    OUTPUT:

    [student@localhost ~]$ cc storage1.c[student@localhost ~]$ ./a.outenter the size5address of the first byte is.... 164458504enter the values...1 2 3 4 5

    printing the values...5 is stored in address 164458520

    4 is stored in address 1644585163 is stored in address 1644585122 is stored in address 1644585081 is stored in address 164458504

    RESULT:

    76

  • 7/30/2019 CP II lab manual for engineers

    77/93

    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 programStep2: Initialize p=(char*)malloc(6)Step3: Calculate strcpy(p.madras)

    Strcpy(p.chennai)Step4: Display pStep5: Stop the program

    PROGRAM:

    [aarthi@localhost ~]$ vi storage2.c

    #include#include#includemain(){

    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

  • 7/30/2019 CP II lab manual for engineers

    78/93

    OUTPUT:

    [student@localhost ~]$ cc storage2.c[student@localhost ~]$ ./a.outMemory contains:MADRASMemory now contains:CHENNAI

    RESULT:

    78

  • 7/30/2019 CP II lab manual for engineers

    79/93

    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 programStep2: Initialize the values x=22,*aStep3: Assume that the a=&xStep4: Print values of x,address of x and value at addressStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi pointer1.c

    #include#includemain(){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

  • 7/30/2019 CP II lab manual for engineers

    80/93

    OUTPUT:

    [student@localhost ~]$ cc pointer1.c[student@localhost ~]$ ./a.out

    value of x=22address of x=3218743884value at address 3218743884 = 22

    RESULT:

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

    80

  • 7/30/2019 CP II lab manual for engineers

    81/93

    ACCESSING VARIABLE USING POINTERS

    AIM:

    To write a C program for accessing variable using pointer.

    ALGORITHM:

    Step1: Start the programStep2: Initialize the values for x=33,*a,y=2.25 and *bStep3: Assume that a=&x and b=&yStep4: Print value of a and bStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi pointer2.c

    #includemain(){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

  • 7/30/2019 CP II lab manual for engineers

    82/93

    OUTPUT:

    [student@localhost ~]$ cc pointer2.c[student@localhost ~]$ ./a.out

    value of a=33value of b=2.250000

    RESULT:

    82

  • 7/30/2019 CP II lab manual for engineers

    83/93

    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 programStep2: Initialize a=22, *b, **cStep3: Assume b=&a and c=&bStep4: Print the values of a, b, c and address of a, b, cStep5: Stop the program.

    PROGRAM:

    [aarthi@localhost ~]$ vi pointer3.c

    #includemain(){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

  • 7/30/2019 CP II lab manual for engineers

    84/93

    OUTPUT:

    [student@localhost ~]$ cc pointer3.c[student@localhost ~]$ ./a.out

    value of a is 22value of a is 22value of a is 22value of a is 22

    value of b and address of a is 3215705968value of c and address of b is 3215705964address of a is 3215705968address of b is 3215705964address of a is 3215705968address of b is 3215705964address of b is 3215705964address of c is 3215705960

    RESLUT:

    84

  • 7/30/2019 CP II lab manual for engineers

    85/93

    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

    #includemain(){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

  • 7/30/2019 CP II lab manual for engineers

    86/93

    OUTPUT:

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

    86

  • 7/30/2019 CP II lab manual for engineers

    87/93

    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 programStep2: Declare the function cubeStep3: Print enter the value of nStep4: Read the value of nStep5: Calculate x=x*x*xStep6: Display cube valueStep7: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi func2.c

    #includeint 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

  • 7/30/2019 CP II lab manual for engineers

    88/93

    OUTPUT:

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

    RESULT:

    88

  • 7/30/2019 CP II lab manual for engineers

    89/93

    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 programStep2: Declare the fun interchangeStep3: Print I and j values before interchangingStep4: Print i and j values after interchangeStep5: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi func3.c

    #includevoid 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

  • 7/30/2019 CP II lab manual for engineers

    90/93

    OUTPUT:

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

    RESLUT:

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

    90

  • 7/30/2019 CP II lab manual for engineers

    91/93

    READ CHARACTERS AND PRINT REVERSELY

    AIM:

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

    ALGORITHM:

    Step1: Start the programStep2: Declare fun reverseStep3: Print enter line of textStep4: The character is reversed using if((c=getchar))!=\n)Step5: Print the reversed characterStep6: Stop the program

    PROGRAM:

    [student@localhost ~]$ vi func4.c

    #includemain(){void reverse();

    printf("enter line of text... ln\t");

    reverse();}void reverse(){char c;if((c=getchar())!='\n')reverse();

    putchar(c);}

    91

  • 7/30/2019 CP II lab manual for engineers

    92/93

    OUTPUT:

    [student@localhost ~]$ cc func4.c[student@localhost ~]$ ./a.out

    enter line of text... ln iah olleh

    hello hai

    RESULT:

    92

  • 7/30/2019 CP II lab manual for engineers

    93/93

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