Sie sind auf Seite 1von 43

GE2155Computer Practice II

Ex. No: 1.1 AIM

STUDY OF UNIX OPERATING SYSTEM

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. SingleUserThe system will have its own hard disk, memory, CPU and other resources all dedicated to a single user. Eg. MS-DOS 2. MultiUserThe 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 systemMulti-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 systemMultitasking is the capability of the operating system to perform various task simultaneously,i.e. a user can run multiple tasks concurrently. 3. Programming FacilityUNIX is highly programmable, the UNIX shell has all the necessary ingredients like conditional and control structures, etc. 4. SecurityUNIX allows sharing of data; every user must have a single login name and password. So, accessing another users data is impossible without his permission. 5. PortabilityUNIX is portable because it is written in a high level language. So, UNIX can be run on different computers. 1

GE2155Computer Practice II

6. CommunicationUNIX 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.

GE2155Computer 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 filesContains stream of data. All data, text, source programs, object and executable code, commands fall into this category. Directory filesContains 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 filesEven 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.

GE2155Computer 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 date date +%D date +%T date +% Y date +% H cal cal year cal month year who who am i tty uname uname r uname n echo "txt" echo $HOME bc lpfile man cmdname history exit Function Used to display the current system date and time. Displays date only Displays time only Displays the year part of date Displays the hour part of time Calendar of the current month Displays calendar for all months of the specified year Displays calendar for the specified month of the year Login details of all users such as their IP, Terminal No, User name, Used to display the login details of the user Used to display the terminal name Displays the Operating System Shows version number of the OS (kernel). Displays domain name of the server Displays the given text on the screen Displays the user's home directory Basic calculator. Press Ctrl+d to quit Allows the user to spool a job along with others in a print queue. Manual for the given command. Press q to exit To display the commands used by the user since log on. Exit from a process. If shell is the only process then logs out

Directory commands Command pwd mkdirdir mkdirdir1 dir2 cd subdir cd cd / Function Path of the present working directory A directory is created in the given name under the current directory A number of sub-directories can be created under one stroke Change Directory. If the subdir starts with / then path starts from root (absolute) otherwise from current working directory. To switch to the home directory. To switch to the root directory. 4

GE2155Computer Practice II

Command cd .. rmdirsubdir File commands Command cat >filename cat filename cat >>filename cpsrcdes cp isrcdes cp r src des mv oldnew mv f1 f2 f3 dir mv v old new rmfile rm * rm r * rm f * ls lsname lsname* ls a ls x dirname ls R ls l cmpfile1 file2 wcfile chmodperm file

Function To move back to the parent directory Removes an empty sub-directory.

Function To create a file with some contents. To end typing press Ctrl+d. The > symbol means redirecting output to a file. (< for input) Displays the file contents. Used to append contents to a file Copy files to given location. If already exists, it will be overwritten Warns the user prior to overwriting the destination file Copies the entire directory, all its sub-directories and files. To rename an existing file or directory. i option can also be used To move a group of files to a directory. Display name of each file as it is moved. Used to delete a file or group of files. i option can also be used To delete all the files in the directory. Deletes all files and sub-directories To forcibly remove even write-protected files Lists all files and subdirectories (blue colored) in sorted manner. To check whether a file or directory exists. Short-hand notation to list out filenames of a specific pattern. Lists all files including hidden files (files beginning with .) To have specific listing of a directory. Recursive listing of all files in the subdirectories Long listing showing file access rights (read/write/execute-rwxfor user/group/others-ugo). Used to compare two files. Displays nothing if files are identical. It produces a statistics of lines (l), words(w), and characters(c). 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.

GE2155Computer Practice II

Command Function headused to display the first few records (10 records by default) head stud Displays first 10 records by default head -5 stud Displays first 5 records head -1 stud | wc c length of first record tailused to display the last few records (10 records by default) tail stud Displays last 10 records by default tail -5 stud | tee last5 Last 5 records listed & stored in file last5 using tee cutused 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 wise cut d \| -f 1,3,4 stud Fields 1,3,4 listed cut d \| -f 2-4 stud Fields 2,3,4 listed paste d \| list1 list2 merges two cut files list1 and list2 sortreorders the file as per ASCII sequence. The t option is used to specify delimiter sort stud Sorted on 1st column by default sort t \| +2 stud Sort as per 3rd column sort c stud Check if file is sorted using c option sort t \| +3 -4 +4 stud Sorting on secondary keys sort -t \| -nr +4 stud Sort on numeric field using n option, r for reverse uniq stud Display unique entries in a sorted file nldisplay file content with lines numbered. The s option is used to specify separator nl s "|" stud Displays entries numbered with separator | trtranslates 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 grep this demo grep 'end of' demo grep this demo* grep c to demo grep n sequence demo grep v word demo grep l vim * grep i WORD demo grep '^[0-9]' demo grep '[0-9]$' demo ls -l | grep "^d" grep c "^$" demo grep "2....$" stud egrep "lower|UPPER" demo Function Lists the lines that contains the string this Quotes mandatory for text containing space Search this in multiple files Number of occurrence of the word to in the file Display line numbers along with matching lines Displays lines that does not contain the text word Displays files containing text vim Search for text ignoring case differences Lines that start with a number Lines that end with a number Display the subdirectory names Display count of blank lines in the file. Display lines that ends in the range 2000029999 Display lines that match either lower or upper 6

GE2155Computer 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. Result Thus 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

GE2155Computer 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?

GE2155Computer Practice II

Ex. No: 1.3 Aim

STUDY OF VI EDITOR

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 modeWhere any key depressed is entered as text 2. Command modeWhere keys are used as commands to act on text (initial mode) 3. ex modeex 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 i I a A o O Function Inserts text to the left of the cursor. Inserts text at the beginning of line. Appends text to right of cursor Appends text at end of line Opens line below Opens line above

GE2155Computer 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 Function R 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 line dw Cuts the entire word d$ Cuts a line from cursor position to the end of the line d0 Cuts from the cursor position to the start of the line yy Copies (yanks) the entire line yw Copies the entire word p Pastes the text NAVIGATION COMMANDS Command b w | $ k j h l Ctrl+f Ctrl+b lG Function Moves back to beginning of a word Moves forward to beginning of word Moves to start of the line Moves to end of the line Up one line Down one line Left one character Right one character Scrolls a page forward Scrolls a page backward 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 Function w Saves file, displays the number of lines & characters and returns to 10

GE2155Computer Practice II

w file L1,L2 w file

q q! wq sh %s/Sstr/Rstr/g

r file new file

Input mode. If it is an unnamed file then vi puts a message. The file is saved under the given name 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. Quits vi session and returns to $ prompt. vi has a safety mechanism that warns if changes made to file are not saved. Quits vi session without saving any changes made since the last save Save and exit Escape to shell 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. To insert another file into the current file. Splits screen into multiple windows and opens the file.

~ ~ ~ ~ ~ ~ ~ ~ ~ Sample.txt [New File] vi Editor for new file This is vi improved vim A rudimentary text ~ ~ ~ ~ ~ ~ vi editor ~ ~ ~ Sample.txt 2L, 30C written viEditorwith Contents Result Thus the study of text manipulation using vieditor has been completed successfully.

11

GE2155Computer Practice II

Ex. No: 2 Aim

SHELL PROGRAMS

To 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. Operator -eq -ne -gt -ge -lt -le -a -o ! Description Equal to Not equal to Greater than Greater than or equal to Less than Less than or equal to Logical AND Logical OR Logical NOT

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 12

GE2155Computer Practice II

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 one is an elif ladder, in which conditions are tested in sequence, but only one set of statements is executed. Syntax 1: if[condition] then statements fi Syntax 2: if [ condition] then statements else statements fi Syntax 3: if [condition] then statements elif [condition] then statements .. . else statements fi

The case statement is used to compare a variables 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 |. casevariablein constant1) statements ;; constant2) statements ;; ... constantN) statements ;; *) statements esac 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 list do statements done The while loop executes the statements as long as the condition remains true. while [ condition ] do statements done

13

GE2155Computer Practice II

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

2.1 -Write a Shell program to Swap values of two variables Algorithm Step 1 : Step 2 : Step 3 : Start Read the values of a and b Interchange the values of a and b using another variable t as follows: t=a a=b b=t Print a and b Stop

Step 4 : Step 5 :

Program (swap.sh) # Swapping values echo -n "Enter value for A : " read a echo -n "Enter value for B : " read b t=$a a=$b b=$t echo "Values after Swapping" echo "A Value is $a" echo "B Value is $b" Output [vijai@localhost simple]$ sh swap.sh Enter value for A : 12 Enter value for B : 23 Values after Swapping A Value is 23 B Value is 12

Result:

14

GE2155Computer Practice II

2.2 -Write a Shell program to covert Fahrenheit to Centigrade Algorithm Step 1 : Step 2 : Step 3 : Step 4 : Step 5 : Program # Degree conversion echo -n "Enter Fahrenheit : " read f c=`expr\( $f - 32 \) \* 5 / 9` echo "Centigrade is : $c" Output [vijai@localhost simple]$ sh degconv.sh Enter Fahrenheit : 213 Centigrade is : 100 Start Read fahrenheit value Convert fahrenheit to centigrade using the formulae: (fahrenheit 32) 5/9 Print centigrade Stop

Result:

15

GE2155Computer Practice II

2.3 -Write a Shell program to calculate the Area & Circumference of a Circle Algorithm Step 1 : Step 2 : Step 3 : Step 4 : Step 5 : Step 6 : Step 7 : Start Define constant pi = 3.14 Read the value of radius Calculate area using formulae: pi radius2 Calculate circumference using formulae: 2 pi radius Print area and circumference Stop

Program (circle.sh) # Circle metrics using readonly variable pi=`expr "scale=2; 22 / 7" | bc` readonly pi # pi value cannot be altered echo -n "Enter value for radius : " read radius area=`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.sh Enter value for radius : 12 Area : 452.16 Circumference : 75.36

Result:

16

GE2155Computer Practice II

2.4 -Write a Shell program tocalculate Simple Interest Algorithm Step 1 : Step 2 : Step 3 : Step 4 : Step 5 : Program Program (simpint.sh) # Interest computation using bc echo -n "Enter Principal amount : " read p echo -n "Enter number of years : " read n echo -n "Enter rate of interest : " read r si=`expr "scale=2; $p * $n *$r / 100" | bc` echo "Simple Interest : $si" Output [vijai@localhost simple]$ sh simpint.sh Enter Principal amount : 1285 Enter number of years : 3 Enter rate of interest : 5 Simple Interest : 192.75 Start Read the values principal, rate and years Compute simpleinterest using the formulae: (principal rate years) / 100 Print simpleinterest Stop

Result:

17

GE2155Computer Practice II

2.5 -Write a Shell program to check whether a given number is odd or even Algorithm Step 1 : Step 2 : Step 3 : Step 3.1 : Step 4 : Start Read number If number divisible by 2 then Print "Number is Even" else Print "Number is Odd" Stop

Program (oddeven.sh) # Odd or even using if-else echo -n "Enter a non-zero number : " read num rem=`expr $num % 2` if [ $rem -eq 0 ] then echo "$num is Even" else echo "$num is Odd" fi Output [vijai@localhost decision]$sh oddeven.sh Enter a non-zero number : 12 12 is Even

Result:

18

GE2155Computer Practice II

2.6 -Write a Shell program to display student grades Algorithm Step 1 : Step 2 : Step 3 : Step 3.1 : Step 3.2 : Step 3.3 : Step 3.4 : Step 3.5 : Step 3.6 : Step 4 : Start Read mark If mark> 90 then Print "S grade" else if mark> 80 then Print "A grade" else if mark> 70 then Print "B grade" else if mark> 60 then Print "C grade" else if mark> 55 then Print "D grade" else if mark 50 then Print "E grade" else Print "U grade" Stop

Program(grade.sh) echo -n "Enter the mark : " read mark if [ $mark -gt 90 ] then echo "S Grade" elif [ $mark -gt 80 ] then echo "A Grade" elif [ $mark -gt 70 ] then echo "B Grade" elif [ $mark -gt 60 ] then echo "C Grade" elif [ $mark -gt 55 ] then echo "D Grade" elif [ $mark -ge 50 ] then echo "E Grade" else echo "U Grade" fi

19

GE2155Computer Practice II

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

Result:

20

GE2155Computer 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

GE2155Computer Practice II

2.8 -Write a Shell program to find biggest of 3 numbers Algorithm Step 1 : Step 2 : Step 3 : Step 3.1 : Step 3.2 : Step 4 : Program # Biggest using logical expression echo -n "Give value for A B and C: " read a b c if [ $a -gt $b -a $a -gt $c ] then echo "A is the Biggest number" elif [ $b -gt $c ] then echo "B is the Biggest number" else echo "C is the Biggest number" fi Output [vijai@localhost decision]$sh big3.sh Give value for A B and C: 4 3 5 C is the Biggest number Start Read values of a, b and c If a>b and a>c then Print "A is the biggest" else if b>c then Print "B is the biggest " else Print "C is the biggest" Stop

Result:

22

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

Algorithm

Program

Output

Result:

23

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

Algorithm

Program

Output

Result:

24

GE2155Computer Practice II

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

Program

Output

Result:

25

GE2155Computer Practice II

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

Program

Output

Result:

26

GE2155Computer Practice II

2.13 Write a Shell program to check whether a letter is vowel or not. Algorithm Step 1 : Step 2 : Step 3 : Step 3.1 : Step 4 : Start Read char If char is either 'a', 'e', 'i', 'o' or 'u' then Print "It's a vowel" else Print "It's a consonant" Stop

Program (vowel.sh) # check for vowel echo -n "Key in a lower case character : " read choice case $choice in a|e|i|o|u) echo "It's a Vowel";; *) echo "It's a Consonant" esac Output [vijai@localhostmultway]$sh vowel.sh Key in a lower case character : e It's a Vowel

Result:

27

GE2155Computer Practice II

2.14.Write a shell program to print Multiplication Table Algorithm Step 1 : Step 2 : Step 3 : Step 4 : Step 5 : Step 6 : Step 7 : Start Read the value of n Initialize 1 to i Print n, i, ni Increment i by 1 Repeatsteps 4 and 5tilli 10 Stop

Program (multable.sh) # Multiplication table using for loop clear echo -n "Which multiplication table? : " read n for x in 1 2 3 4 5 6 7 8 9 10 do p=`expr $x \* $n` echo -n "$n X $x = $p" sleep 1 done Output [vijai@localhost loops]$sh multable.sh Which multiplication table? : 6 6X1=6 6 X 2 = 12 6 X 3 = 18 6 X 4 = 24 6 X 5 = 30 6 X 6 = 36 6 X 7 = 42 6 X 8 = 48 6 X 9 = 54 6 X 10= 60

Result:

28

GE2155Computer Practice II

2.15.Write a shell program to compare two strings. Algorithm Step 1 : Step 2 : Step 3 : Start Read two strings str1 and str2. If str1 = str2 Print The strings are same Else Print The strings are not same Stop

Step 4 : Program

Output

Result:

29

GE2155Computer 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 numbers Step 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

GE2155Computer 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 numbers 7. 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); } Output Enter number of items to be stored: 4 Enter number #0:3 Enter number #1:2 Enter number #2:1 Enter number #3:5 You have entered: 3 2 1 5 Result: Thus the program is written and executed to allocate memory for array using Calloc.

31

GE2155Computer Practice II

3.3 - Write a C program to allocate space for a string dynamically and print the string backwards Aim To 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

GE2155Computer 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 array Step 2: Allocate memory for the array using malloc function Step 3: Input the elements of the array Step 4: Input the element to be searched Step 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)/2 Step 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

GE2155Computer Practice II

3.5 -Write a C program to copy one file to another file Aim To 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 destination file 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.txt This is Bensam. Hi, How are you! Content of Jovita.txt This is Bensam. Hi, How are you!

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

34

GE2155Computer 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

GE2155Computer 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

GE2155Computer 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

GE2155Computer 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

GE2155Computer 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 odd c. 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 years c. 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

GE2155Computer 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 users 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.txt b. Write a Shell program to find the roots of a quadratic equation c. 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 file b. 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 file b. Write a Shell program to check the given integer is prime or not c. 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 file b. Write a Shell program to generate prime numbers between 1 and 50 c. Write a C program using dynamic memory allocation to find the sum of elements of a matrix

40

GE2155Computer 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 directory b. Write a Shell program to find the sum of square of individual digits of a number c. 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 command b. Write a Shell program to find the sum of cube of individual digits of a number c. 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 command b. Write a Shell program to execute various UNIX commands using case statements c. 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 directories b. Write a Shell program to count the number of vowels in a line of text c. 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 extension b. Write a Shell program to display student grades c. 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

GE2155Computer 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.txt b. Write a Shell program to find the smallest number from a set of numbers c. 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 todays date (iv) To display the calendar of this month (v) To display a message University Exam using a special character b. Write a Shell program to find the smallest digit from a number c. 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.txt b. Write a Shell program to find the sum of all numbers between 50 and 100, which are divisible by 3 and not divisible by 5 c. 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 file b. 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 time b. Write a Shell program to find the second highest number from a set of numbers c. Write a C program using dynamic memory allocation to develop salary details of 5 employees

42

GE2155Computer Practice II

Mark Allocation UNIX Commands - 10 marks Shell Programming* - 40 marks C - Programming* - 40 marks Viva-voce - 10 marks ---------------Total - 100 marks ---------------* Shell programming and C programming mark allocation (40 marks) Algorithm - 10 marks Program - 20 marks Execution - 10 marks -------------Total - 40 marks --------------

43

Das könnte Ihnen auch gefallen