You are on page 1of 67

GE2155 COMPUTER PRACTICE LABORATORY II 0 1 2 2

LIST OF EXPERIMENTS

1. UNIX COMMANDS Study of Unix OS - Basic Shell Commands - Unix Editor 2. SHELL PROGRAMMING Simple Shell program - Conditional Statements - Testing and Loops 3. C PROGRAMMING ON UNIX Dynamic Storage Allocation-Pointers-Functions-File Handling

15

15

15

TOTAL : 45 PERIODS

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

LIST OF EXPERIMENTS
EX.NO 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. TITLE UNIX COMMANDS Study Of Unix Operating System Basic Shell Commands Unix Editor SHELL PROGRAMMING Odd Or Even Largest Among Two Numbers Largest Among Three Numbers Leap Year Area And Circumference Of A Circle Armstrong Number Interchanging Two Numbers Prime Number Fibonacci Series Factorial Of A Number Sum Of Digits Sum Of Square Of Individual Digits Unix Commands Using Case Statements Sum Of Numbers Between 50 And 100 Palindrome - String Student Details Counting No. Of Vowels In A String Palindrome Number Smallest Number Second Largest Number C PROGRAMMING Ascending Order Matrix Addition Matrix Multiplication Memory Reallocation Using Realloc Sum Of N Numbers Using Function Sum Of Digits Using Function Reverse Of A Number Using Function Swapping Of Two Numbers Using Pointers File Copy Operation Linear Search 34 35 37 39 40 41 42 43 44 45 PAGE NO. 1 3 5 11 12 13 14 15 16 17 19 21 22 23 24 25 27 28 29 30 31 32 33

EX No 1 Date: INTRODUCTION TO UNIX STUDY OF UNIX OPERATING SYSTEM Aim: To Understand the Basic concepts of the Unix Operating System Procedure : An operating system (commonly abbreviated OS and O/S) is the software component of a computer system that is responsible for the management and coordination of activities and the sharing of the limited resources of the computer. Operating systems offer a number of services to application programs and users. Applications access these services through application programming interfaces (APIs) or system calls. By invoking these interfaces, the application can request a service from the operating system, pass parameters, and receive the results of the operation. runs the Operating System. There are two types of Operating System 1.Single User Operating System In Single User System one person can use at a time .Examples are DOS,Windows 95. 2.Multi User Operating System. In Multi User System multiple users can use at a time. Examples are Unix,Linux etc

UNIX OPERATING SYSTEM Unix operating systems are widely used in both servers and workstations. The Unix environment and the client-server program model were essential elements in the development of the Internet and the reshaping of computing as centered in networks rather than in individual Computers Unix was designed to be portable, multi-tasking and multi-user in a timesharing configuration. Unix systems are characterized by various concepts: the use of plain text for storing data; a hierarchical file system; treating devices and certain types of inter-process communication (IPC) as files; and the use of a large number of software tools, small programs that can be strung together through a command line interpreter These concepts are known as the Unix philosophy.

Under Unix, the operating system consists of many of these utilities along with the master control program, the kernel. The kernel provides services to start and stop programs, handle the file system and other common low level tasks that most programs share and perhaps most importantly schedules access to hardware to avoid conflicts. PARTS OF THE UNIX OPERATING SYSTEM The unix Operating System have three Parts They are 1.Kernal 2.Shell 3.Users Shell Programs.

Kernal It is the main part of the operating system. It controls all the resources, users, hardware and tasks that are present in the system. So we can define kernel as the Master program which act as the heart of the The functions of the kernel are 1. Receives user command from the shell 2. Communicates with the hardware. 3. Control all the computer resources 4. Runs scheduler. 5. Run all the programs. Shell The user cannot directly interact with the kernel. During the login of the user the kernel starts an interactive program for each user. This program is known as shell. The shell acts as an interface between the user and kernel. The shell will act as an interpreter. When user gives some command the shell analyses those commands and passes them to the kernel. The kernel then submits these commands to hardware and the required actions are carried out. This process is shown below:

FILES AND DIRECTORIES A file is a collection of information that is assigned a name that is used to identify that file. The file is always stored in secondary storage medium. A directory is a special type file that contains a list of file names. All files are grouped together into directory for easier access. A directory can have one or more directories in it called sub-directories.In LINUX files and directories are arranged in a hierarchical manner. DIRECTORY HIERARCHY OF UNIX In UNIX every file is assigned to some directory. The root directory is the main directory and named as I. All the other files and directories are its subdirectories.

The details of the different types of the Directories is given Below

Result: Thus the Basic concepts of the Unix Operating System was studied.

Ex no:2 Date: BASIC UNIX COMMANDS Aim: To study about unix commands Commands: 1. Cat The cat command is used to create a file Syntax : cat > filename Example : cat>test Hello Ctrl+d ( to save & exit from the file creation ) Used to concatenate the file1,file2 content and stored in file3 Used to concatenate the file1 at the end of file2 Syntax : cat file1 file2>file3 cat file1>>file2 Example : cat test1 Hai Ctrl+d cat test test1>test3 cat test3 2. Mkdir To create a directory or sub directory in disk Syntax: mkdir directory name Example : pwd mkdir cplab 3. Cd To move from one directory another directory Syntax: cd directory name Example : cd cplab pwd 4. Cd .. To exit from the single directory or leave form the directory Syntax : cd .. Example : cd .. 5. Rmdir To remove directory from disk While the directory should be empty & you are exit from the directory Syntax: rmdir directory name Example: rmdir cplab 6. Clear To clear the screen Syntax: clear Example: clear

7. Cp The cp command is used to copy the content of one file to another file. Opt may be -i used to warn the user before overwriting the destination file R used to copy the entire directory Syntax: cp -opt oldfilname duplicate filename Example: cp -i test copyoftest cat copyoftest 8. Rm It is used to dele the file or remove the file The opt may be i used to ask for confirmation before removing the file -r or -R used to search and delete file from subdirectories -f used to prompt file is write protected ( if protected) Syntax: rm -opt filename Example: rm copyoftest ir 9. Wc Used to count the no of line ,word and character in a specified file opt may be c no of char only in a file w - no of words only in a file l no of lines only in a file Syntax: wc -opt filename Example: wc list wc list -l wc list -w 10. Head It displays the first ten lines of a file Opt may be Integer no to display number of lines to display in screen Syntax: head -opt filename Example: head list head -15 list 11. Tail It displays the last ten lines of a file Opt may be Integer no to display number of lines to display in screen Syntax: tail -opt filename Example: tail list tail -15 list 12. Date The date command is used to display the current date opt may be +%m - to display month +%h - to display month name +%d - to display day of month

+%y - to display last two digit of the year +%H - to display Hours +%M - to display Minutes +%S - to display Seconds Syntax: date opt Example: date 13. Echo To display the message in screen given in the echo command Syntax: echo message Example: Echo Hai 14. Cal To display the calendar of particular year or month Opt may be Year like cal 2004 Month and Year Like cal 2 2004 Syntax: cal opt Example: cal cal 2004 cal 2 2004 15. Who am i Used to display identify the user name and terminal line, the date and time of login Syntax: who am i Example: who am i 16. Who Used to display a data about users who are currently logged into the system Syntax: who 17. Finger Finger command display the user details Syntax: finger username Example: finger temp 18. ID Used to display the numerical value that corresponding to your login name, user id and group id Syntax: id Example: id 19. Tty Used to know the terminal name that we are using Syntax: tty Example: tty 20. Passwd The account password can be changed using passwd Syntax: passwd Example: passwd 21. The semicolon ; It is used to execute more then one command in single command line

Syntax: command1;command2;etc Example: ls;date;cat test 22. The && operator It siginifies the logical AND operation meaning. It mans that only if the first command is successfully executed then the next command will be executed Syntax: command1&&command2 Example: ls && date cat gg && date 23. The || operator It siginifies the logical OR operation meaning. It mans that the first command is not successfully then the next command will be executed. If first command executed second one not excuted Syntax: command1||command2 Example: ls || date cat gg || date 24. Pwd Used to print the current working directory Syntax: pwd Example: pwd 25. Mv It is used to rename the file and directory also to move file from one location to another location Syntax: Mv oldfilename newfilename Example: mv test3 sample mv sample /home/cplab/test3 26. Ls To display the files & directories in present directory or specified directory opt may be x - display multi column output t List files & sub directories with time order r List the files & sub directories is reverse order A List all files & sub Dir except (. ..) a - List all files c - List files by inode modification time I - List the inode for each file h - List names of hidden files also q - List the file name having non printable characters l - List in long formation ( Permission , owner , size, modification, time with file or directory name ) Syntax: ls -opt or ls -opt dir_name Example: ls -l ls r ls r*

ls ?a* ls [a]* ls [a-m]* ls l | pg ls -l /usr/bin 27. File To show file type Syntax: file filename Example: file list 28. Chmod To set file permission for files Category may be u user g group o others permission may be (+or-) rwx To set the file permission For file d1 for user d2 for group d3 for others Octal value for 4 read 2 write 1 execute Syntax: chmod category permission file name chmod d1d2d3 (octal value) filename Example: ls -l chmod u -+rwx list ls -l chmod u -rwx list ls l chmod 000 list chmod 642 list 29. Bc To act as a simple calculator Syntax: bc Example : bc 30. Grep To search the specified pattern from a file & displays the lines of the file that contains the pattern Syntax: grep pattern filename Example: grep Hello test 31. Sort

To sort the file content & display the result only in screen no change in the file content Opt may be r reverse order c checks if the file is sorted n Sorts numerically u removes duplicate records m list merges sorted files in list Syntax: sort -opt filename sort -opt filename>filename to store sorted information Example: sort test sort test>test1 32. Nl It is used to add the line number for file content and shown only in screen not in file. Syntax: nl filename Example: nl test2 33. Cmp It is compare the two files byte by byte and give the first difference find by them it show the result as a line no & column no of the difference only difference is there Syntax: cmp file name1 file name2 Example: cmp test test1 34. Comm It compare the two sorted file and give the result in three columns 1st column represent the lines common only to file1 2nd column represent the lines common only to file2 3rd column represent the lines common to file1 and file2 Syntax: comm Filename1 filename2 Example: comm test test1

35. Diff It compare the two files and show the result as a difference of the two files with line number of both files Syntax: diff file name1 file name2 Example: diff test test1 Message and mail command 36. Mesg It used to grant the permission to user for send and receive the message to or from user mesg y means y have permission mesg n means you denied the permission Syntax: mesg y or mesg n Example: mesg y 37. Write It is used to send the message to the user who presently login to the system. If u are going to executing the command it is waiting for type the message form keyboard after keying the message press ctrl+d terminate to your task. Syntax: write username

Example: write temp hello ctrl+d 38. Wall It is used to broadcast message to all users presently login into the system If u are going to executing the command it is waiting for type the message form keyboard after keying the message press ctrl+d terminate to your task. Syntax: wall message Example: wall Hello hai Ctrl+d 39. News The news command permits to user to read message published by the system administrator Syntax: news Example: news 40. Mail It is used to send the mail to the specified users. Opt may be s to reprensent subject of the mesaage. While executing the command we are going to key the message and press ctrl+d to complete the task Syntax: mail opt user name Example: mail s mail test Here I am going to check mail command Ctrl+d It used to read the message was sent by the users Syntax: mail Example: mail 41. Reply It is used to reply the message to user Syntax: reply username Example: reply temp hai ctrl+d 42. PATH PATH is a system variable it holds path to search commands when executing it. Using this command we are going to see the already set PATH Syntax: echo PATH Example: echo PATH Result: Thus the basic unix commands were studied.

EX No.3 Date: UNIX EDITOR UNIX system starts a special version of a shell called an interactive shell, and shows a shell prompt, usually in the form of a dollar sing (\$), a percent sign( %), or a pound sign (#), When we type a line of input at a shell prompt, the shett tries to interpret it. Input to a shell prompt is sometimes called a command line.The basic format Modes in vi There are three basic modes of vi: Command mode This is the default when you enter vi. In command mode, most letters, or short sequences of letters, that you type will be interpreted as commands, without explicitly pressing Enter . If you press Esc when you're in command mode, your terminal will beep at you. This is a very good way to tell when you're in command mode. Insert mode In insert mode, whatever you type is inserted in the file at the cursor position. Type a (lowercase letter a, for append) to enter insert mode from command mode; press Esc to end insert mode, and return to command mode. Line mode Use line mode to enter line oriented commands. To enter line mode from command mode, type a colon . Your cursor moves to the bottom of the screen, by a colon prompt. Type a line mode command, then press Enter. Any sensible command from the Unix line editor ex will work, and a few are good to know about. These commands are indicated in this handout by a colon in front of the command. Each time you use a line mode command, you must type a colon to enter line mode, then type the command by the colon prompt at the bottom of the screen, then press Enter when you finish typing the command.

Starting vi: vi filename Start editing filename, create it if necessary

Saving the file you're working on and/or leaving vi: :wq :q! write the file to disk and quit Quit without saving any changes

Moving the Cursor Many commands take number prefixes; for example 5w moves to the right by 5 words. Type: H J K L \$ ^ Enter G :n w E B Ctrl-b To Move To: one space to the left (also try left arrow) one line down (also try down arrow) one line up (also try up arrow) one space to the right (also try right arrow) end of current line beginning of current line beginning first word on the next line end of file line n; use :0 to move the beginning of the file beginning of next word; 5w moves to the beginning of the 5th word to the right end of next word beginning of previous word one page up

Searching for Text Type: /string ?string N To: search down for string search up for string repeat last search from present position

Inserting Text Type: a A i I o O :r newfile To: append starting right of cursor append at the end of the current line insert starting left of cursor insert at beginning of the current line open line below cursor, then enter insert mode open line above cursor, then enter insert mode add the contents of the file newfile starting below the current line

Deleting Text Type: X Dw Dd Cw Cc S D To: Delete single character; 5x deletes 5 characters Delete word; 5dw deletes 5 words Delete line; 5dd deletes ... well you get the idea! Delete word, leaves you in insert mode (i.e. change word) change line -- delete line and start insert mode change character -- delete character and start insert mode Delete from cursor to end of line

C U

change from cursor to end of line -- delete and start insert mode undo last change

Cutting and Pasting Type: Xp Yy "ayy P "aP P "ap To: transpose two characters (two commands, x followed by p) yank (i.e. copy) one line into a general buffer (5yy to yank 5 lines) yank into the buffer named a put the general buffer back before the current line put from buffer a before current line put the general buffer back after the current line put from buffer a after the current line

Miscellaneous Commands Type: Ctrl-g To: show line number of current line

Conditional and looping statements 1. If condition: If condition which is used for decision making in shell script, if given condition is true then command1 is executed Syntax: If condition Then

Command1 if condition is true or if exit status Of condition is 0 (zero) ... fi 2. Ifelseif: If given condition is true then command1 is executed otherwise command2 is executed. Syntax: If condition then condition is zero (true -0) execute all commands up to else statement else if condition is not true then execute all commands up to fi fi

3. Nested if-else-fi: You can write the entire if-else construct within either the body of the if statement of the body of an else statement. This is called the nesti8ng of ifs. You can use the nested ifs as follows also: Syntax: If condition then . Do this else . Do this fi 4. Multilevel if-then-else: Syntax: If condition Then Condition is zero (true 0) Execute all commands up to elif statement Elif condition1 Then Condition1 is zero (true -0 ) Execute all commands up to elif statement

Elif condition2 Then Condition2 is zero (true-0) Execute all commands up to elif statement Else None of the above condition,condition1,condition2 are true(i.e all of the above non-zero or false) Execute all commands upto fi Fi 5.for loop: Syntax: For{variable name} in {list} Do Execute one for each item in the list until the list is not finished (and repeat all statement between do and done) Done 6.Nesting of for loop As you see the if statements can nested,similarly loop statement can be nested. You can nest the for loop . To understand the nesting of for loop see the following shell script. Example: For ((i=1;i<=5;i++)) do for ((j=1;j<=5;j++)) do echo n \$i done

###inner for loop###

Echo ####print the new line### Done 7. While loop Syntax: While [condition] Do command1 command2 command3 .. . Done

Result: Thus the study of unix editor is studied successfully.

EX No .4 Date:

SIMPLE SHELL PROGRAMS CHECKING OF EVEN OR ODD NUMBER Aim: To write a shell program to find the given number is even or odd. Algorithm: 1. Start the program. 2. Enter the number to check even or odd, 3. Get the remainder by dividing the number by 2 (use % operator). 4. Check if remainder is zero then given number is even otherwise given number 5. Stop the program Program: #ODD-EVEN checking program echo Enter a number read a z=expr\$a%2 if test \$z eq 0 then echo Even number else echo Odd number fi Output: Enter the number 22 Even Number. Result: Thus the program is written and executed for checking the given number is even or Odd.

Ex No .5 Date:

CHECK POSITIVE OR NEGATIVE NUMBER Aim: To write a shell program to check the given number is positive or negative. Algorithm: 1. Start the program. 2. Get the number n from the user. 3. C heck if n <0 then print negative number. If n > 0 then print positive number otherwise print zero. 4. Stop the program. Program: echo Enter a number read n if test \$n-gt0 then echo Positive number elif test \$n -it 0 then echo Negative number else echo zero Output : enter the number:72 (positive number) enter a number : -3 (negative) Result: Thus the program is written and executed for checking the given number positive or Negative.

EX NO: 6 DATE:

LEAP YEAR

AIM: To write a shell program to find the given year is leap year or not. ALGORITHM: 1. Start the program. 2. Enter the year to check leap year or not. 3. Get the remainder by dividing the number by 4 (use % operator). 4. Check if remainder is zero then given year is leap otherwise its not a leap year. 5. Stop the program PROGRAM: echo "Enter the year" read y b=`expr \$y % 4` if [ \$b -eq 0 ] then echo "\$y is a leap year" else echo "\$y is not a leap year" fi OUTPUT: Enter the year 2000 2000 is a leap year Enter the year 2010 2010 is not a leap year

EX NO: 7 DATE:

AREA AND CIRCUMFERENCE OF A CIRCLE

AIM: To write a shell program to find the area and circumference of a circle. ALGORITHM: 1. Start the program. 2. Enter the radius to find area and circumference. 3. Calculate area and circumference using the formulae. 4. Display the result. 5. Stop the program PROGRAM: echo "Enter the radius" read r area=`expr "3.14 * \$r * \$r" | bc` cir=`expr "2 * 3.14 * \$r" | bc` echo "The area is " \$area echo "The circumference is " \$cir OUTPUT: Enter the radius 3 The area is 28.26 The circumference is 18.84

EX NO: 8 DATE:

LARGEST AMONG THREE NUMBERS

AIM: To write a shell program to find the largest among three numbers. ALGORITHM: 1. Start the program. 2. Enter the value of a, b and c. 3. If a is greater than b and c, then print A is greater. 4. Else, check whether b is greater than c, then print B is greater. 5. Otherwise, print C is greater 6. Stop the program PROGRAM: read a b c if [ \$a -gt \$b -a \$a -gt \$c ] then echo "\$a is Greater" elif [ \$b -gt \$c ] then echo "\$b is Greater" else echo "\$c is Greater" fi OUTPUT: Enter Three Numbers 22 55 33 55 is Greater

RESULT: Thus the program is written and executed to find the largest among three numbers.

EX NO: 9 DATE:

INTERCHANGING TWO NUMBERS

AIM: To write a shell program to interchange two numbers using a temporary variable and without using a temporary variable. ALGORITHM Using the Temporary Variable 1.Enter the two numbers. 2. Declare the temporary variable C and do the following assignments c=a, a=b and b=c. 3. Display the result. Without using temporary variable 1. Enter the two numbers by using a and b variable. 2. Then using the expressions. a= a+b, b=a-b and a=a-b, values are interchanged. 3. Display the result.

PROGRAM:1
#Swap using Temporary variable echo swapping using temporary variable echo Enter a read a echo Enter b read b
c = \$a a = \$b b = \$c

echo After swapping echo Number a is \$a echo Number b is \$b PROGRAM 2 (using the Temporary Variable) Using Temporary variable PROGRAM: 2 #swap without Temporary variable echo Swapping without using temporary variable echo Enter a read a echo Enter b read b a = expr \$a + \$b b = expr \$a \$b a = expr \$a \$b echo After swapping echo a is \$a echo b is \$b
-

OUTPUT Swapping using temporary variable Enter a 10 Enter b 15 After swapping a is 15 b is 10 Swapping without using temporary variable Enter a 6 Enter b 7 After swapping ais7 b is 6

RESULT: Thus the program is written and executed for swapping of two numbers.

EX NO: 10 DATE:

PALINDROME OR NOT

AIM: To write a shell program to find a given number is palindrome or not. ALGORITHM 1. Start the program. 2. Input a. 3. Initialize c=0, b=1. 4. Using while, loop until the number is greater than 0. b=a%10 c=s*10+b n=n/10 5. if the value of d is equal to c, then print the number is PALINDROME otherwise NOT PALINDROME 6. Stop the program

PROGRAM:
echo "Enter a number" read a d=\$a c=0 b=1 while [ \$a -gt 0 ] do b=`expr \$a % 10` c=`expr \$c \* 10 + \$b` a=`expr \$a / 10` done if [ \$d -eq \$c ] then echo "PALINDROME" else echo "NOT PALINDROME" fi

OUTPUT: Enter a number 12321 PALINDROME Enter a number 12345 NOT PALINDROME

RESULT: Thus the program is written and executed for checking a number is palindrome or not.

EX. NO: 11 DATE:

ARMSTRONG NUMBER

AIM: To write a shell program to print the Armstrong numbers between the given limit. ALGORITHM: 1. Start the program. 2. Get the boundary value from the user. 3. Initialize i = 1. 4. If i n then assign number = i. 5. If i not equal to number then separate the digits of the number by dividing 10. 6. The remainder value is cubed and it is added to the sum value. 7. Change the number = number I 10. 8. Repeat steps 5 to 7. 9. Check the number and the summed value. If both are same then that number is an Armstrong number. 10. Increment the value of i by 1. 11. Repeat steps4to 10. 12. Stop the program. PROGRAM: #Armstrong Number Generation echo "Enter a Number" read num x=\$num sum=0 while [ \$num -gt 0 ] do y=`expr \$num % 10` z=`expr \$y \* \$y \* \$y` sum=`expr \$sum + \$z` num=`expr \$num / 10` done if [ \$x -eq \$sum ] then echo "\$x is an armstrong Number" else echo "\$x is not an armstrong Number" fi

OUTPUT: Enter a Number 123 123 is not an armstrong Number Enter a Number 153 153 is an armstrong Number

RESULT: Thus the program is written and executed to find the Armstrong number.

EX NO: 12 DATE:

PRIME NUMBER

AIM: To write a shell program to find a given number is prime number or not. ALGORITHM 1. Start the program. 2. Get a number n from the user. 3. Initialize t=0. 4. Using while, loop until the number is greater than 0. b=a%10 c=s*10+b n=n/10 5. If p is equal to 0, then increment t by 1. 6. Decrement the value of i by 1. 7. If i is equal to 0, then print the number is PRIME otherwise NOT PRIME 8. Stop the program

PROGRAM:
echo "Enter a Number" read n i=`expr \$n - 1` t=0 while [ \$i -ge 2 ] do p=`expr \$n % \$i` if [ \$p -eq 0 ] then t=`expr \$t + 1` fi i=`expr \$i - 1` done if [ \$t -gt 0 ] then echo "The Number \$n is not a Prime Number" else echo "The Number \$n is a Prime Number" fi

OUTPUT: Enter a Number 7 The Number 7 is a Prime Number Enter a Number 12 The Number 12 is not a Prime Number

RESULT: Thus the program is written and executed to find a number is prime number or not.

EX NO: 13 DATE:

FIBONACCI SERIES

AIM: To write a shell program to generate the Fibonacci series for the given limit. ALGORITHM: 1. Start the program. 2. Get the limit number n from the user. 3. Assign a=0,b=l and s=0. 4. Print the value of a and b. 5. If i<n then c=a+b and assign a=b and b=c. 6. Print the value of c. 7. Increment the value of i by 1. 8. Stop the program.

PROGRAM:
echo "Enter the Limit" read n i=2 echo "Fibonacci Series" echo "--------------------" a=0 b=1 echo \$a echo \$b while [ \$i -lt \$n ] do c=`expr \$a + \$b` echo \$c a=\$b b=\$c i=`expr \$i + 1` done

OUTPUT: Enter the Limit 3 Fibonacci Series ---------------0 1 1

RESULT: Thus the program is written and executed to generate Fibonacci series.

EX.NO: 14 DATE:

FACTORIAL OF A GIVEN NUMBER

AIM: To write a shell program to find the factorial of a given number. ALGORITHM: 1. Read the number n. 2. Initialize the value of p to 1. 3. While the value of i is less than 1 find the value of n by multiplying i and n. 4. Decrement the value of i by 1. 5. Display the result. PROGRAM: echo "Enter a Number" read n i=`expr \$n - 1` p=1 while [ \$i -ge 1 ] do n=`expr \$n \* \$i` i=`expr \$i - 1` done echo "The Factorial of the given Number is \$n" OUTPUT: Enter a Number 6 The Factorial of the given Number is 720

RESULT: Thus the program is written and executed to find the factorial of the given number.

EX. NO: 15 DATE:

SUM OF DIGITS

AIM: To write a shell program to find the sum of digits of a given integer. ALGORITHM: 1. Start the program. 2. Get a number num 3. Initialize sum=0 4. Using while, loop until the number is greater than 0. y=num%10 sum =sum + y num =num/10 5. Display the result by printing the value of sum. 6. Stop the program. PROGRAM: echo "Enter a Number" read num sum=0 while [ \$num -gt 0 ] do y=`expr \$num % 10` sum=`expr \$sum + \$y` num=`expr \$num / 10` done echo "The Sum of the Digits of the Integer is \$sum" OUTPUT: Enter a Number 12345 The Sum of the Digits of the Integer is 15

RESULT: Thus the program is written and executed to find the sum of digits of an integer.

EX NO: 16 DATE:

SUM OF SQUARES OF INDIVIDUAL DIGITS

AIM: To write a shell program to find the sum of squares of individual digits. ALGORITHM: 1. Start the program. 2. Get a number a from the user. 3. Initialize b=1,c=0. 4. Using while, loop until the number is greater than 0. b=a%10 c=c + b*b a=a/10 5. Display the result by printing the value of c. 6. Stop the program

PROGRAM:
echo "enter the number" read a b=1 c=0 while [ \$a -gt 0 ] do b=`expr \$a % 10` c=`expr \$c + \$b \* \$b` a=`expr \$a / 10` done echo "The sum of square of digits is" \$c

OUTPUT: enter the number 234 The sum of square of digits is 29

RESULT: Thus the program is written and executed to find the square of individual digits.

EX NO: 17 DATE:

UNIX COMMANDS USING CASE STATEMENTS

AIM: To write a shell program to execute various UNIX commands using case statements. ALGORITHM: 1. Start the program. 2. Print the MENU 3. Get the user choice ch. 4. Using case, enter the commands to execute. 5. Stop the program.

PROGRAM:
echo " MENU" echo "1. List of files" echo "2. Today's date" echo "3. Display the Present month of a Calendar" echo "4. Logged in users" echo "5. Display in current working directory" echo "6. Quit" echo -n "Enter your choice: " read ch case \$ch in 1) ls;; 2) date;; 3) cal;; 4) who;; 5) pwd;; 6) exit;; *) echo "Invalid choice" exit;; esac

OUTPUT: MENU 1. List of files 2. Today's date 3. Display the Present month of a Calendar 4. Logged in users 5. Display in current working directory 6. Quit Enter your choice: 1 Areacircumference.sh factorial.sh nodigits.sh reverseno.sh sumsquare.sh Arithcase.sh Fibonacci.sh oddeven.sh sumcube.sh swaptemp.sh

RESULT: Thus the program is written and executed to execute various UNIX commands using case statements.

EX NO: 18 DATE:

SUM OF NUMBERS BETWEEN 50 AND 100

AIM: To write a shell program to execute various UNIX commands using case statements. ALGORITHM: 1. Start the program. 2. Initialize sum=0, b=1, c=1 and i=50. 3. Using while, loop until the number i is greater than 100. 4. Get the remainder value of b and c by dividing it by 3 and 5. ( Using modulos operator) 5. If the value of b is equal to 0 and c is not equal to 0, then find the sum. 6. Add the value of sum to i 7. Increment the value of i by 1, until the condition is satisfied. 8. Display the result by printing the value of sum. 9. Stop the program.

PROGRAM:
sum=0 i=50 b=1 c=1 while [ \$i -le 100 ] do b=`expr \$i % 3` c=`expr \$i % 5` if [ \$b -eq 0 ] && [ \$c -ne 0 ] then sum=`expr \$sum + \$i` fi i=`expr \$i + 1` done echo "The sum of all numbers between 50 and 100 which are divisible by 3 and not divisible by 5 is" \$sum OUTPUT: The sum of all numbers between 50 and 100 which are divisible by 3 and not divisible by 5 is 1050

RESULT: Thus the program is written and executed to find the sum of all numbers between 50 and 100 which are divisible by 3 and not divisible by 5.

EX NO:19 DATE:

GIVEN STRING IS PALINDROME OR NOT

AIM: To write a shell program to check whether the given string is palindrome or not. ALGORITHM: 1. Enter the input. 2. Find the length of the given string. 3. Using while ioop until the length is greater than zero do the following step 4. 4. temp = expr \$11 cut c \$len 5. len is decremented by 1. 6. If the reverse string is equal to input string,print the given string is palindrome else not palindrome.

PROGRAM: rev = len=expr\$1 Iwcc while [ \$len ge 0] do temp=expr\$1 Icutc\$len len = expr \$ len 1 rev = echo \$rev \$temp done if [ \$i = \$rev] then echo The Given string is palindrome else echo Non palindrome fi

OUTPUT: MalayalaM The Given string is palindrome

RESULT: Thus the program is written and executed to check the given string is palindrome or not.

EX.NO:20 DATE:

AIM: To write a shell program to find the grade of a student. ALGORITHM: 1. Start 2. Get the marks of the students and add it. 3. Find the percentage of marks 4. If the percentage is less than 40 display D grade 5. Else if percentage is between 40 and 65, display C grade 6. Else if percentage is between 65 and 75, display B grade 7. Else if percentage is between 75 and 90, display A grade 8. Else display A++ grade PROGRAM: echo "Enter 5 Marks" read m1 m2 m3 m4 m5 total=`expr \$m1 + \$m2 + \$m3 + \$m4 + \$m5` echo "Total Marks = \$total" percent=`expr \$total \* 100 / 500` echo "Percentage of Marks = \$percent" if [ \$percent -lt 40 ] then echo "D Grade" elif [ \$percent -ge 40 -a \$percent -lt 65 ] then echo "C Grade" elif [ \$percent -ge 65 -a \$percent -lt 75 ] then echo "B Grade" elif [ \$percent -ge 75 -a \$percent -lt 90 ] then echo "A Grade" else echo "A++ Grade" fi

OUTPUT: Enter 5 Marks 67 98 89 78 89 Total Marks = 421 Percentage of Marks = 84 A Grade

RESULT: Thus the program is written and executed to find the grade of a student.

EX NO: 21 DATE:

COUNTING NO. OF VOWELS

AIM: To write a shell program to count the number of vowels in a string. ALGORITHM: 1. Start the program. 2. Initialize sum=0, b=1, c=1 and i=50. 3. Using while, loop until the number i is greater than 100. 4. Get the remainder value of b and c by dividing it by 3 and 5. ( Using modulos operator) 5. If the value of b is equal to 0 and c is not equal to 0, then find the sum. 6. Add the value of sum to i 7. Increment the value of i by 1, until the condition is satisfied. 8. Display the result by printing the value of sum. 9. Stop the program.

PROGRAM:
echo Enter String read string len=`expr length \$string` count=0 i=1 while [ \$i -le \$len ] do char=`expr substr \$string \$i 1` if [ \$char = a -o \$char = e -o \$char = i -o \$char = o -o \$char = u ] then count=`expr \$count + 1` fi i=`expr \$i + 1` done echo Vowel Occurence = \$count OUTPUT: abcde Vowel Occurrence = 2

RESULT: Thus the program is written and executed to count the number of vowels in a given string.

EX NO:22 DATE:

SMALLEST NUMBER

AIM: To write a shell program to find the smallest number from given n numbers. ALGORITHM 1.Start the program 2.Get n numbers from the user and store that in to an array. 3.Sort the elements. 4.Print the first array element.(smallest element). 5.Stop the process. PROGRAM: echo "Enter the range:" read n for((i=0;i<n;i++)) do echo "Enter the value for a[\$i]:" read a[\$i] done for((i=0;i<\$n;i++)) do for((j=0;j<`expr \$n - 1`;j++)) do if ((\${a[\$j]}>\${a[`expr \$j + 1`]})) then t=\${a[\$j]} a[\$j]=\${a[`expr \$j + 1`]} a[`expr \$j + 1`]=\$t fi done done echo the smallest element from the given n element is "\${a}" OUTPUT: Enter the range: 5 Enter the value for a: 4 Enter the value for a:3 Enter the value for a:6 Enter the value for a:2 Enter the value for a:8 The smallest element from the given n element is 2 RESULT: Thus the program is written and executed for finding the smallest number from n numbers.

EX NO:23 DATE:

SECOND LARGEST NUMBER

AIM: To write a shell program to find the second largest number from the set of numbers. ALGORITHM: 1. Start the program 2.Get n numbers from the user and store that in to an array. 3.Sort the elements. 4.Print the previous element of the last element(Second largest element). 5.Stop the process. PROGRAM: echo "Enter the range:" read n for((i=0;i<n;i++)) do echo "Enter the value for a[\$i]:" read a[\$i] done for((i=0;i<\$n;i++)) do for((j=0;j<`expr \$n - 1`;j++)) do if ((\${a[\$j]}>\${a[`expr \$j + 1`]})) then t=\${a[\$j]} a[\$j]=\${a[`expr \$j + 1`]} a[`expr \$j + 1`]=\$t fi done done echo sorted array elements for((i=0;i<\$n;i++)) do echo "\${a[\$i]}" done echo the second largest element from the given n element is "\${a[`expr \$n - 2`]}"

OUTPUT: Enter the range: 5 Enter the value for a: 4 Enter the value for a:3 Enter the value for a:6 Enter the value for a:2 Enter the value for a:8 The second largest element from the given n element is: 6

RESULT: Thus the program is written and executed for finding the second largest number from n numbers.

EX.NO:24 DATE:

C PROGRAMMING ASCENDING ORDER

AIM: To write a C program to sort the elements in ascending order. ALGORITHM: 1. Start the program. 2. Declare the variables. 3. Get the elements to be sorted. 4. Using for loop, sort the elements one by one. 5. Print the result. 6. Stop. PROGRAM: #include<stdio.h> #include<malloc.h> main() { int i,j,n,*a,temp; printf("Enter total number of items:"); scanf("%d",&n); a=(int *)malloc(n*sizeof(int)); printf("\nEnter the elements one by one:"); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } for(i=0;i<n;i++) printf("%d\t",a[i]); }

OUTPUT: Enter total number of items: 5 Enter the elements one by one: 22 55 33 44 11 11 22 33 44 55

RESULT: Thus the program was executed and the output was verified.

EX.NO:25 DATE: AIM:

To write a C program to perform matrix addition. ALGORITHM: 1. Start the program. 2. Declare the variables. 3. Get the size of the two matrices. 4. Allocate the variables using malloc. 5. Get the elements of the two matrices. 6. Add the elements and print the result in resultant matrix. 7. Stop. PROGRAM: #include<stdio.h> #include<malloc.h> main() { int **a,**b,**c,i,j,m,n,p,q; printf("Enter the row and column of first matrix:"); scanf("%d%d",&m,&n); printf("Enter the row and column of second matrix:"); scanf("%d%d",&p,&q); if((m==p)&&(n==q)) { printf("Matrix addition is possible:\n"); printf("Enter the values of matrix a\n"); a=(int **)malloc(m*sizeof(int*)); for(i=0;i<n;i++) a[i]=(int *)malloc(n*sizeof(int)); b=(int **)malloc(m*sizeof(int*)); for(i=0;i<n;i++) b[i]=(int *)malloc(n*sizeof(int)); c=(int **)malloc(m*sizeof(int*)); for(i=0;i<m;i++) c[i]=(int *)malloc(n*sizeof(int)); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&a[i][j]); } } printf("Enter the values of matrix b:\n");

for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&b[i][j]); } } for(i=0;i<m;i++) { for(j=0;j<n;j++) { c[i][j]=a[i][j]+b[i][j]; } } printf("the resultant matrix is:\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf("%d\t",c[i][j]); } printf("\n"); } } else printf("Addition is not possible, row and column of both matrix should be same."); } OUTPUT: Enter the row and column of first matrix: 2 2 Enter the row and column of second matrix: 2 2 Matrix addition is possible! Enter the values of matrix a 1 1 1 1 Enter the values of matrix b: 1 1 1 1 the resultant matrix is: 2 2 2 2

RESULT: Thus the program was executed and the output was verified. EX.NO:26 MATRIX MULTIPLICATION DATE: AIM: To write a C program to perform matrix multiplication. ALGORITHM: 1. Start the program. 2. Declare the variables. 3. Get the size of the two matrices. 4. Allocate the variables using malloc. 5. Get the elements of the two matrices. 6. Multiply the elements and print the result in resultant matrix. 7. Stop. PROGRAM: #include<stdio.h> #include<malloc.h> main() { int **a,**b,**c,i,j,k,m,n,p,q; printf("Enter the row and column of first matrix:"); scanf("%d%d",&m,&n); printf("Enter the row and column of second matrix:"); scanf("%d%d",&p,&q); if(n==p) { printf("Matrix multiplication is possible\n"); printf("Enter the values of matrix a\n"); a=(int **)malloc(m*sizeof(int*)); for(i=0;i<n;i++) a[i]=(int *)malloc(n*sizeof(int)); b=(int **)malloc(m*sizeof(int*)); for(i=0;i<n;i++) b[i]=(int *)malloc(q*sizeof(int)); c=(int **)malloc(m*sizeof(int*)); for(i=0;i<n;i++) c[i]=(int *)malloc(q*sizeof(int));

for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&a[i][j]); } } printf("Enter the values of matrix b:\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&b[i][j]); } } for(i=0;i<m;i++) { for(j=0;j<n;j++) { c[i][j]=0; for(k=0;k<n;k++) c[i][j]=a[i][k]*b[k][j]+c[i][j]; } } printf("The resultant matrix is:\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf("%d\t",c[i][j]); } printf("\n"); } } else printf("Multiplication is not possible"); }

OUTPUT: Enter the row and column of first matrix:2 2 Enter the row and column of second matrix:2 2 Matrix multiplication is possible Enter the values of matrix a 1 2 3 4 Enter the values of matrix b: 1 1 1 1 The resultant matrix is: 3 3 7 7

RESULT: Thus the program was executed and the output was verified.

EX.NO:27 DATE:

MEMORY REALLOCATION USING REALLOC

AIM: To write a C program to reallocate memory using realloc function. ALGORITHM: 1.Start the program. 2.Get the string from the user. 3.Allocate memory for the string using malloc function. 4.Then using the realloc function reallocate the memory space. 5.Display the output. 6.Stop the program. PROGRAM: #include<stdio.h> #include<stdlib.h> #include<string.h> main() { char *p; p=(char *)malloc(6); strcpy(p,"MADRAS"); printf("Memory contains %s\n",p); p=(char *)realloc(p,7); strcpy(p,"CHENNAI"); printf("Memory now contains %s\n",p); free(p); } OUTPUT: Memory contains MADRAS Memory now contains CHENNAI

RESULT: Thus the program was executed and the output was verified.

SUM OF N NUMBERS USING FUNCTION

To write a C program to find the sum of n numbers using function. ALGORITHM: 1.Start the program. 2.Read limit n from user. 3.Read n elements from user. 4.Pass the n elements and limit n to function sum. 5.Declare variable sum in function and initialize it to 0. 6.Add each array value to variable sum and store result in sum variable itself. 7.Display the value of sum variable. 8.Stop the program. PROGRAM: #include<stdio.h> void sum(int[ ],int); main() { int a,i,n; printf("Enter the limit:\n"); scanf("%d",&n); printf("Enter the elements:\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); sum(a,n); } void sum(int *a,int n) { int i,sum=0; for(i=0;i<n;i++) sum=sum+a[i]; printf("\nThe Sum of the given numbers is %d",sum); }

OUTPUT: Enter the limit: 4 Enter the elements: 12 23 34 45 The Sum of the given numbers is 114

RESULT: Thus the program was executed and the output was verified.

SUM OF DIGITS USING FUNCTION

To write a C program to find the sum of digits of a number using function. ALGORITHM: 1. Start the program 2. Get number from user. Pass it as argument to function sum. 3. Find out each individual digit by means of modulo and calculate by adding them. 4. Display output. 5. Stop the program. PROGRAM: #include<stdio.h> void sum(int); main() { int no; printf("Enter your number\n"); scanf("%d",&no); sum(no); } void sum(int num) { int a,sum=0; while(num>0) { a=num%10; sum=sum+a; num=num/10; } printf("Sum=%d",sum); } OUTPUT: Enter your number 12345 Sum=15

RESULT: Thus the program was executed and the output was verified.

EX.NO:30 DATE:

REVERSE OF A NUMBER USING FUNCTION

AIM: To write a C program to check whether the given number and its reverse are same using function. ALGORITHM: 1.Start the program 2.Read number from user and pass it to function reverse. 3.In the function,separate each individual digit and reverse it. 4.Check if the original and reversed number are same. 5.Stop the program. PROGRAM: #include<stdio.h> void reverse(int); main() { int no; printf("Enter the Number:\n"); scanf("%d",&no); reverse(no); } void reverse(int num) { int n,digit,rev=0; n=num; while(num>0) { digit=num%10; rev=rev*10+digit; num=num/10; } if(n==rev) printf("The given number %d and its reverse are same",n); else printf("The given number %d and its reverse are not same",n); }

OUTPUT: Enter the Number: 12321 The given number 12321 and its reverse are same Enter the Number: 12345 The given number 12345 and its reverse are not same

RESULT: Thus the program was executed and the output was verified.

EX.NO:31 DATE:

SWAPPING OF TWO NUMBERS

AIM: To write a C program using pointers to swap two numbers ALGORITHM: 1. Start the program. 2. Read numbers from user. 3. Assign the address of numbers to two pointers respectively. 4. Swap them by using a temporary pointer t. 5. Display swapped output. 6. Stop the program. PROGRAM: #include<stdio.h> main() { int a,b,*x,*y,t; x=&a; y=&b; printf("Enter the values for a and b:\n"); scanf("%d%d",&a,&b); printf("\nBefore swapping\n"); printf("The value of a is %d\n",*x); printf("The value of b is %d\n",*y); t=*x; *x=*y; *y=t; printf("\nAfter swapping\n"); printf("The value of a is %d\n",*x); printf("The value of b is %d\n",*y); }

OUTPUT: Enter the values for a and b: 4 5 Before swapping The value of a is 4 The value of b is 5 After swapping The value of a is 5 The value of b is 4

RESULT: Thus the program was executed and the output was verified.

FILE COPY OPERATION

To write a C program for performing file copy operation. 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> main() { char ch; FILE *fp1,*fp2; fp1=fopen("one.txt","r"); fp2=fopen("two.txt","w+"); printf("The contents of one.txt file is\n"); while((ch=getc(fp1))!=EOF) { putc(ch,fp2); printf("%c",ch); } printf("\n"); printf("the file one.txt is copied into the file two.txt\n"); printf("the contents of two.txt file is \n\n"); fseek(fp2,0L,0); while((ch=getc(fp2))!=EOF) { printf("%c",ch); } fclose(fp1); fclose(fp2); }

OUTPUT: The contents of one.txt file is hai how are you

the file one.txt is copied into the file two.txt the contents of two.txt file is hai how are you

RESULT: Thus the program was executed and the output was verified.

EX NO: 33 DATE:

LINEAR SEARCH

AIM: To write a C program using Dynamic Memory Allocation to perform linear search. ALGORITHM: 1.Start the program. 2.Read total number of items from user. 3.Read elements from user and allocate memory to them dynamically. 4.Read the element to be searched. 5.Perform linear search on elements. Check whether all elements in array is equal to element to be searched.If found ,display element and its location 6.Stop the program. PROGRAM: #include<stdio.h> #include<malloc.h> #include<stdlib.h> main() { int i,j,n,*a,temp,x; printf("Enter total number of items:"); scanf("%d",&n); a=(int *)malloc(n*sizeof(int)); printf("\nEnter the elements one by one:\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nEnter the value to be searched:"); scanf("%d",&x); for(i=0;i<n;i++) { if(x==a[i]) { printf("\n%d is located at location %d",x,i+1); exit(0); } } printf("\n the given number is not found"); }

OUTPUT Enter total number of items: 5 Enter the elements one by one: 5 8 9 3 4 Enter the value to be searched: 8 8 is located at location 2
{"ft_lang_label":"__label__en","ft_lang_prob":0.73670894,"math_prob":0.8967463,"size":46031,"snap":"2019-26-2019-30","text_gpt3_token_len":12382,"char_repetition_ratio":0.15975405,"word_repetition_ratio":0.20606579,"special_character_ratio":0.2834177,"punctuation_ratio":0.14248149,"nsfw_num_words":2,"has_unicode_error":false,"math_prob_llama3":0.98763126,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-06-25T13:29:59Z\",\"WARC-Record-ID\":\"<urn:uuid:34fa69d3-5c45-4965-9d71-d5337a511102>\",\"Content-Length\":\"317607\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:3415abf3-26ef-4d2b-8659-cc62021850a7>\",\"WARC-Concurrent-To\":\"<urn:uuid:46ddca61-75ad-4012-ac60-128175fc51da>\",\"WARC-IP-Address\":\"151.101.250.152\",\"WARC-Target-URI\":\"https://ja.scribd.com/document/201870823/Computer-Practices-II-Laboratory-Manual\",\"WARC-Payload-Digest\":\"sha1:XJYZQNFU4BC3XXQLVQRVHBPNTOP7U3PE\",\"WARC-Block-Digest\":\"sha1:TNYFR7WXWWXZJZX52WC7WMV373V7FXWK\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-26/CC-MAIN-2019-26_segments_1560627999838.27_warc_CC-MAIN-20190625132645-20190625154645-00382.warc.gz\"}"}