cp 2 lab manual final

59
GE2155–Computer Practice II Ex. No: 1.1 STUDY OF UNIX OPERATING SYSTEM AIM To introduce the concept of UNIX Operating System OPERATING SYSTEM An Operating System is a set of programs that Functions as an virtual machine by presenting an interface that is easier to program than the underlying hardware Acts as resource management through orderly and controlled allocation of the processors, memories, and I/O devices among the programs competing for it. OS TYPES 1. SingleUser—The system will have its own hard disk, memory, CPU and other resources all dedicated to a single user. Eg. MS-DOS 2. MultiUser—The users having access to a multi-user system will have just a terminal and a keyboard. The other resources such as hard disk, printers are centrally located. The user is expected to simply hook onto his account, perform the work, disconnect and leave quietly. Eg. UNIX UNIX HISTORY The spade work for UNIX began at AT&T Bell Laboratories in 1969 by Ken Thompson and Dennis Ritchie. The OS was initially known as UNICS (jokingly UNiplexed Information and Computing System). In 1970 UNICS finally became UNIX. In 1973, UNIX was rewritten in 1973 in C principally authored by Ritchie. UNIX FEATURES 1. Multi-user system—Multi-user capability of UNIX allows several users to use the same computer to perform their 1

Upload: villixyloo

Post on 27-Apr-2015

124 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Ex. No: 1.1 STUDY OF UNIX OPERATING SYSTEM

AIM

To introduce the concept of UNIX Operating System

OPERATING SYSTEM

An Operating System is a set of programs that

Functions as an virtual machine by presenting an interface that is easier to program than the underlying hardware

Acts as resource management through orderly and controlled allocation of the processors, memories, and I/O devices among the programs competing for it.

OS TYPES

1. SingleUser—The system will have its own hard disk, memory, CPU and other resources all dedicated to a single user. Eg. MS-DOS

2. MultiUser—The users having access to a multi-user system will have just a terminal and a keyboard. The other resources such as hard disk, printers are centrally located. The user is expected to simply hook onto his account, perform the work, disconnect and leave quietly. Eg. UNIX

UNIX HISTORY

The spade work for UNIX began at AT&T Bell Laboratories in 1969 by Ken Thompson and Dennis Ritchie. The OS was initially known as UNICS (jokingly UNiplexed Information and Computing System). In 1970 UNICS finally became UNIX. In 1973, UNIX was rewritten in 1973 in C principally authored by Ritchie.

UNIX FEATURES

1. Multi-user system—Multi-user capability of UNIX allows several users to use the same computer to perform their tasks. Several terminals [Keyboards and Monitors] are connected to a single powerful computer [UNIX server] and each user can work with their terminals.

2. Multi-tasking system—Multitasking is the capability of the operating system to perform various task simultaneously,i.e. a user can run multiple tasks concurrently.

3. Programming Facility—UNIX is highly programmable, the UNIX shell has all the necessary ingredients like conditional and control structures, etc.

4. Security—UNIX allows sharing of data; every user must have a single login name and password. So, accessing another user’s data is impossible without his permission.

5. Portability—UNIX is portable because it is written in a high level language. So, UNIX can be run on different computers.

1

Page 2: Cp 2 Lab Manual Final

GE2155–Computer Practice II

6. Communication—UNIX supports communication between different terminals of the same server as well as between terminals on different servers.

Apart from these features, UNIX has an extensive Tool kit, exhaustive system calls and Libraries and enhanced GUI (X Window).

ORGANIZATION OF UNIX

The UNIX system is functionally organized at three levelsand are:

1. The kernel, which schedules tasks and manages storage;

2. The shell, which connects and interprets users' commands, calls programs from memory, and executes them; and

3. The tools and applications that offer additional functionality to the OS

UNIX Structure

The kernel is the heart of the system, a collection of programs written in C that directly communicate with the hardware. There is only one kernel for any system. It's that part of UNIX system that is loaded into memory when the system is booted. It manages the system resources, allocates time between user and processes, decides process priorities, and performs all other tasks. The kernel, in traditional parlance, is often called the Operating system.

The shell, on the other hand, is the "sleeping beauty" of UNIX. It is actually the interface between the user and the kernel. The shell is the agency which takes care of the features of redirection and has a programming capability of its own.

The Tools and Applicationsconsist of Application Software, Compilers, Database Package, Internet tools, UNIX commands, etc.

2

Page 3: Cp 2 Lab Manual Final

GE2155–Computer Practice II

FILE SYSTEM

A file in UNIX is nothing but a storehouse of information and everything is treated as a file by UNIX. The files can be broadly classified as follows:

Ordinary files—Contains stream of data. All data, text, source programs, object and executable code, commands fall into this category.

Directory files—Contains no external data. It contains an entry, name of the file and its inode (identification number) for each file and subdirectory under that directory. Directory files are not created by the user but by the UNIX system itself.

Device files—Even physical devices are treated as files. These are special in the sense that any output directed to it will be reflected onto the respective device.

UNIX File System

All files in UNIX are related to one another. The file system of UNIX resembles a tree that grows from top to bottom as shown in the figure.The file system begins with a directory called root (at the top). The root directory is denoted by a slash (\). Branching from root there are several directories such asbin, lib, etc, tmp, dev. Each of these directories contains several sub-directories and files.

Result

Thus the study of UNIX Operating System has been completed successfully.

3

Page 4: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Ex. No: 1.2 BASIC UNIX COMMANDS

Aim

To study and execute UNIX commands.

Unix is security conscious, and can be used only by those persons who have an account. Telnet (Telephone Network) is a Terminal emulator program for TCP/IP networks that enables users to log on to remote servers.

To logon, type telnetserver_ipaddress in run window.

User has to authenticate himself by providing username and password. Once verified, a greeting and $ prompt appears. The shell is now ready to receive commands from the user. Options suffixed with a hyphen (–) and arguments are separated by space.

General commands

Command Functiondate Used to display the current system date and time. date +%D Displays date onlydate +%T Displays time onlydate +% Y Displays the year part of datedate +% H Displays the hour part of timecal Calendar of the current monthcal year Displays calendar for all months of the specified year cal month year Displays calendar for the specified month of the yearwho Login details of all users such as their IP, Terminal No, User name, who am i Used to display the login details of the usertty Used to display the terminal nameuname Displays the Operating Systemuname –r Shows version number of the OS (kernel). uname –n Displays domain name of the serverecho "txt" Displays the given text on the screenecho $HOME Displays the user's home directorybc Basic calculator. Press Ctrl+d to quitlpfile Allows the user to spool a job along with others in a print queue.man cmdname Manual for the given command. Press q to exithistory To display the commands used by the user since log on.exit Exit from a process. If shell is the only process then logs out

Directory commands

Command Functionpwd Path of the present working directorymkdirdir A directory is created in the given name under the current directorymkdirdir1 dir2 A number of sub-directories can be created under one strokecd subdir Change Directory. If the subdir starts with / then path starts from

root (absolute) otherwise from current working directory.cd To switch to the home directory. cd / To switch to the root directory.

4

Page 5: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Command Functioncd .. To move back to the parent directoryrmdirsubdir Removes an empty sub-directory.

File commands

Command Functioncat >filename To create a file with some contents. To end typing press Ctrl+d.

The > symbol means redirecting output to a file. (< for input)cat filename Displays the file contents.cat >>filename Used to append contents to a filecpsrcdes Copy files to given location. If already exists, it will be overwritten cp –isrcdes Warns the user prior to overwriting the destination filecp –r src des Copies the entire directory, all its sub-directories and files.mv oldnew To rename an existing file or directory. –i option can also be usedmv f1 f2 f3 dir To move a group of files to a directory.mv –v old new Display name of each file as it is moved. rmfile Used to delete a file or group of files. –i option can also be usedrm * To delete all the files in the directory.rm –r * Deletes all files and sub-directories rm –f * To forcibly remove even write-protected filesls Lists all files and subdirectories (blue colored) in sorted manner.lsname To check whether a file or directory exists.lsname* Short-hand notation to list out filenames of a specific pattern.ls –a Lists all files including hidden files (files beginning with .)ls –x dirname To have specific listing of a directory.ls –R Recursive listing of all files in the subdirectories ls –l Long listing showing file access rights (read/write/execute-rwxfor

user/group/others-ugo).cmpfile1 file2 Used to compare two files. Displays nothing if files are identical.wcfile It produces a statistics of lines (l), words(w), and characters(c).chmodperm file Changes permission for the specified file. (r=4, w=2, x=1)

chmod 740 file sets all rights for user, read only for groups and no rights for others

The commands can be combined using the pipeline (|) operator. For example, number of users logged in can be obtained as.

who | wc -l

Simple Filters

Filters are the central commands of the UNIX tool kit. It acts on data file where lines are records, fields delimited by a character not used by the data (mostly |, default is white space). The output is a set of records and the input file is unaltered by these commands.

5

Page 6: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Command Functionhead―used to display the first few records (10 records by default)head stud Displays first 10 records by defaulthead -5 stud Displays first 5 recordshead -1 stud | wc –c length of first recordtail―used to display the last few records (10 records by default)tail stud Displays last 10 records by defaulttail -5 stud | tee last5 Last 5 records listed & stored in file last5 using

teecut―used to extract specific fields. The d option specifies the delimiter and f for specifying the field list. The c option may be used if extraction is done character wisecut –d \| -f 1,3,4 stud Fields 1,3,4 listedcut –d \| -f 2-4 stud Fields 2,3,4 listedpaste –d \| list1 list2 merges two cut files list1 and list2sort―reorders the file as per ASCII sequence. The t option is used to specify delimitersort stud Sorted on 1st column by defaultsort –t \| +2 stud Sort as per 3rd columnsort –c stud Check if file is sorted using c optionsort –t \| +3 -4 +4 stud Sorting on secondary keys sort -t \| -nr +4 stud Sort on numeric field using n option, r for reverseuniq stud Display unique entries in a sorted filenl―display file content with lines numbered. The s option is used to specify separatornl –s "|" stud Displays entries numbered with separator | tr―translates characters. Can be used to change text case. It works with standard input <tr '[a-z]' '[A-Z]' < stud Changes text to upper case

Regular Expression

A frequent requirement is to look for a pattern or expression in a file. Unix handles this feature through grep and egrep. grep uses an regular expression to display lines that match and egrep enables searching for multiple patterns. Its usage isgrepoptionssearchtext filename

Command Functiongrep this demo Lists the lines that contains the string thisgrep 'end of' demo Quotes mandatory for text containing spacegrep this demo* Search this in multiple filesgrep –c to demo Number of occurrence of the word to in the filegrep –n sequence demo Display line numbers along with matching linesgrep –v word demo Displays lines that does not contain the text wordgrep –l vim * Displays files containing text vimgrep –i WORD demo Search for text ignoring case differencesgrep '^[0-9]' demo Lines that start with a numbergrep '[0-9]$' demo Lines that end with a numberls -l | grep "^d" Display the subdirectory namesgrep –c "^$" demo Display count of blank lines in the file.grep "2....$" stud Display lines that ends in the range 20000–29999egrep "lower|UPPER" demo Display lines that match either lower or upper

6

Page 7: Cp 2 Lab Manual Final

GE2155–Computer Practice II

egrep "(previous|current) word" demo

Display lines that match either previous word or current word

Finally to terminate the unix session execute the command exit or logout.

ResultThus the study and execution of UNIX commands has been completed

successfully.

Exercise:

1. Write the command to display only the first two characters of all the lines from a file

2. Write the command to convert the lower case to uppercase

3. Write the command to sort the two files in ascending order

4. Write the command to Count the number of lines in the files

5. Write the command to Search a specific word from any one of the file

6. Write the command to view only the directories page by page

7. Write the command to display the complete path of the working directory

8. Write the command Create a file called cs1101.txt in the CS1101 directory

9. Write the command to print the specified number of lines of a file from start to end of the file.

10. Write the command to Update the file content with I/O redirection

7

Page 8: Cp 2 Lab Manual Final

GE2155–Computer Practice II

UNIX Viva Questions

1. How do you change File Access Permissions?

2. What is a shell?

3. What is the significance of the “tee” command?

4. What does the command “ $who | sort –logfile>newfile” do?

5. What does the command “$ls | wc –l > file1” do?

6. Which of the following commands is not a filter man , (b) cat , (c) pg , (d) head

7. How is the command “$cat file2 “ different from “$cat >file2 and >> redirection operators ?

8. What difference between cmp and diff commands?

9. What is the difference between cat and more command?

10. What is a pipe and give an example?

8

Page 9: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Ex. No: 1.3 STUDY OF VI EDITOR

Aim

To introduce the concept of text editing vi editor and the options regarding the control of the editor.vi Editor

A text editor is one of the most common and useful tools in all Operating Systems. Unix provides a versatile editorvi, a full-screen editor and owes its origin to Bill Joy. "vi" stands for visual editor. A vi session begins by invoking vi with or without a filename

$vi$vifilename

The user is presented with a full empty screen, each line beginning with a ~. This is vi's way of indicating non-existent lines. Out of 25 lines on the terminal, 24 can be used to enter text. The last line is reserved for commands and also used by the system to display messages.vi functions in three modes namely:

1. Input mode—Where any key depressed is entered as text2. Command mode—Where keys are used as commands to act on text (initial

mode)3. ex mode—ex mode commands that can be entered in the last line to act on text

vi modes

INPUT MODE

vi starts with command mode. To insert text any of the following commands should be used.

Commands Functioni Inserts text to the left of the cursor.I Inserts text at the beginning of line.a Appends text to right of cursorA Appends text at end of lineo Opens line belowO Opens line above

9

Page 10: Cp 2 Lab Manual Final

GE2155–Computer Practice II

In Input mode the editor displays INSERT in the last line. Press Enter key to start a fresh line of text in Input mode and the ~ disappears. To quit input mode press Esc key.COMMAND MODE

EDIT COMMANDS

Command FunctionR Replaces more than a single character. The editor displays REPLACE in

the last line. The existing text is overwritten as they are typed. s Deletes a single character to the left and switches to Input mode.x Deletes the character in the current cursor position?text Locates the text in the file. If not found, the message "Pattern not found"

appears. Use n to repeat the forward search and Nforbackwardsearch. U or u Reverses the last change made to the buffer.dd Cuts the entire linedw Cuts the entire wordd$ Cuts a line from cursor position to the end of the lined0 Cuts from the cursor position to the start of the lineyy Copies (yanks) the entire lineyw Copies the entire wordp Pastes the text

NAVIGATION COMMANDS

Command Functionb Moves back to beginning of a wordw Moves forward to beginning of word| Moves to start of the line$ Moves to end of the linek Up one linej Down one lineh Left one character l Right one character Ctrl+f Scrolls a page forwardCtrl+b Scrolls a page backwardlG To move to the specific line

One of the most notable features of vi is the facility of prefixing a number to most commands. When prefixed, commands interpret the instruction to be repeated as many times. For example 3xdeletes the next three character.

THE EX MODE

The essential save and exit commands form the features of ex mode. Press :(colon)in command mode to switch to ex mode. The: is displayed in the last line. Type the command and press Enterkeyto execute the same.

Command Functionw Saves file, displays the number of lines & characters and returns to

10

Page 11: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Input mode. If it is an unnamed file then vi puts a message. w file The file is saved under the given nameL1,L2 w file Used to write specific line numbers to some file. The . (dot)

represents current line, 0 for first line and $ could be used to represent last line.

q Quits vi session and returns to $ prompt. vi has a safety mechanism that warns if changes made to file are not saved.

q! Quits vi session without saving any changes made since the last savewq Save and exitsh Escape to shell%s/Sstr/Rstr/g This is yet another powerful feature known as substitution. It is

similar to Find and Replace. % represents all lines, g makes it global. To make vi ask for confirmation before replacing use gc instead of g.

r file To insert another file into the current file.new file Splits screen into multiple windows and opens the file.

vi Editor for new file

vi editor

viEditorwith Contents

ResultThus the study of text manipulation using vieditor has been completed

successfully.

11

~~~~~~~~~“Sample.txt” [New File]

This is vi improved – vimA rudimentary text ~~~~~~~~~“Sample.txt” 2L, 30C written

Page 12: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Ex. No: 2 SHELL PROGRAMS

AimTo write simple shell scripts using shell programming fundamentals.

The activities of a shell are not restricted to command interpretation alone. The shell also has rudimentary programming features. When a group of commands has to be executed regularly, they are stored in a file (with extension .sh). All such files are called shell scripts or shell programs. Shell programs run in interpretive mode.

The original UNIX came with the Bourne shell (sh) and it is universal even today. Then came a plethora of shells offering new features. Two of them, C shell (csh) and Korn shell (ksh) has been well accepted by the UNIX fraternity. Linux offers Bash shell (bash) as a superior alternative to Bourne shell.

Preliminaries

1. Comments in shell script start with #. It can be placed anywhere in a line; the shell ignores contents to its right. Comments are recommended but not mandatory

2. Shell variables are loosely typed i.e. not declared. Their type depends on the value assigned. Variables when used in an expression or output must be prefixed by $.

3. The read statement is shell's internal tool for making scripts interactive. 4. Output is displayed using echo statement. Any text should be within quotes.

Escape sequence should be used with –e option.5. Commands are always enclosed with ` ` (back quotes).6. Expressions are computed using the expr command. Arithmetic operators are + -

* / %. Meta characters * ( ) should be escaped with a \.7. Multiple statements can be written in a single line separated by ;8. The shell scripts are executed using the sh command (shfilename).

The set of relational and logical operators used in conditional expression is given below. The numeric comparison in the shell is confined to integer values only.

Shell supports decision-makingusing if statement. The if statement like its counterpart in programming languages has the following formats. The first construct executes the statements when the condition is true. The second construct adds an optional else to the first one that has different set of statements to be executed depending on whether the condition is true or false. The last

12

Operator

Description

-eq Equal to-ne Not equal to-gt Greater than-ge Greater than or equal to-lt Less than-le Less than or equal to-a Logical AND-o Logical OR! Logical NOT

Page 13: Cp 2 Lab Manual Final

GE2155–Computer Practice II

one is an elif ladder, in which conditions are tested in sequence, but only one set of statements is executed.

Syntax 1:

if[condition]thenstatementsfi

Syntax 2:

if [ condition]thenstatementselsestatementsfi

Syntax 3:

if [condition]thenstatementselif [condition]thenstatements.. .elsestatementsfi

The case statement is used to compare a variable’s value against a set of constants (integer, character, string, range). If it matches a constant, then the set of statements followed after ) is executed till a ;; is encountered. The optional default block is indicated by *. Multiple constants can be specified in a single pattern separated by |.

casevariableinconstant1) statements ;; constant2) statements ;; . . .constantN) statements ;; *) statementsesac

Shell supports a set of loops such as for, while and until to execute a set of statements repeatedly. The body of the loop is contained between do and done statement.

The for loop doesn't test a condition, but uses a list instead.

forvariable in listdo

statementsdone

The while loop executes the statements as long as the condition remains true.

while [ condition ]do

statementsdone

The until loop complements the while construct in the sense that the statements are executed as long as the condition remains false.

13

Page 14: Cp 2 Lab Manual Final

GE2155–Computer Practice II

until [ condition ]do

statementsdone

2.1 -Write a Shell program to Swap values of two variables

Algorithm

Step 1 : StartStep 2 : Read the values of a and bStep 3 : Interchange the values of a and b using another variable t as follows:

t = aa = bb = t

Step 4 : Print a and bStep 5 : Stop

Program (swap.sh)

# Swapping valuesecho -n "Enter value for A : "read aecho -n "Enter value for B : "read bt=$aa=$bb=$techo "Values after Swapping"echo "A Value is $a"echo "B Value is $b"

Output

[vijai@localhost simple]$ sh swap.shEnter value for A : 12Enter value for B : 23Values after SwappingA Value is 23B Value is 12

Result:

2.2 -Write a Shell program to covert Fahrenheit to Centigrade

Algorithm

14

Page 15: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Step 1 : StartStep 2 : Read fahrenheit valueStep 3 : Convert fahrenheit to centigrade using the formulae: (fahrenheit – 32) × 5/9Step 4 : Print centigradeStep 5 : Stop

Program

# Degree conversionecho -n "Enter Fahrenheit : "read fc=`expr\( $f - 32 \) \* 5 / 9`echo "Centigrade is : $c"

Output

[vijai@localhost simple]$ sh degconv.shEnter Fahrenheit : 213Centigrade is : 100

Result:

2.3 -Write a Shell program to calculate the Area & Circumference of a Circle

Algorithm

15

Page 16: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Step 1 : StartStep 2 : Define constant pi = 3.14Step 3 : Read the value of radiusStep 4 : Calculate area using formulae: pi × radius2

Step 5 : Calculate circumference using formulae: 2 × pi × radiusStep 6 : Print area and circumferenceStep 7 : Stop

Program (circle.sh)

# Circle metrics using readonly variablepi=`expr "scale=2; 22 / 7" | bc`readonly pi # pi value cannot be alteredecho -n "Enter value for radius : "read radiusarea=`expr "scale=2; $pi * $radius * $radius" | bc`circum=`expr "scale=2; 2 * $pi * $radius" | bc`echo "Area : $area"echo "Circumference : $circum"

Output

[vijai@localhost simple]$ sh circle.shEnter value for radius : 12Area : 452.16Circumference : 75.36

Result:

2.4 -Write a Shell program tocalculate Simple Interest

Algorithm

16

Page 17: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Step 1 : StartStep 2 : Read the values principal, rate and yearsStep 3 : Compute simpleinterest using the formulae: (principal × rate × years) / 100Step 4 : Print simpleinterestStep 5 : Stop

Program

Program (simpint.sh)

# Interest computation using bcecho -n "Enter Principal amount : "read pecho -n "Enter number of years : "read necho -n "Enter rate of interest : "read rsi=`expr "scale=2; $p * $n *$r / 100" | bc`echo "Simple Interest : $si"

Output

[vijai@localhost simple]$ sh simpint.shEnter Principal amount : 1285Enter number of years : 3Enter rate of interest : 5Simple Interest : 192.75

Result:

17

Page 18: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.5 -Write a Shell program to check whether a given number is odd or even

Algorithm

Step 1 : StartStep 2 : Read numberStep 3 : If number divisible by 2 then

Print "Number is Even" Step 3.1 : else

Print "Number is Odd"Step 4 : Stop

Program (oddeven.sh)

# Odd or even using if-elseecho -n "Enter a non-zero number : "read numrem=`expr $num % 2`if [ $rem -eq 0 ]thenecho "$num is Even"elseecho "$num is Odd"fi

Output

[vijai@localhost decision]$sh oddeven.shEnter a non-zero number : 1212 is Even

Result:

18

Page 19: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.6 -Write a Shell program to display student grades

Algorithm

Step 1 : StartStep 2 : Read markStep 3 : If mark> 90 then

Print "S grade"Step 3.1 : else if mark> 80 then

Print "A grade"Step 3.2 : else if mark> 70 then

Print "B grade"Step 3.3 : else if mark> 60 then

Print "C grade"Step 3.4 : else if mark> 55 then

Print "D grade"Step 3.5 : else if mark 50 then

Print "E grade"Step 3.6 : else

Print "U grade"Step 4 : Stop

Program(grade.sh)

echo -n "Enter the mark : "read markif [ $mark -gt 90 ] thenecho "S Grade"elif [ $mark -gt 80 ] thenecho "A Grade"elif [ $mark -gt 70 ] thenecho "B Grade"elif [ $mark -gt 60 ] thenecho "C Grade"elif [ $mark -gt 55 ] thenecho "D Grade"elif [ $mark -ge 50 ] thenecho "E Grade"elseecho "U Grade"fi

19

Page 20: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Output

[vijai@localhost decision]$sh grade.shEnter the mark : 65C Grade

Result:

20

Page 21: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.7 -Write a Shell program to find the sum of odd and even numbers from a set of numbers.

Algorithm

Program

Output

Result:

21

Page 22: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.8 -Write a Shell program to find biggest of 3 numbers

Algorithm

Step 1 : StartStep 2 : Read values of a, b and cStep 3 : If a>b and a>c then

Print "A is the biggest" Step 3.1 : else if b>c then

Print "B is the biggest "Step 3.2 : else

Print "C is the biggest"Step 4 : Stop

Program

# Biggest using logical expressionecho -n "Give value for A B and C: "read a b cif [ $a -gt $b -a $a -gt $c ]thenecho "A is the Biggest number"elif [ $b -gt $c ]thenecho "B is the Biggest number"elseecho "C is the Biggest number"fi

Output

[vijai@localhost decision]$sh big3.shGive value for A B and C: 4 3 5C is the Biggest number

Result:

22

Page 23: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.9 - Write a Shell program to check the given integer is Armstrong number or not.

Algorithm

Program

Output

Result:

23

Page 24: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.10- Write a Shell program to generate prime numbers between 1 and 50

Algorithm

Program

Output

Result:

24

Page 25: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.11 - Write a Shell program to check whether the given year is leap or not.

Algorithm

Program

Output

Result:

25

Page 26: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.12 - Write a Shell program to find the smallest number from a set of numbers

Algorithm

Program

Output

Result:

26

Page 27: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.13 Write a Shell program to check whether a letter is vowel or not.

Algorithm

Step 1 : StartStep 2 : Read charStep 3 : If char is either 'a', 'e', 'i', 'o' or 'u' then

Print "It's a vowel"Step 3.1 : else

Print "It's a consonant"Step 4 : Stop

Program (vowel.sh)

# check for vowelecho -n "Key in a lower case character : "read choicecase $choice ina|e|i|o|u) echo "It's a Vowel";; *) echo "It's a Consonant"esac

Output

[vijai@localhostmultway]$sh vowel.shKey in a lower case character : eIt's a Vowel

Result:

27

Page 28: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.14.Write a shell program to print Multiplication Table

Algorithm

Step 1 : StartStep 2 : Read the value of nStep 3 : Initialize 1 to iStep 4 : Print n, i, n×iStep 5 : Increment i by 1Step 6 : Repeatsteps 4 and 5tilli¿ 10Step 7 : Stop

Program (multable.sh)

# Multiplication table using for loopclearecho -n "Which multiplication table? : "read nfor x in 1 2 3 4 5 6 7 8 9 10do p=`expr $x \* $n`echo -n "$n X $x = $p"sleep 1done

Output

[vijai@localhost loops]$sh multable.shWhich multiplication table? : 66 X 1 = 66 X 2 = 126 X 3 = 186 X 4 = 246 X 5 = 306 X 6 = 366 X 7 = 426 X 8 = 486 X 9 = 546 X 10= 60

Result:

28

Page 29: Cp 2 Lab Manual Final

GE2155–Computer Practice II

2.15.Write a shell program to compare two strings.

Algorithm

Step 1 : StartStep 2 : Read two strings str1 and str2.Step 3 : If str1 = str2

Print “The strings are same”Else Print “The strings are not same”

Step 4 : Stop

Program

Output

Result:

29

Page 30: Cp 2 Lab Manual Final

GE2155–Computer Practice II

C PROGRAMMING ON UNIX

3.1 - Write a C program to swap two numbers

Aim:To write a program to swap the given two values in the function, the values are

passed ascall by reference.

Algorithm:

Step 1: Input two numbersStep 2: Swap them without using a third variable by passing their reference to the function that swaps them.Step 3: Print the swapped values.Step 4: Stop.

Program:

Output:

Result:

30

Page 31: Cp 2 Lab Manual Final

GE2155–Computer Practice II

3.2 -Write a C program to allocate memory for array using Calloc

Aim:To write a program in C to allocate memory for an array using calloc.

Algorithm:1. Start the program.2. Declare a pointer variable.3. Allocate memory space using calloc.4. If pointerData = = NULL, allocation is not done. 5. Input thenumbersand store them in the allocated space.6. Print the stored numbers7. Stop the program.

Program:#include <stdio.h>#include <stdlib.h>int main 0{inti, n;int *pojnterData;printf (“Enter number of items to be stored: “);scanf (“%d”, &i);pointerData = (int*) calloc (i, sizeof(int));if (pointerData==NULL)

exit (1);for (n =0; n <i; n++){

printf (“Enter number #%d: “, n);scanf (“%d”, &pointerData[ n]);

}printf (“You have entered: “);for (n =0; n <i; n++)

printf(“%d “, pointerData[ n]);free (pointerData);

}

OutputEnter number of items to be stored: 4Enter number #0:3Enter number #1:2Enter number #2:1Enter number #3:5You have entered: 3 2 1 5

Result:Thus the program is written and executed to allocate memory for array using

Calloc.

31

Page 32: Cp 2 Lab Manual Final

GE2155–Computer Practice II

3.3 - Write a C program to allocate space for a string dynamically and print the string backwards

AimTo write a program in C to allocate space for a string dynamically and print the

stringbackwards.

Algorithm:1.Start the program.2.Declare the pointer variable s.3.Allocate the memory space using malloc.4.Ifs = = NULL, allocation is not done. 5.Input the string and store it in the allocated space.6.Print the string starting from the last character to the first character.7.Stop the program.

Program

Output:

Result

32

Page 33: Cp 2 Lab Manual Final

GE2155–Computer Practice II

3.4 -Write a C program using dynamic memory allocation to perform binary search operation

Aim:To write a C program to perform binary search using dynamic memory allocation.

Algorithm:Step 1: Input the size of the arrayStep 2: Allocate memory for the array using malloc functionStep 3: Input the elements of the arrayStep 4: Input the element to be searchedStep 5: Let low be the lower limit of the array and high be the upper limit of the array.Step 6: Find the mid using the index formula (low+high)/2Step 7: If key is equal to the mid element, return the position.Step 8: Else divide the array into 2 parts.Step 9: If the key is less than the mid element, repeat from Step 6 to Step 8, keeping high as mid-1. Step 10: If the key is greater than the mid element, repeat from Setp 6 to Step 8, keeping low as mid+1.

Program:

Output

Result:

33

Page 34: Cp 2 Lab Manual Final

GE2155–Computer Practice II

3.5 -Write a C program to copy one file to another file

AimTo write a C program to copy one file to another.

Algorithm:1. Start the program.2 Open the source file in read and write mode.3. Create the new file and open with new file name.4. Read each character from the source file and write the character into the destinationfile until end of the character.5. Stop the program.

Program:#include <stdio.h>#include <files.h>main(){

FILE *fdl, *fd2;charc;fd1 = fopen(”Bensam.txt”, “r+”);fd2 = fopen(”Jovita.txt”, “w”);while(fd1!=EOF){

c=getchar(fd1);putchar(c,fd2);

}printf(“File Copied”);fcloseall();

}

Output:

File Copied

Content of Bensam.txtThis is Bensam. Hi, How are you!

Content of Jovita.txtThis is Bensam. Hi, How are you!

Result:Thus the program is written and executed to copy the content of one file toanother

file.

34

Page 35: Cp 2 Lab Manual Final

GE2155–Computer Practice II

3.6 -Write a C program to count the number of characters and lines in a file

Aim:To write a C program that counts the number of characters and number of lines in

afile.

Algorithm:1. Start the program.2. Open a file in read mode.3. Set a counter charcnt that is incremented every time a character is read from the file.4. Set another counter linecnt for counting the number of lines.5. Whenever a newline character is encountered, increment linecnt.6. Print charcnt and linecnt.7. End the program.

Program:

Output :

Result:Thus the Program is written, executed and output is tested.

35

Page 36: Cp 2 Lab Manual Final

GE2155–Computer Practice II

C – Viva Questions

1. What does a static variable mean?

2. What are the different storage classes in C ?

3. What is hashing ?

4. Can static variables be declared in a header file ?

5. Can a variable be both constant and volatile ?

6. Can include files be nested?

7. What is a null pointer ?

8. What is the output of printf("%d") ?

9. What is the difference between calloc() and malloc() ?

10. What is the difference between printf() and sprintf() ?

11. How to reduce a final size of executable ?

12. Advantages of a macro over a function ?

36

Page 37: Cp 2 Lab Manual Final

GE2155–Computer Practice II

13. What is the difference between strings and character arrays ?

14. Write down the equivalent pointer expression for referring the same element a[i][j][k][l] ?

15. Which bit wise operator is suitable for checking whether a particular bit is on or off ?

16. Does there exist any other function which can be used to convert an integer or a float to a string ?

17. Why does malloc(0) return valid memory address ? What's the use ?

18. Difference between const char* p and char const* p

19. What is the benefit of using an enum rather than a #define constant ?

20. How can you determine the size of an allocated portion of memory ?

21. When does the compiler not implicitly generate the address of the first element of an array ?

22. What is the benefit of using #define to declare a constant ?

23. Why should we assign NULL to the elements (pointer) after freeing them ?

24. What is a null pointer assignment error ? What are bus errors, memory faults, and core dumps ?

37

Page 38: Cp 2 Lab Manual Final

GE2155–Computer Practice II

25. When should a type cast be used ?

26. Is it possible to execute code even after the program exits the main() function?

27. How do you print an address ?

28. What is Preprocessor ?

29. What is the purpose of realloc( ) ?

30. How do you use a pointer to a function ?

31. What is the purpose of main ( ) function ?

32. Why n++ executes faster than n+1?

33. What is the easiest sorting method to use?

34. Is it better to use a macro or a function ?

35. What are the standard predefined macros?

38

Page 39: Cp 2 Lab Manual Final

GE2155–Computer Practice II

SAMPLE UNIVERSITY QUESTION PAPER

1. a. Write and execute the following UNIX commands (i) Create a file.(ii) Display only the first two characters of all the lines from a file.(iii) Convert the lower case to uppercase.(iv) Combine two strings.(v) Display the file contents in descending order.b. Write a Shell program to check the given number is even or oddc. Write a C program using dynamic memory allocation to sort ‘n’ numbers in ascending order.

2. a. Write and execute the following UNIX commands(i) Create two files with the name of name.txt, which contain only names, and reg.txt with the content of register number respectively.(ii) Combine the two files in the form of register number followed by name(iii) Sort the two files in ascending order(iv) Count the number of lines in the files(v) Rename the two files.b. Write a Shell program to check and display 10 leap yearsc. Write a C program using dynamic memory allocation to sort ‘n’ numbers in descending order.

3. a. Write and execute the following UNIX commands(i) Create two files.(ii) Combine the two files.(iii) Search a specific word from any one of the file.(iv) Search a specific file from a directory.(v) Display the common and distinct line of contents from a file.b. Write a Shell program to find the area and circumference of a circle.c. Write a C program using dynamic memory allocation to sort ‘n’ names in ascending order.

4. a. Write and execute the following UNIX commands(i) Create two files.(ii) Display the contents of both the files.(iii) Count the number of characters in both the files.(iv) Rename the two files.(v) Combine the two files without duplicate.b. Write a Shell program to check the given number and its reverse are same.c. Write a C program using dynamic memory allocation to sort ‘n’ names in descending order.

5. a. Write and execute the following UNIX commands(i) To view all the files and directories page by page(ii) To view only the directories page by page.(iii) To view only the files in a directory.(iv) Display the working directory.(v) Display the complete path of the working directory.b. Write a Shell program to check the given string is palindrome or not.

39

Page 40: Cp 2 Lab Manual Final

GE2155–Computer Practice II

c. Write a C program using dynamic memory allocation to add two matrices.

6. a. Write and execute the following UNIX commands (i) Display the calendar.(ii) Execute more than one command at a time (using semi-colon ;)(iii) Display the user’s full details.(iv) Display the user-id / Group-id.(v) Execute more than one command at a time (using logical-AND &&).b. Write a Shell program to find the sum of odd and even numbers from a set of numbers.c. Write a C program using dynamic memory allocation to subtract two matrices.

7. a. Write and execute the following UNIX commands (i) Demonstrate pipe command (ii) Demonstrate tee command(iii) Use more than one command at a time (who and date)(iv) Create a file called create.txt(v) Move the file create.txt to move.txtb. Write a Shell program to find the roots of a quadratic equationc. Write a C program using dynamic memory allocation to transpose a given matrix

8. a. Write and execute the following UNIX commands(i) Create a file(ii) Print the specified number of lines of a file from start to end of the file.(iii) Display the file content with line number(iv) Update the file content with I/O redirection(v) Rename the fileb. Write a Shell program to check the given integer is Armstrong number or not.c. Write a C program using dynamic memory allocation to copy one matrix to another matrix

9. a. Write and execute the following UNIX commands(i) Create a directory(ii) Create a file(iii) Rename the directory(iv) Rename the file(v) View the fileb. Write a Shell program to check the given integer is prime or notc. Write a C program using dynamic memory allocation to perform multiplication of two matrices

10. a. Write and execute the following UNIX commands(i) Create a file(ii) Update the file(iii) Display the file content(iv) Display the file with line number(v) Count the number of words in the fileb. Write a Shell program to generate prime numbers between 1 and 50c. Write a C program using dynamic memory allocation to find the sum of elements of a matrix

40

Page 41: Cp 2 Lab Manual Final

GE2155–Computer Practice II

11. a. Write and execute the following UNIX commands(i) Create a Directory called main(ii) Create a sub-directory called sub in the main directory(iii) Create a file in the main directory(iv) Copy the file to the sub directory(v) Delete the file in the main directoryb. Write a Shell program to find the sum of square of individual digits of a numberc. Write a C program using dynamic memory allocation to develop a mark sheet of 5 students.

12. a. Write and execute the following UNIX commands (i) Display the calendar (ii) Display the date and time (iii) Display the present working directory (iv) Display your user name (v) Create a file using cat commandb. Write a Shell program to find the sum of cube of individual digits of a numberc. Write a C program using dynamic memory allocation to develop salary details of 5 employees

13. a. Write and execute the following UNIX commands (i) Use finger command (ii) Use grepcommand (iii) Use diff command (iv) Use uniqcommand (v) Use cmp commandb. Write a Shell program to execute various UNIX commands using case statementsc. Write a C program using dynamic memory allocation to find the minimum and maximum of a set of numbers.

14. a. Write and execute the following UNIX commands(i) Create a directory(ii) View all directories from a user(iii) Rename a directory(iv) View all the directories starting with a specific character.(v) View only the hidden directoriesb. Write a Shell program to count the number of vowels in a line of textc. Write a C program to find the sum of ‘n’ numbers using function.

15. a. Write and execute the following UNIX commands (i) Create a file (ii) View only files from a directory (iii) Rename a file (iv) View all files starting with a specific character (v) View all the files which has a specific extensionb. Write a Shell program to display student gradesc. Write a C program using pointers to allocate a memory for the string “University” and reallocate the memory for the string to “University Examinations”

41

Page 42: Cp 2 Lab Manual Final

GE2155–Computer Practice II

16. a. Write and execute the following UNIX commands (i) Create a directory with the name of Exam (ii) Change the Exam directory as the working directory (iii) Create a file called exam.txt in the Exam directory (iv) View the content of the exam.txt file (v) Rename the file exam.txt to test.txtb. Write a Shell program to find the smallest number from a set of numbersc. Write a C program using pointers to combine two array elements without duplicate

17. a. Write and execute the following UNIX commands (i) To check the working directory (ii) Change the password (iii) To display today’s date (iv) To display the calendar of this month (v) To display a message “University Exam” using a special characterb. Write a Shell program to find the smallest digit from a numberc. Write a program to perform file copy operation

18. a. Write and execute the following UNIX commands(i) Create two directories called CS1101 and CS1102(ii) Create a file called cs1101.txt in the CS1101 directory(iii) Copy the file cs1101.txt from CS1101 to CS1102(iv) Update the file content of cs1101.txt in the CS1102 directory(v) Rename the file in the CS1102 with cs1102.txtb. Write a Shell program to find the sum of all numbers between 50 and 100, which are divisible by3 and not divisible by 5c. Write a program to create two files and perform merge operation on it

19. a. Write and execute the following UNIX commands (i) Create a file (ii) Rename a file (iii) Change the mode of the file to read only (iv) View the content of a file (v) Count the number of words in a fileb. Write a Shell program to find the sum of digits of a number until a single digit is obtained.c. Write a C program using dynamic memory allocation to copy one matrix to another matrix

20. a. Write and execute the following UNIX commands (i) Count the specific number of lines from a file start from the beginning of the file(ii) To destroy a specific file from a user directory(iii) Send a greeting message to other user(iv) Execute a shell program(v) To display current timeb. Write a Shell program to find the second highest number from a set of numbersc. Write a C program using dynamic memory allocation to develop salary details of 5 employees

42

Page 43: Cp 2 Lab Manual Final

GE2155–Computer Practice II

Mark AllocationUNIX Commands - 10 marksShell Programming* - 40 marksC - Programming* - 40 marksViva-voce - 10 marks----------------Total - 100 marks----------------* Shell programming and C programming mark allocation (40 marks)Algorithm - 10 marksProgram - 20 marksExecution - 10 marks--------------Total - 40 marks--------------

43