Vous êtes sur la page 1sur 42

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) Page 1 of 42

File handling

HARDWARE / SOFTWARE REQUIREMENTS FOR A BATCH OF 30 STUDENTS Hardware 1 UNIX Clone Server 33 Nodes (thin client or PCs) Printer 3 Nos Software OS-UNIX clone (33 user license or License free Linux) Compiler- C

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 Experiments
I. UNIX COMMANDS 1. Basic Shell Commands (6 Hrs) 2. Unix Editor (3 Hrs) II. SHELL PROGRAMMING 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 15 15

III. C PROGRAMMING ON UNIX 9. Write a C Program to find Prime No.

15 Page 2 of 42

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 3 of 42

Ex.No.1
1) Command : cat

Study of Basic Unix Commands

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 [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 col1.txt college.txt fir.sh coll.txt firs.sh one.txt new.txt second.sh one pgms programs` cat >one.txt

college2.txt file.txt [it@rcet ~]$

Page 4 of 42

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
Page 5 of 42

col1.txt college.txt file.txt firs.sh one [it@rcet ~]$

pgms

second.sh

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 . .. a.out .bashrc col1.txt .emacs.d file.txt new.txt one one.txt pgms .swn .swp .viminfo .xemacs .zshrc .swo

college2.txt fir.sh

.bash_history college.txt firs.sh .bash_logout coll.txt .bash_profile .emacs [it@rcet ~]$ d) [it@rcet ~]$ ls x .gtkrc

.five.sh.swp programs .viminfo.tmp second.sh .viminfz.tmp

Page 6 of 42

a.out

col1.txt college2.txt college.txt coll.txt file.txt fir.sh one.txt pgms programs second.sh

firs.sh new.txt one [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 new.txt pgms second.sh
Page 7 of 42

col1.txt college.txt fir.sh [it@rcet ~]$ rm new.txt

[it@rcet ~]$ ls a.out college2.txt file.txt firs.sh pgms one second.sh col1.txt college.txt fir.sh [it@rcet ~]$ programs

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 one second.sh col1.txt college.txt fir.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 (Dont Print a New Line)
Page 8 of 42

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

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
Page 9 of 42

[it@rcet ~]$

13) Command : who (Displays the Users Who Logged into the System) [it@rcet ~]$ who cse it pts/2 pts/1 Apr 15 13:34 (192.168.1.21) 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 [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 5 6 7 8 2 3 4 9 10 11 Apr 15 15:10 (192.168.1.69)

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

Page 10 of 42

16) Command : wc (Counts the No. of Chars, Bytes, lines, Chars in the Longest Line) [it@rcet ~]$ wc -m college.txt 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.
Page 11 of 42

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). Syntax sort filename sort r filename (sort in the reverse order) Example users.txt jdoe John Doe 4/15/96 lsmith Laura Smith 3/12/96 pchen Paul Chen 1/5/96 jhsu Jake Hsu 4/17/96 sphilip Sue Phillip 4/2/96 [it@rcet ~]$ sort users.txt jdoe John Doe jhsu Jake Hsu lsmith Laura Smith pchen Paul Chen sphilip Sue Phillip 4/15/96 4/17/96 3/12/96 1/5/96 4/2/96

19) Command : uniq (Simple Filter to remove duplicates) uniq filters duplicate adjacent lines from a file. Syntax uniq file [file.new] Example Consider the following file and example, in which uniq removes the 4th line from file and places the [it@rcet ~]$ cat > fi 1236 4536 7890 7890 [it@rcet ~]$ uniq file file.new [it@rcet ~]$cat file.new 1236 4536 7890 20) Command: pipes ( | - redirect the output to one command to Another Command)
Page 12 of 42

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 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
General Information: About vi:

UNIX Editor

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. Page 13 of 42

A Brief vi Session: Starting vi: 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. Page 14 of 42

Line Numbers: 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 vi File Name vi vi -r File Name view File Name vipw There are three modes of operation: Meaning Open or Create File Open New File To Be Named Recover Crashed File Open File Read-Only Edit the /etc/passwd file, setting locks and doing appropriate processing. Command Mode Insert Mode Last Line Mode Vi Commands A Quick Review Vi Commands Used To Edit Files Positioning The Cursor: Command h j k l w Meaning Move left one character Move down one line Move up one line Move right one character Move right one word Page 15 of 42

W b B e Return Backspace H M L Control-f Control-d Control-b G 1G 21G

Move right one word (Past Punctuation) Move left one word Move left one word (Past Punctuation) Move to end of current word Move down one line Move left one character Move to top of screen Move to middle of screen Move to bottom on screen Scroll forward one screen Scroll forward one-half screen Scroll backward one-half screen Go to last line of file Go to first line of file Go to 21st line of file Table Vi Commands to Edit Files

Appending Commands: Command A A I I O O Meaning Append text after cursor Append text at line end Insert text before cursor Insert text at beginning of line Insert line below cursor 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 Page 16 of 42

clap loudly exploded. Glancing back, I saw an ocean rising behind us. It just wouldnt stop raining. Our weathered tent 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 x X dw dd D dG d1G :5,10d Meaning Delete Character at the cursor Delete character to the left of the cursor Delete word (or part of word to right of cursor) Delete line containing the cursor Delete part of line to right of cursor Delete to end of file Delete from beginning of file to cursor 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 lets 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 wouldnt stop raining. Move the cursor anywhere on that line, and type dd. The line vanishes. Changing Text: Command CW Meaning Change word (or part of word) to right of cursor Page 17 of 42

cc c s r r Return Examples:

Change line Change from cursor to end of line Substitute string for characters from cursor forward Replace character at cursor with one other character Break line Lets 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. Well 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 J xp ~ u or :u Meaning Join current line and line below Transpose character at cursor and character to the right Change case of letter (upper or lower ) 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: Page 18 of 42

i
and insert the following text: I saw everything spinning wildly. RETURN 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 y Y p P Meaning Yank or copy line Yank or copy line Put yanked or deleted line below current 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. Page 19 of 42

2. Type mletter to set a marker. 3. Move the cursor to the other end. 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 :w :w new file :wq :q! Meaning Save changes (write buffer) Write buffer to named file Save changes and quit Vi Quit without saving changes Commands to Save and Quit Displaying and Hiding Line: Command :set nu :set nonu :set ic :set noic :set list Meaning Show line numbers Hide line numbers; setting is case sensitive Searches should ignore case Searches should be case sensitive Display invisible characters Commands to Hide and Display a Line Search and Replace:

Page 20 of 42

Command /string ?string N N :%s/old/new/g

Meaning Search for string Search backward for string Find next occurrence of string in search direction Find previous occurrence of string in search direction Search and replace Commands to Search and Replace

Refresh the Screen and Including Files: Command Control-1 :r file name :34r file name Meaning Clear (refresh) scrambled screen Insert (read) file after cursor 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.)

Page 21 of 42

Ex.No.3 (a) Shell Script to swap values in two variables x and y 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 Calculator Algorithm:


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
Page 22 of 42

6. End the program

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

Page 23 of 42

Ex.No.7 Shell script to find whether an input number is Armstrong or not Algorithm:
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

Page 24 of 42

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 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 Aim To write a C Program to Sort n Numbers in Ascending Order. Algorithm: 1. Start the Program 2. Declare variables x, n, i, j as Integer type 3. Declare variable a as Integer array of 100 elements 4. Read the no. of elements to be stored in the array in variable n 5. Using For Loop, till the value of i is less than n a. Read the Elements of the array 6. 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-1 i. 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
Page 25 of 42

a. Print the Elements of Array 8. Stop the Program Result Hence the Given n Numbers are sorted in Ascending Order using C Program. 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 Allocation Aim 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
Page 26 of 42

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 ptr 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.
Page 27 of 42

Programs

Ex.No.3(a) 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"
Page 28 of 42

if [ $# -eq 0 ] then echo "$0 string1 string2" exit 1 fi len=$(expr length $OUT) 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 ));;
Page 29 of 42

-) echo $(( $a - $b ));; /) echo $(( $a / $b ));; x) echo $(( $a * $b ));; *) echo "Error";;

Output:
[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"
Page 30 of 42

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 echo "Sorry cannot guess number" fi

Output:
[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
Page 31 of 42

if [ $on -eq $rev ] then echo "Number is Palindrome" else echo "Number is not a Palindrome" fi

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))
Page 32 of 42

done if [ $sum -eq $no ] then echo "$no is armstrong number." else echo "$no is not armstrong number." 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
Page 33 of 42

a=$b b=$c i=`expr $i + 1` done

Output:
[it@raja ~]$ sh seven.sh 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;
Page 34 of 42

} i=i+1; } if(no==i) printf("\n%d is a prime no.\n",no); getchar(); }

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++)
Page 35 of 42

if(a[j]>a[j+1]) { x=a[j]; a[j]=a[j+1]; a[j+1]=x; } } 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
Page 36 of 42

6 8 9 11 [it@raja ~]$

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");
Page 37 of 42

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; }

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++)
Page 38 of 42

{ *(ptr+i)=i; } for(i=number;i>0;i--) { printf("Number %d is stored at Location %d\n",*(ptr+(i-1)),(ptr+(i-1))); } 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 39 of 42

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);
Page 40 of 42

printf("\nData Output\n"); f1=fopen("Input.txt","r"); while((c=getc(f1))!=EOF) printf("%c",c); printf("\n"); fclose(f1); }

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 41 of 42

Page 42 of 42

Vous aimerez peut-être aussi