54
Anna University of Technology,Madurai B.E./B.Tech. Degree Programme Regulations 2010 Raja College of Engineering & Technology, Madurai 625 020 Department of Science & Humanities Syllabus Year & Semester : I/II 10ACPL02 COMPUTER PRACTICE LABORATORY II L T P C 0 1 2 2 Basic Commands in UNIX Working with files - Files and File types - Sorting the contents of a file - Counting the number of words in a file Working with Directories UNIX Editor Pipes Simple Filters Command line parameters with simple UNIX commands Shell Programming Fundamentals - Shell Variables - Conditional Statements - Testing and Loops - Simple shell Programs - Grep and Sedcommands - Awk filter - Security commands UNIX C - Simple C programs to simulatethe basic UNIX commands (Fork, Signal) - File handling HARDWARE / SOFTWARE REQUIREMENTS FOR A BATCH OF 30 STUDENTS Hardware Page 1 of 54

Lab Manual(CP Lab-II).doc

Embed Size (px)

Citation preview

Page 1: Lab Manual(CP Lab-II).doc

Anna University of Technology,Madurai

B.E./B.Tech. Degree Programme Regulations 2010

Raja College of Engineering & Technology, Madurai 625 020

Department of Science & Humanities

Syllabus Year & Semester : I/II

10ACPL02 COMPUTER PRACTICE LABORATORY IIL T P C0 1 2 2

Basic Commands in UNIX Working with files

- Files and File types- Sorting the contents of a file- Counting the number of words in a file

Working with Directories UNIX Editor Pipes Simple Filters Command line parameters with simple UNIX commands Shell Programming Fundamentals

- Shell Variables- Conditional Statements- Testing and Loops- Simple shell Programs- Grep and Sedcommands- Awk filter- Security commands

UNIX C- Simple C programs to simulatethe basic UNIX commands (Fork, Signal)- File handling

HARDWARE / SOFTWARE REQUIREMENTS FOR A BATCH OF 30 STUDENTS

Hardware

1 UNIX Clone Server33 Nodes (thin client or PCs)Printer – 3 Nos

Software

OS-UNIX clone (33 user license or License free Linux)Compiler- C

Page 1 of 41

Page 2: Lab Manual(CP Lab-II).doc

Raja College of Engineering and Technology

Department of Science & Humanities

Laboratory Manual – 2010-2011(Even)

Computer Practice Laboratory II

Class: 02nd Sem. B.E./B.Tech.

Branch:

List of ExperimentsI. UNIX COMMANDS 15

1. Basic Shell Commands (6 Hrs)

2. Unix Editor (3 Hrs)

II. SHELL PROGRAMMING 15

3. (a) Shell Script to swap values in two variables x and y

(b) Shell script to concatenate to two Strings and display the resultant string along with its string

length.

4. Shell Script to Simulate a Simple Calculator

5. Shell script to read 3 numbers and find the greatest of the three

6. Shell script to find whether an input number is palindrome or not

7. Shell script to find whether an input number is Armstrong or not

8. Shell script to print Fibonacci series

III. C PROGRAMMING ON UNIX 15

9. Write a C Program to find Prime No.

10. Write a C Program to Sort n Numbers

11. Write a C Program to Swap two Numbers using Pointer

12. Write a C Program to demonstrate Dynamic Memory Allocation

13. Write a C Program to demonstrate File Handling using getc and putc Functions.

Page 2 of 41

Page 3: Lab Manual(CP Lab-II).doc

Ex.No.1 Study of Basic Unix Commands

1) Command : cat

a) To Create a New File:Synatax : cat > filename

[it@rcet ~]$ cat > one.txt

Hi

Welcome to IT Lab

Raja College of Engineering & Technology

Madurai

Pressing Ctrl+z to save the file

[2]+ Stopped cat >one.txt

[it@rcet ~]$

b) To Display the Contents of the File :Syntax : cat filename

[it@rcet ~]$ cat one.txt

Hi

Welcome to IT Lab

Raja College of Engineering & Technology

Madurai

[it@rcet ~]$

2) Command : mkdir

Syntax : mkdir filename

[it@rcet ~]$ mkdir programs

[it@rcet ~]$ ls

a.out college.txt fir.sh new.txt second.sh

col1.txt coll.txt firs.sh one pgms

college2.txt file.txt one.txt programs`

[it@rcet ~]$

Page 3 of 41

Page 4: Lab Manual(CP Lab-II).doc

3) Command : cd (change directory)

Syntax : cd directory name

[it@rcet ~]$ cd programs

[it@rcet programs]$ cd ..

[it@rcet ~]$ cd programs

[it@rcet programs]$ mkdir shellprogram

[it@rcet programs]$ cd shellprogram

[it@rcet shellprogram]$ cd

[it@rcet ~]$

4) Command : pwd (Print Working Directory)

[it@rcet shellprogram]$ pwd

/home/it/programs/shellprogram

[it@rcet shellprogram]$ cd

[it@rcet ~]$ pwd

/home/it

[it@rcet ~]$

5) Command : ls (List Files and Directories)

a) ls

[it@rcet ~]$ ls

a.out college2.txt coll.txt fir.sh new.txt one.txt programs

col1.txt college.txt file.txt firs.sh one pgms second.shPage 4 of 41

Page 5: Lab Manual(CP Lab-II).doc

[it@rcet ~]$

b) ls –l : Lists Files and Directories in Long Listing Mode

[it@rcet ~]$ ls -l

total 112

-rwxrwxr-x 1 it it 5890 Jan 29 15:16 a.out

-rw-rw-r-- 1 it it 300 Feb 23 09:55 col1.txt

-rw-rw-r-- 1 it it 603 Feb 23 10:10 college2.txt

-rw-rw-r-- 1 it it 300 Feb 23 09:55 college.txt

-rw-rw-r-- 1 it it 0 Feb 27 12:43 coll.txt

-rw------- 1 it it 129 Feb 19 10:18 file.txt

-rw-rw-r-- 1 it it 132 Mar 6 09:50 fir.sh

-rw-rw-r-- 1 it it 222 Mar 6 10:16 firs.sh

-rw-rw-r-- 1 it it 59 Feb 23 09:47 new.txt

-rw-rw-r-- 1 it it 95 Feb 14 09:46 one

-rw-rw-r-- 1 it it 81 Apr 15 11:44 one.txt

drwxrwxr-x 4 it it 4096 Jan 29 15:45 pgms

drwxrwxr-x 3 it it 4096 Apr 15 11:59 programs

-rw-rw-r-- 1 it it 236 Mar 6 10:05 second.sh

[it@rcet ~]$

c) [it@rcet ~]$ ls -a

. .bashrc .emacs.d new.txt .swn .xemacs

.. col1.txt file.txt one .swo .zshrc

a.out college2.txt fir.sh one.txt .swp

.bash_history college.txt firs.sh pgms .viminfo

.bash_logout coll.txt .five.sh.swp programs .viminfo.tmp

.bash_profile .emacs .gtkrc second.sh .viminfz.tmp

[it@rcet ~]$

d) [it@rcet ~]$ ls –xa.out col1.txt college2.txt college.txt coll.txt file.txt fir.sh

firs.sh new.txt one one.txt pgms programs second.shPage 5 of 41

Page 6: Lab Manual(CP Lab-II).doc

[it@rcet ~]$

6) Command : mv (Move)

a) mv (Move a File to Directory)

Syntax : mv SourceFile DestinationDirectory

[it@rcet ~]$ mv coll.txt programs

[it@rcet ~]$ cd programs

[it@rcet programs]$ ls

coll.txt shellprogram

[it@rcet programs]$

b) mv (Move Contents of one File to Another File)

Syntax : mv SourceFile DestinationFile

[it@rcet ~]$ cat one.txt

Hi, Welcome to IT Lab

Raja College of Engineering & Technology

[it@rcet ~]$ mv one.txt new.txt

[it@rcet ~]$ cat new.txt

Hi, Welcome to CSE Lab

Raja College of Engineering & Technology

[it@rcet ~]$

7) Command : rm (Remove a File)

Syntax : rm filename

[it@rcet ~]$ ls

a.out college2.txt file.txt firs.sh one programs

col1.txt college.txt fir.sh new.txt pgms second.sh

[it@rcet ~]$ rm new.txt

[it@rcet ~]$ ls

a.out college2.txt file.txt firs.sh pgms second.sh

Page 6 of 41

Page 7: Lab Manual(CP Lab-II).doc

col1.txt college.txt fir.sh one programs

[it@rcet ~]$

8) Command : rmdir (Remove a Diretory)

Syntax : rmdir Directoryname

[it@rcet programs]$ ls

coll.txt shellprogram

[it@rcet programs]$ rmdir shellprogram

[it@rcet programs]$ ls

coll.txt

[it@rcet programs]$

9) Command : rm -rf (Remove a Diretory which is not Empty)

Syntax : rm –rf Directoryname

[it@rcet programs]$ ls

coll.txt

[it@rcet ~]$ rm -rf programs

[it@rcet ~]$ ls

a.out college2.txt file.txt firs.sh pgms

col1.txt college.txt fir.sh one second.sh

[it@rcet ~]$

10) Command : echo (Prints the Given String)

a) Syntax : echo “String”

[it@rcet ~]$ echo "Raja College of Engineering & Technology"

Raja College of Engineering & Technology

[it@rcet ~]$

b) Syntax : echo –n “String” (Don’t Print a New Line)

[it@rcet ~]$ echo -n "Raja College of Engineering &Technology"

Raja College of Engineering & Technology [it@rcet ~]$

Page 7 of 41

Page 8: Lab Manual(CP Lab-II).doc

11) Command : head (Prints required no. of lines in the File Counting from

the Beginning of the File)

Syntax : head –n filename

n : Number of Lines to be displayed

[it@rcet ~]$ cat one.txt

Welcome to Raja College of Engineering

Madurai

IT Dept

Computer Practices Laboratory

[it@rcet ~]$ head -2 one.txt

Welcome to Raja College of Engineering

Madurai

[it@rcet ~]$

12) Command : tail (Prints required no. of lines in the File Counting from

the End of the File)

Syntax : tail –n filename

n : Number of Lines to be displayed

[it@rcet ~]$ cat one.txt

Welcome to Raja College of Engineering

Madurai

IT Dept

Computer Practices Laboratory

[it@rcet ~]$ tail -2 one.txt

IT Dept

Computer Practices Laboratory

[it@rcet ~]$

Page 8 of 41

Page 9: Lab Manual(CP Lab-II).doc

13) Command : who (Displays the Users Who Logged into the System)

[it@rcet ~]$ who

cse pts/2 Apr 15 13:34 (192.168.1.21)

it pts/1 Apr 15 15:10 (192.168.1.69)

[it@rcet ~]$

Command : who am i (Displays the Name of the Current User of this

System)

[it@rcet ~]$ who am i

it pts/1 Apr 15 15:10 (192.168.1.69)

[it@rcet ~]$

14) Command : date (Displays the Current Date and Time)

[it@rcet ~]$ date

Wed Apr 15 15:25:49 IST 2009

[it@rcet ~]$

15)Command : cal (Displays the Calendar)

[it@rcet ~]$ cal

April 2009

Su Mo Tu We Th Fr Sa

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

16) Command : wc (Counts the No. of Chars, Bytes, lines, Chars in the

Longest Line)

[it@rcet ~]$ wc -m college.txt

Page 9 of 41

Page 10: Lab Manual(CP Lab-II).doc

300 college.txt

[it@rcet ~]$ wc -c college.txt

300 college.txt

[it@rcet ~]$ wc -l college.txt

11 college.txt

[it@rcet ~]$ wc -L college.txt

44 college.txt

[it@rcet ~]$

17) Command : grep (Displays a Line from the file Containing the Given

String)

Syntax : grep “String” filename

Syntax : grep –i “String” filename

i – Ignore Case of the Given String

[it@rcet ~]$ cat one.txt

Welcome to Rcet College of Engineering

Madurai

IT Dept

Computer Practices Laboratory

[it@rcet ~]$ grep "Rcet" one.txt

Welcome to Rcet College of Engineering

[it@rcet ~]$

18) Command : Sort (Sorting the Contents of the File)

The sort command is used to order the lines of a file. Various options can be used to choose the order as well as the field on which a file is sorted. Without any options, the sort compares entire lines in the file and outputs them in ASCII order (numbers first, upper case letters, then lower case letters).

Syntaxsort filename

Page 10 of 41

Page 11: Lab Manual(CP Lab-II).doc

sort –r filename (sort in the reverse order)Exampleusers.txt

jdoe John Doe 4/15/96lsmith Laura Smith 3/12/96pchen Paul Chen 1/5/96jhsu Jake Hsu 4/17/96sphilip Sue Phillip 4/2/96

[it@rcet ~]$ sort users.txtjdoe John Doe 4/15/96jhsu Jake Hsu 4/17/96lsmith Laura Smith 3/12/96pchen Paul Chen 1/5/96sphilip Sue Phillip 4/2/96

19) Command : uniq (Simple Filter to remove duplicates)

uniq filters duplicate adjacent lines from a file.

Syntaxuniq file [file.new]

ExampleConsider the following file and example, in which uniq removes the 4th line from file and places the

[it@rcet ~]$ cat > fi1 2 3 64 5 3 67 8 9 07 8 9 0

[it@rcet ~]$ uniq file file.new[it@rcet ~]$cat file.new

1 2 3 64 5 3 67 8 9 0

20) Command: pipes ( | - redirect the output to one command to Another

Command)

The Unix system allows you to effectively connect two commands

together. This connection is known as a pipe, and it enables you to take the output

Page 11 of 41

Page 12: Lab Manual(CP Lab-II).doc

from one command and feed it directly into the input of another command. A pipe

is effected by the character |, which is placed between the two commands.

Example

To make a pipe between the who and wc -l commands,

[it@rcet ~]$ who | wc –l

5 (number of users logged in the system)

The standard output from the first command is connected directly to the standard

input of the second command.

Ex.No.2 UNIX Editor

General Information:

About vi:

vi (pronounced vee-EYE, short for “visual”) provides basic text editing capabilities. Three

aspects of vi make it appealing.

1. vi is supplied with all UNIX systems.

2. vi uses a small amount of memory, which allows efficient operation when the

network is busy.

3. vi uses standard alphanumeric keys for commands.

You can use it on virtually any terminal or workstation in existence without having to worry

about unusual keyboard mappings. As a point of interest, vi is actually a special mode of another

UNIX text editor called ex. Normally you do not need to use ex except in vi mode.

vi commands are case-sensitive, which means that upper-case and lower-case commands are

not the same command. For example, j moves the cursor down, but J combines two lines into one

line.

The word RETURN represents the action of pressing RETURN key. ESC indicates pressing

the ESCAPE key. Also, sometimes you will see a keystroke like CTRL-F. CTRL-F means you hold

down the key marked CONTROL or CTRL, and press F. The CTRL key acts in a manner similar to

the SHIFT key.

A Brief vi Session:

Starting vi:

Page 12 of 41

Page 13: Lab Manual(CP Lab-II).doc

To start vi, enter:

vi filename RETURN

Where filename is the name of the file you want to edit. If the file does not exist, vi will create it for

you. You can also start vi without giving any filename. In this case, vi will ask for one when you quit

or save your work.

Example:

Start vi in preparation for some tutorial exercises; throughout this document, the exercises

will use the file, sample. In an xterm, type:

vi sample RETURN

The window clears and displays the contents of the file, sample. Since it is a new file, it does not

contain any text. vi uses the tilde (~) character to indicate lines on the screen beyond the end of the

file.

Command Mode and Input Mode:

vi has two modes,

1. command mode

2. input mode

In command mode, characters you type perform actions like moving the cursor, cutting or

copying text, or searching for some particular text. In input mode, you type to insert or overwrite

text. When you start vi, it is in command mode.

To switch from command to input mode, press the “i” key (you do not need to press

RETURN) Vi lets you insert text beginning at the current cursor location. To switch back to

command mode, press ESC. You can also use ESC to cancel an unfinished command in command

mode. Unfortunately, vi does not normally indicate which mode you are in. The next exercise turns

on a mode indicator. If you are uncertain about the current mode, you can press ESC a few times.

When vi beeps, you have returned to command mode.

To Know the Current Mode:

Before you start typing text, the command below activates the modeline indicator. You are

not required to use it, but it tells you whether you are in command or input mode.

Type:

:set showmode RETURN

Nothing appears to change. When you are in command mode, there is no indicator, but if you

enter input mode, one will appear in the bottom right-hand corner of the window.

Line Numbers:

Page 13 of 41

Page 14: Lab Manual(CP Lab-II).doc

Many vi commands use line numbers, which simply count the number of RETURN

characters in a file. You can cut and copy text by line number or jump to a certain line. Line numbers

can be useful when you ritive error messages during program compilation. Frequently compilers will

print the line number, so you can use vi to jump to the appropriate line and look for the error.

Exercise to display the line numbers, enter the following command:

:set number RETURN

This command will immediately display the line numbers in the left margin of your vi window. It

may cause long lines to wrap around the right edge of the window, but they will not be damaged.

The G movement command lets you jump to any line within a file. First type the line number,

followed by G. If you do not type any line number, vi jumps to the end of the file. Thus, 1G takes

you to the beginning, and G takes you to the end.

Vi Commands – A Quick View:

Command Meaning

vi File Name Open or Create File

vi Open New File To Be Named

vi -r File Name Recover Crashed File

view File Name Open File Read-Only

vipw Edit the /etc/passwd file, setting locks and doing appropriate processing.

There are three modes of operation:

Command ModeInsert ModeLast Line Mode

Vi Commands – A Quick Review

Vi Commands Used To Edit Files Positioning The Cursor:

Command Meaning

h Move left one character

j Move down one line

k Move up one line

l Move right one character

w Move right one word

W Move right one word (Past Punctuation)

b Move left one word

Page 14 of 41

Page 15: Lab Manual(CP Lab-II).doc

B Move left one word (Past Punctuation)

e Move to end of current word

Return Move down one line

Backspace Move left one character

H Move to top of screen

M Move to middle of screen

L Move to bottom on screen

Control-f Scroll forward one screen

Control-d Scroll forward one-half screen

Control-b Scroll backward one-half screen

G Go to last line of file

1G Go to first line of file

21G Go to 21st line of file

Table Vi Commands to Edit Files

Appending Commands:

Command Meaning

A Append text after cursor

A Append text at line end

I Insert text before cursor

I Insert text at beginning of line

O Insert line below cursor

O Insert line above cursor

Table: Appending Commands

Example 1:

To enter input mode, press: i Note that in the bottom right-hand corner, vi indicates that you are in input mode. Then

enter the following text, and remember to press RETURN at the end of each line.

You can use the special keystrokes if you make a mistake. We scrambled to strike camp.

Water crashed down upon us, far too slow in foot and hands to do it. “Oh, no,” I said. Our heavens

darkened grimly. Thunder echoed overhead and shook the clouds, even the ground rumbled as each

clap loudly exploded.

Glancing back, I saw an ocean rising behind us. It just wouldn’t stop raining. Our weathered tent

Page 15 of 41

Page 16: Lab Manual(CP Lab-II).doc

was a poor shelter tonight. As a lightning bolt flashes over the hills, we made out a small cave on

the mountainside. A safe haven, thought I.Our heavens fell down, but just up ahead lay safety.

After entering this text, press ESC to return to command mode. Notice that the

mode line clears, too

Example 2:

Move to the line “Our heavens fell...” and press A to append text at the end of the line. Then

type (the symbol -- means a space character):

--We crawled in, and wept. ESC

Next go to the line “in foot and hand...” and open a new line below it. Press: o to start open mode,

and observe that vi creates a new line for text. Type: Take a step and fall. ESC

Deleting Text:

Command Meaning

x Delete Character at the cursor

X Delete character to the left of the cursor

dw Delete word (or part of word to right of cursor)

dd Delete line containing the cursor

D Delete part of line to right of cursor

dG Delete to end of file

d1G Delete from beginning of file to cursor

:5,10d Delete lines 5 through 10

Commands to Delete Text

Examples:

Try using the cursor movement keys to place the cursor on the word “hands.” Move the cursor onto

the “s.” Press x to delete it. Now let’s delete the word “loudly.” Move to the beginning of the word.

Although you could press x seven times to delete the word and its trailing space, it is quicker to

delete it by typing dw. Finally, remove the line “It just wouldn’t stop raining.” Move the cursor

anywhere on that line, and type dd. The line vanishes.

Changing Text:

Command Meaning

CW Change word (or part of word) to right of cursor

cc Change line

c Change from cursor to end of line

Page 16 of 41

Page 17: Lab Manual(CP Lab-II).doc

s Substitute string for characters from cursor forward

r Replace character at cursor with one other character

r Return Break line

Examples:

Let’s correct some words. To maintain proper verb tense, “flashes” should be

“flashed.” Move the cursor to the last “s” in “flashes.” To enter replace mode, type: r and notice

that the mode line says, “REPLACE 1 CHAR.” Next type the letter: d to make the change. Notice

that you do not need to press ESC or RETURN when replacing just one character. Next change

“safety” to “sanctuary.” Move to the beginning of the word “safety,” then type: CW vi shows a

dollar sign ($) indicating the end of the text being corrected. Type: sanctuary ESC

To finish the exercise, move the cursor to “do.” We’ll change all the text from “do” to

the end of the line. Start the correction by pressing: C Again vi shows a dollar sign (this time at

the end of the line). Make the change by typing: reach that island. ESC

Insert Mode Commands:

Command Meaning

J Join current line and line below

xp Transpose character at cursor and character to the right

~ Change case of letter (upper or lower )

u or :u Undo previous command

Commands in Insert Mode

Example 1:

Move to the line “flashed over the hills...” and delete it by typing:

dd

Bring back the line by pressing:

u

which undoes the last text change. Press u a few more times, and watch what happens. When you

undo something, you change the text, so your undo becomes the last text change! That explains

why undoing appears to flip between two displays. Leave the line “flashed over...” on the display.

Example 2:

Move to the blank line just after “in foot and hand.” Press:

i

and insert the following text: I saw everything spinning wildly. RETURN

Page 17 of 41

Page 18: Lab Manual(CP Lab-II).doc

Press ESC to return to command mode. Now move to the line “in foot and hand” and press:

J

to join it with the line you just typed.

Copying and Pasting:

Command Meaning

y Yank or copy line

Y Yank or copy line

p Put yanked or deleted line below current

P Same as above

Commands to Copy Text and Paste Text

General:

vi has its own terminology for “cut” and “copy”: “delete” and “yank,” respectively.

Note that the delete command is the same one you have already used; every time you delete text,

vi changes the automatic buffer and pushes the previous delete into the next numbered buffer.

When you delete or yank, the desired text enters a buffer. If you do not specify a named buffer, vi

uses the automatic buffer (buffer 1).

The delete and yank commands take the following form:

1. Move the cursor to one end of the desired text.

2. If desired, specify a named buffer by typing “letter where letter is a letter from a

through z. If you do not give a named buffer, vi uses the automatic buffers 1-9.

3. Type a repetition number, if needed. (To copy 5 words or 8 lines, for example.)

4. Type d to delete text, or type y to yank text.

5. Type a cursor movement key to determine the text unit; if you type d or y instead, vi

uses the “line” unit. The cursor key completes the delete or yanks and stores the text in the

desired buffer.

Using Markers:

Markers also let you specify a range of text for cutting or copying without having to

count words or lines. The next procedure shows you how to delete or yank text by using markers.

1. Move the cursor to one end of the selection.

2. Type mletter to set a marker.

3. Move the cursor to the other end.

Page 18 of 41

Page 19: Lab Manual(CP Lab-II).doc

4. If desired, specify a named buffer by typing “letter If you do not give a named buffer, vi

uses the automatic buffers.

5. Type d or y to delete or yank text, respectively.

6. Using letter from the marker, type ‘letter to delete or yank the text between the marker

and the cursor. You may instead type ’letter to delete or yank the text by line.

Example:

This exercise performs a standard copy-and-paste. It uses the automatic buffer and does not use

any markers. Move to the first line of text, then yank three lines of text by typing:

3yy

Nothing appears to happen, but vi has put the first three lines into its automatic buffer. The

message “3 lines yanked” appears at the bottom of the screen. Now move to the line “A safe

haven and paste the lines in place. To do so, just press:

p

Saving Changes and Quitting:

Command Meaning

:w Save changes (write buffer)

:w new file Write buffer to named file

:wq Save changes and quit Vi

:q! Quit without saving changes

Commands to Save and Quit

Displaying and Hiding Line:

Command Meaning

:set nu Show line numbers

:set nonu Hide line numbers; setting is case sensitive

:set ic Searches should ignore case

:set noic Searches should be case sensitive

:set list Display invisible characters

Commands to Hide and Display a Line

Search and Replace:

Command Meaning

/string Search for string

Page 19 of 41

Page 20: Lab Manual(CP Lab-II).doc

?string Search backward for string

N Find next occurrence of string in search direction

N Find previous occurrence of string in search direction

:%s/old/new/g Search and replace

Commands to Search and Replace

Refresh the Screen and Including Files:

Command Meaning

Control-1 Clear (refresh) scrambled screen

:r file name Insert (read) file after cursor

:34r file name Insert file after line 34

Commands for Screen Refreshing

Repeating a Command:

Often you will want to act on more than one character, word, or line. For example, suppose

you want to delete three words. Rather than type dw three times, you can type 3dw, and vi will

execute the command three times. Many vi commands can be repeated in this manner.

Just type a number (it can be more than one digit), then type the command. If you want to

abandon the number, press ESC to cancel it.

Example:

Start vi with the sample document by typing:

vi sample RETURN

Once vi starts, turn on the modeline with:

:set showmode RETURN

Move to the “e” in “echoed overhead and,” then type:

3dw

and notice that vi deletes three words at once. (Then press u to undo the deletion.)

Ex.No.3 (a) Shell Script to swap values in two variables x and y

Page 20 of 41

Page 21: Lab Manual(CP Lab-II).doc

Algorithm:

1. Start the Program

2. Read the Value of X and Y

3. Using temporary variable Z interchange the values of X and Y

4. Display the result after Swapping

5. Stop the Program

Ex.No.3 (b) Shell script to concatenate to two Strings given as input and

display the resultant string along with its string length.

Algorithm:1. Start the Program

2. Read Two Strings as Arguments

3. If Number of Arguments less than two exit the Program

4. Concatenate two strings and store the result

5. Using Length Function find the length of the result string

6. Display the Concatenated String with its length

7. Stop the Program

Ex.No.4 Shell Script to Simulate a Simple CalculatorAlgorithm:

1. Start the program

2. Read a, b, op

3. Check for no. of inputs and if it is less than three exit the program

4. Use case statement for op

a. If op is + add a, b

b. If op is – subtract a, b

c. If op is / divide a, b

d. If op is x multiply a, b

e. Else print error

5. Display the result

6. End the program

Page 21 of 41

Page 22: Lab Manual(CP Lab-II).doc

Ex.No.5 Shell script to read 3 numbers and find the greatest of the three

Algorithm:

1. Start the program

2. Read a, b, c

3. Using If Statement Check the condition to find the biggest value

a. If value of a is greater than b and c print a as biggest

b. If value of b is greater than a and c print b as biggest

c. If value of c is greater than a and c print c as biggest

d. If values of a, b and c are equal Print all the numbers are equal

e. Else Print ‘Cannot guess greatest of three numbers’

4. End the program

Ex.No.6 Shell script to find whether an input number is palindrome or not

Algorithm

1. Start the Program

2. Read the value of n

3. Initialize sd to zero, empty the string variable rev

4. Assign the value of n to variable on

5. While the value of n is greater than zero

a. Using MOD operator, separate each digits of n and store value in sd

b. Divide n by 10 to get new value of n

c. Concatenate value of sd with variable rev

6. If the value of rev is equal to the original input value n

a. Print the number is Palindrome

7. Else Print Number is not a Palindrome

8. Stop the Program

Ex.No.7 Shell script to find whether an input number is Armstrong or not

Algorithm:Page 22 of 41

Page 23: Lab Manual(CP Lab-II).doc

1. Start the Program

2. Read the Value of n

3. Initialize sd=0,sum=0

4. Assign the value of n to the variable no

5. While value of n is greater than zero

a. Using MOD operator, separate each digits of n and store value in sd

b. Calculate the Cube value of sd and store it in variable ar

c. Divide n by 10 to get new value of n

d. Add the Value of sum and ar

6. If the value of sum is equal to the value of no

a. Print the Given number as Armstrong Number

7. Else print the Given number is not Armstrong Number

8. Stop the program

Ex.No.8 Shell script to print Fibonacci series

Algorithm:

1. Start the Program

2. Initialize i=1,a=0,b=1

3. Read the value of n

4. Print the Value of a

5. While value of i is not equal to value of n

a. Add the values of a ,b and store it in variable b

b. Print the value of b

c. Using Variable c, Interchange the values of a and b

d. Increment the value of i

6. Stop the Program

Ex.No.9 C Program to find Prime No.

Aim To write a C Program to check whether the given number is Prime or Not

Page 23 of 41

Page 24: Lab Manual(CP Lab-II).doc

Algorithm:1. Start the Program

2. Declare Variables no, i as Integer Type

3. Read the value of no and Initialize i = 2

4. While i is less than or equal to no - 1

a. Using MOD Operator Check the remainder after no / i

b. If the remainder is equal to zero

i. Print the Number is not Prime

c. Exit the Program

d. Increment the value of i by 1

5. If the value of no is equal to the value of i

a. Print the Number is a Prime number

6. Stop the Program

Result Hence the Given number is verified as Prime or not Using C Program.

Ex.No.10 C Program to Sort n Numbers

AimTo write a C Program to Sort n Numbers in Ascending Order.

Algorithm:1. Start the Program2. Declare variables x, n, i, j as Integer type3. Declare variable a as Integer array of 100 elements4. Read the no. of elements to be stored in the array in variable n5. Using For Loop, till the value of i is less than n

a. Read the Elements of the array6. Using For Loop, till the value of i is less than n

a. Using For Loop, till the value of j is less than n-1i. If Value of a[j] is greater than a[j+1]

1. Interchange the values of a[j] and a[j+1]7. Using For Loop, till the value of i is less than n

a. Print the Elements of Array8. Stop the Program

ResultHence the Given n Numbers are sorted in Ascending Order using C Program.

Page 24 of 41

Page 25: Lab Manual(CP Lab-II).doc

Ex.No.11 C Program to Swap two Numbers using Pointer

Aim

To write a C Program to Swap two numbers using pointer.

Algorithm:

1. Start the Program

2. Declare two variables a, b as Integer type

3. Read the Values of a and b to be swapped

4. Call Swap Function by passing the address of Variable a and b

5. In the Swap Function, Interchange the values of a and b using temporary

variable

6. Print the swapped values

7. Stop the program

Result

Hence the Given two numbers are swapped using Pointer in C Program.

Ex.No.12 C Program to demonstrate Dynamic Memory AllocationAim

To write a C Program to demonstrate the Concept of Dynamic Memory

Allocation

Algorithm:

1. Start the Program

2. Declare two variables number, i as Integer type

3. Declare variable ptr as Integer Pointer

4. Read the Number of Integer values to be stored and Store it in Variable

number

5. Using malloc function , Allocate Memory to the Pointer Variable ptr

6. If variable ptr is Not Null

a. Using For Loop, till the value of i is less than value of number

i. Store the value of i in the pointer variable ptr

b. Using For Loop, till the value of i is greater than 0

i. Print the Stored values of Pointer Variable ptrPage 25 of 41

Page 26: Lab Manual(CP Lab-II).doc

7. Using Free Function, Clear the contents of the variable ptr

8. Stop the Program

Result

Hence the Concept of Dynamic Memory Allocation is demonstrated using C

Program

Ex.No.13 C Program to demonstrate File Handling using getc and putc Functions

Aim

To write a C Program to demonstrate the Concept of File Handling using getc

and putc functions

Algorithm:

1. Start the Program

2. Initialize the file pointer f1

3. Initialize variable c as Character type

4. Using fopen, open a text file for writing

5. Using getchar, get the characters as input till the new line

6. Using putc, Put the characters in the file through file pointer f1

7. Close the file

8. Using fopen, open the text file for reading

9. Using getc, get the characters in the file till the EOF

10.Print the Characters then Close the file .

11.Stop the Program

Result

Hence the Concept of File Handling using getc and putc is demonstrated using

C Program.

Programs

Ex.No.3(a)

Page 26 of 41

Page 27: Lab Manual(CP Lab-II).doc

Program: Shell Script to to Swap Values in two Variables x and y

echo -n "Enter Value for X:"

read x

echo -n "Enter Value for Y:"

read y

echo "Before Swap, X=$x and Y=$y"

z=$x

x=$y

y=$z

echo "After Swap, X=$x and Y=$y"

Output:

[it@raja ~]$ sh nine.sh

Enter Value for X:26

Enter Value for Y:15

Before Swap, X=26 and Y=15

After Swap, X=15 and Y=26

[it@raja ~]$

Ex.No.3(b)

Program: Shell script to concatenate two strings given as input and display

the resultant string along with its string length.

str1=$1

str2=$2

OUT="$str1$str2"

if [ $# -eq 0 ]

then

echo "$0 string1 string2"

exit 1

fi

len=$(expr length $OUT)

Page 27 of 41

Page 28: Lab Manual(CP Lab-II).doc

echo "Before Concatenation String1 is $str1 & String2 is $str2"

echo "Concatenated String is - $OUT"

echo "String Length is - $len"

Output:

[it@raja ~]$ sh six.sh Beautiful INDIA

Before Concatenation String1 is Beautiful & String2 is INDIA

Concatenated String is - BeautifulINDIA

String Length is - 14

[it@raja ~ ]$

Ex.No.4

Program: Shell script To simulate a simple calculator.

a=$1

op=$2

b=$3

if [ $# -lt 3 ]

then

echo "$0 num1 opr num2"

echo "opr can be +,-,/,x"

exit 1

fi

case "$op" in

+) echo $(( $a + $b ));;

-) echo $(( $a - $b ));;

/) echo $(( $a / $b ));;

x) echo $(( $a * $b ));;

*) echo "Error";;

Output:Page 28 of 41

Page 29: Lab Manual(CP Lab-II).doc

[it@raja ~]$ sh one.sh 10 + 5

15

[it@raja ~]$ sh one.sh 10 - 5

5

[it@raja ~]$ sh one.sh 10 x 5

50

[it@raja ~]$ sh one.sh 10 / 5

2

[it@raja ~]$ sh one.sh 10 * 5

Error

Ex.No.5

Program: Shell script To find largest among 3 integers (Numbers) given as

arguments.

a=$1

b=$2

c=$3

if [ $# -lt 3 ]

then

echo "$0 n1 n2 n3"

exit 1

fi

if [ $a -gt $b -a $a -gt $c ]

then

echo "$a is largest number"

elif [ $b -gt $a -a $b -gt $c ]

then

echo "$b is largest number"

elif [ $c -gt $a -a $c -gt $b ]

then echo "$c is largest number"else

Page 29 of 41

Page 30: Lab Manual(CP Lab-II).doc

echo "Sorry cannot guess number"fiOutput:

[it@raja ~]$ sh two.sh 10 15 20

20 is largest number

[it@raja ~]$ sh two.sh 10 10 20

sorry cannot guess number

[it@raja !~]$ sh two.sh 10 10 10

Three are equal

[it@raja ~]$

Ex.No.6

Program: Shell script To find Whetherr an input is palindrome or not.

echo -n "Enter Number:"

read n

sd=0

rev=""

on=$n

while [ $n -gt 0 ]

do

sd=$(( $n % 10 ))

n=$(( $n / 10 ))

rev=$(echo ${rev}${sd})

done

if [ $on -eq $rev ]

then

echo "Number is Palindrome"

else

echo "Number is not a Palindrome"

fi

Page 30 of 41

Page 31: Lab Manual(CP Lab-II).doc

Output:

[it@raja ~]$ sh eight.sh

Enter Number:121

Number is Palindrome

[it@raja ~]$ sh eight.sh

Enter Number:153

Number is not a Palindrome

[it@raja ~]$

Ex.No.7

Program: Shell script To verify whether the given number is Armstrong

number or not.

echo -n "Enter the number:"

read n

sd=0

sum=0

no=$n

while [ $n -gt 0 ]

do

sd=$(($n % 10))

ar=`expr $sd*$sd*$sd`

n=$(($n / 10))

sum=$(($sum + $ar))

done

if [ $sum -eq $no ]

then

echo "$no is armstrong number."

else

echo "$no is not armstrong number."Page 31 of 41

Page 32: Lab Manual(CP Lab-II).doc

Fi

Output:

[it@raja ~]$ sh arm.sh

Enter the number:153

153 is armstrong number.

[it@raja ~]$ sh arm.sh

Enter the number:121

121 is not armstrong number.

[it@raja ~]$

Ex.No.8

Program: Shell script To print fibonacci series.

i=1

a=0

b=1

echo -n "Enter the No. of Terms you want:"

read n

echo ${a}

while [ $i != $n ]

do

b=`expr $a + $b`

echo $b

c=$a

a=$b

b=$c

i=`expr $i + 1`

done

Output:

[it@raja ~]$ sh seven.sh

Page 32 of 41

Page 33: Lab Manual(CP Lab-II).doc

Enter the No. of Terms you want:5

0

1

1

2

3

[it@raja ~]$

Ex.No.9

Program: C Program to find Prime No.

#include<stdio.h>

main()

{

int no,i;

printf("Enter the number you want to check:");

scanf("%d",&no);

i=2;

while(i<=no-1)

{

if(no%i==0)

{

printf("\n%d is not a Prime No.\n",no);

break;

}

i=i+1;

}

if(no==i)

printf("\n%d is a prime no.\n",no);

getchar();

Page 33 of 41

Page 34: Lab Manual(CP Lab-II).doc

}

Output:

[it@raja ~]$ cc four.c

[it@raja ~]$ ./a.out

Enter the number you want to check:12

12 is not a Prime No.

[it@raja ~]$ ./a.out

Enter the number you want to check:13

13 is a prime no.

Ex.No.10

Program: C Program to Sort n Numbers.

#include <stdio.h>

main()

{

int a[100],x,n,i,j;

printf("Enter the Number of Elements in the Array:");

scanf("%d",&n);

printf("Enter the Elements:");

for (i=0;i<n;i++)

scanf("%d",&a[i]);

for (i=0;i<n;i++)

{

for(j=0;j<n-1;j++)

if(a[j]>a[j+1])

{

x=a[j];

a[j]=a[j+1];

a[j+1]=x;

}

Page 34 of 41

Page 35: Lab Manual(CP Lab-II).doc

}

printf("Sorted Array in ascending order\n");

for(i=0;i<n;i++)

printf("%d\n",a[i]);

}

Ex.No.10

Output: Program to Sort n Numbers.

[it@raja ~]$ cc two.c

[it@raja ~]$ ./a.out

Enter the Number of Elements in the Array:5

Enter the Elements:

8

5

9

6

11

Sorted Array in ascending order

5

6

8

9

11

[it@raja ~]$

Page 35 of 41

Page 36: Lab Manual(CP Lab-II).doc

Ex.No.11

Program: C Program to Swap two Numbers using Pointer

#include <stdio.h>

#include <stdlib.h>

void swap(int *x,int *y)

{

int temporary=*x;

*x=*y;

*y=temporary;

}

int main(void)

{

int a;

int b;

printf("Enter Two Values to be Swapped;\n");

scanf("%d %d",&a,&b);

printf("Before Swap: a=%d,b=%d\n",a,b);

swap(&a,&b);

printf("After Swap: a=%d,b=%d\n",a,b);

getchar();

return 0;

Page 36 of 41

Page 37: Lab Manual(CP Lab-II).doc

}

Output:

[it@raja ~]$ cc one.c

[it@raja ~]$ ./a.out

Enter Two Values to be Swapped:

100

50

Before Swap: a=100,b=50

After Swap: a=50,b=100

Ex.No.12

Program: C Program to demonstrate Dynamic Memory Allocation.

#include <stdio.h>

#include <stdlib.h>

main()

{

int number;

int *ptr;

int i;

printf("How many integers would you like to store:");

scanf("%d",&number);

ptr=malloc(number*sizeof(int));

if(ptr!=NULL)

{

for(i=0;i<number;i++)

{

*(ptr+i)=i;

}

for(i=number;i>0;i--)

{

printf("Number %d is stored at Location %d\n",*(ptr+(i-1)),(ptr+(i-1)));

Page 37 of 41

Page 38: Lab Manual(CP Lab-II).doc

}

free(ptr);

return 0;

}

}

Ex.No.12

Output: C Program to demonstrate Dynamic Memory Allocation.

[it@raja ~]$ cc five.c

[it@raja ~]$ ./a.out

How many integers would you like to store : 5

Number 4 is stored at Location 148471832

Number 3 is stored at Location 148471828

Number 2 is stored at Location 148471824

Number 1 is stored at Location 148471820

Number 0 is stored at Location 148471816

[it@raja ~]$

Page 38 of 41

Page 39: Lab Manual(CP Lab-II).doc

Ex.No.13

Program: C Program to demonstrate File Handling using getc and putc

Functions

#include<stdio.h>

#include <stdlib.h>

main()

{

FILE *f1;

char c;

printf("Data Input:\n");

f1=fopen("Input.txt","w");

while ((c=getchar())!='\n')

putc(c,f1);

fclose(f1);

printf("\nData Output\n");

f1=fopen("Input.txt","r");

while((c=getc(f1))!=EOF)

printf("%c",c);

printf("\n");

fclose(f1);

Page 39 of 41

Page 40: Lab Manual(CP Lab-II).doc

}

Output:

[it@raja ~]$ cc six.c

[it@raja ~]$ ./a.out

Data Input:

Raja College of Engineering & Technology, Madurai

Data Output

Raja College of Engineering & Technology, Madurai

[it@raja ~]$

Page 40 of 41

Page 41: Lab Manual(CP Lab-II).doc

Page 41 of 41