computer practices ii - laboratory manual

83
GE2155 COMPUTER PRACTICE LABORATORY – II 0 1 2 2 LIST OF EXPERIMENTS 1. UNIX COMMANDS 15 Study of Unix OS - Basic Shell Commands - Unix Editor 2. SHELL PROGRAMMING 15 Simple Shell program - Conditional Statements - Testing and Loops 3. C PROGRAMMING ON UNIX 15 Dynamic Storage Allocation-Pointers-Functions-File Handling 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

Upload: kalpanasripathi

Post on 31-Dec-2015

35 views

Category:

Documents


4 download

DESCRIPTION

I YEAR - II SEM - EEE

TRANSCRIPT

Page 1: Computer Practices II - Laboratory Manual

GE2155 COMPUTER PRACTICE LABORATORY – II 0 1 2 2

LIST OF EXPERIMENTS

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

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

Page 2: Computer Practices II - Laboratory Manual

LIST OF EXPERIMENTSEX.N

O TITLE PAGE NO.

1.UNIX COMMANDS

Study Of Unix Operating System1

2. Basic Shell Commands 3

3. Unix Editor 5

4.SHELL PROGRAMMING

Odd Or Even11

5. Largest Among Two Numbers 12

6. Largest Among Three Numbers 13

7. Leap Year 14

8. Area And Circumference Of A Circle 15

9. Armstrong Number 16

10. Interchanging Two Numbers 17

11. Prime Number 19

12. Fibonacci Series 21

13. Factorial Of A Number 22

14. Sum Of Digits 23

15. Sum Of Square Of Individual Digits 24

16. Unix Commands Using Case Statements 25

17. Sum Of Numbers Between 50 And 100 27

18. Palindrome - String 28

19. Student Details 29

20. Counting No. Of Vowels In A String 30

21. Palindrome – Number 31

22. Smallest Number 32

23. Second Largest Number 33

24.C PROGRAMMING

Ascending Order 34

25. Matrix Addition 35

26. Matrix Multiplication 37

27. Memory Reallocation Using Realloc 39

28. Sum Of ‘N’ Numbers Using Function 40

29. Sum Of Digits Using Function 41

30. Reverse Of A Number Using Function 42

31. Swapping Of Two Numbers Using Pointers 43

32. File Copy Operation 44

33. Linear Search 45

Page 3: Computer Practices II - Laboratory Manual

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.

Page 4: Computer Practices II - Laboratory Manual

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 SYSTEMThe unix Operating System have three Parts They are1.Kernal2.Shell3.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:

Page 5: Computer Practices II - Laboratory Manual

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 themain 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

Page 6: Computer Practices II - Laboratory Manual

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

Page 7: Computer Practices II - Laboratory Manual

Ex no:2Date: BASIC UNIX COMMANDSAim: To study about unix commandsCommands:

1. Cat The cat command is used to create a file Syntax : cat > filenameExample : cat>testHelloCtrl+d ( to save & exit from the file creation )

Used to concatenate the file1,file2 content and stored in file3Used to concatenate the file1 at the end of file2Syntax : cat file1 file2>file3cat file1>>file2Example : 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 nameExample : pwd mkdir cplab

3. Cd To move from one directory another directorySyntax: cd directory nameExample : cd cplab

pwd4. Cd ..

To exit from the single directory or leave form the directorySyntax : cd ..Example : cd ..

5. Rmdir To remove directory from diskWhile the directory should be empty & you are exit from the directorySyntax: rmdir directory nameExample: rmdir cplab

6. Clear To clear the screenSyntax: clearExample: clear

Page 8: Computer Practices II - Laboratory Manual

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 fileR used to copy the entire directorySyntax: cp -opt oldfilname duplicate filenameExample: cp -i

test copyoftest cat copyoftest8. Rm

It is used to dele the file or remove the fileThe opt may bei 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 filenameExample: rm copyoftest –ir

9. Wc Used to count the no of line ,word and character in a specified fileopt may bec – no of char only in a filew - no of words only in a filel – no of lines only in a fileSyntax: wc -opt filenameExample: wc list wc list -l

wc list -w10. Head

It displays the first ten lines of a fileOpt may be Integer no to display number of lines to display in screenSyntax: head -opt filenameExample: head list

head -15 list11. Tail

It displays the last ten lines of a fileOpt may be Integer no to display number of lines to display in screenSyntax: tail -opt filenameExample: tail list

tail -15 list12. 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

Page 9: Computer Practices II - Laboratory Manual

+%y - to display last two digit of the year+%H - to display Hours+%M - to display Minutes+%S - to display SecondsSyntax: date optExample: date

13. Echo To display the message in screen given in the echo commandSyntax: echo messageExample: Echo “Hai”

14. Cal To display the calendar of particular year or monthOpt may beYear like cal 2004Month and Year Like cal 2 2004Syntax: cal optExample: 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 loginSyntax: who am iExample: who am i

16. Who

Used to display a data about users who are currently logged into the systemSyntax: who

17. Finger Finger command display the user detailsSyntax: finger usernameExample: finger temp

18. ID Used to display the numerical value that corresponding to your login name, user id and group idSyntax: idExample: id

19. Tty Used to know the terminal name that we are usingSyntax: ttyExample: tty

20. Passwd The account password can be changed using passwdSyntax: passwdExample: passwd

21. The semicolon ; It is used to execute more then one command in single command line

Page 10: Computer Practices II - Laboratory Manual

Syntax: command1;command2;etcExample: 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 executedSyntax: command1&&command2Example: 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 excutedSyntax: command1||command2Example: ls || date cat gg || date

24. Pwd Used to print the current working directorySyntax: pwdExample: pwd

25. Mv It is used to rename the file and directory also to move file from one location to another locationSyntax: Mv oldfilename newfilenameExample: mv test3 sample

mv sample /home/cplab/test326. Ls

To display the files & directories in present directory or specified directoryopt may bex - display multi column outputt – List files & sub directories with time orderr – List the files & sub directories is reverse orderA – List all files & sub Dir except (. ..)a - List all files c - List files by inode modification timeI - List the inode for each fileh - List names of hidden files alsoq - List the file name having non printable charactersl - List in long formation ( Permission , owner , size, modification, time with file or directory name )Syntax: ls -opt or

ls -opt dir_nameExample: ls -l

ls –r ls r*

Page 11: Computer Practices II - Laboratory Manual

ls ?a* ls [a]* ls [a-m]* ls –l | pg ls -l /usr/bin

27. File To show file typeSyntax: file filenameExample: file list

28. Chmod

To set file permission for filesCategory may be u –userg – groupo – otherspermission may be (+or-) rwxTo set the file permissionFor filed1 for userd2 for groupd3 for othersOctal value for4 – read2 – write

1 – executeSyntax: chmod category permission file name

chmod d1d2d3 (octal value) filenameExample: 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 calculatorSyntax: bcExample : bc

30. Grep To search the specified pattern from a file & displays the lines of the file that contains the pattern Syntax: grep pattern filenameExample: grep Hello test

31. Sort

Page 12: Computer Practices II - Laboratory Manual

To sort the file content & display the result only in screen no change in the file contentOpt may ber – reverse orderc – checks if the file is sortedn – Sorts numericallyu – removes duplicate recordsm list – merges sorted files in listSyntax: sort -opt filename

sort -opt filename>filename to store sorted informationExample: 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 filenameExample: 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 thereSyntax: cmp file name1 file name2Example: 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 file12nd column represent the lines common only to file2 3rd column represent the lines common to file1 and file2Syntax: comm Filename1 filename2Example: 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 filesSyntax: diff file name1 file name2Example: diff test test1

Message and mail command36. Mesg

It used to grant the permission to user for send and receive the message to or from user mesg y means y have permissionmesg n means you denied the permission Syntax: mesg y or mesg nExample: 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

Page 13: Computer Practices II - Laboratory Manual

Example: write temp hello ctrl+d

38. Wall It is used to broadcast message to all users presently login into the systemIf 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 messageExample: wall

Hello hai Ctrl+d

39. News The news command permits to user to read message published by the system administratorSyntax: newsExample: 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 taskSyntax: mail opt user nameExample: mail –s mail test

Here I am going to check mail command Ctrl+d

It used to read the message was sent by the usersSyntax: mailExample: mail

41. Reply It is used to reply the message to userSyntax: reply usernameExample: 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 PATHSyntax: echo PATHExample: echo PATH

Result:Thus the basic unix commands were studied.

Page 14: Computer Practices II - Laboratory Manual

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 and Saving Files

 Starting vi:

vi filename Start editing filename, create it if necessary

Saving the file you're working on and/or leaving vi:

:wq write the file to disk and quit

:q! Quit without saving any changes

Page 15: Computer Practices II - Laboratory Manual

Moving the Cursor

Many commands take number prefixes; for example 5w moves to the right by 5 words.    

Type: To Move To:

H one space to the left (also try left arrow)

J one line down (also try down arrow)

K one line up (also try up arrow)

L one space to the right (also try right arrow)

$ end of current line

^ beginning of current line

Enter beginning first word on the next line

G end of file

:n line n; use :0 to move the beginning of the file

w beginning of next word; 5w moves to the beginning of the 5th word to the right

E end of next word

B beginning of previous word

Ctrl-b one page up

Searching for Text

Type: To:

/string search down for string

?string search up for string

N repeat last search from present position 

Page 16: Computer Practices II - Laboratory Manual

Inserting Text

Type:  To: 

a  append starting right of cursor 

A  append at the end of the current line 

i  insert starting left of cursor 

I  insert at beginning of the current line 

o  open line below cursor, then enter insert mode 

O  open line above cursor, then enter insert mode 

:r newfile  add the contents of the file newfile starting below the current line 

Deleting Text

Type: To:

X Delete single character; 5x deletes 5 characters

Dw Delete word; 5dw deletes 5 words

Dd Delete line; 5dd deletes ... well you get the idea!

Cw Delete word, leaves you in insert mode (i.e. change word)

Cc change line -- delete line and start insert mode

S change character -- delete character and start insert mode

D Delete from cursor to end of line

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

U undo last change

Page 17: Computer Practices II - Laboratory Manual

Cutting and Pasting

Type: To:

Xp transpose two characters (two commands, x followed by p)

Yy yank (i.e. copy) one line into a general buffer (5yy to yank 5 lines)

"ayy yank into the buffer named a

P put the general buffer back before the current line

"aP put from buffer a before current line

P put the general buffer back after the current line

"ap put from buffer a after the current line 

Miscellaneous Commands

Type: To:

Ctrl-g show line number of current line

Conditional and looping statements1. 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. If…else…if:If given condition is true then command1 is executed otherwise command2 is executed.

Syntax:

Page 18: Computer Practices II - Laboratory Manual

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 conditionthen …. Do thiselse …. Do thisfi

4. Multilevel if-then-else:

Syntax: If condition Then Condition is zero (true – 0) Execute all commands up to elif statementElif condition1Then Condition1 is zero (true -0 ) Execute all commands up to elif statementElif condition2 Then Condition2 is zero (true-0) Execute all commands up to elif statementElse None of the above condition,condition1,condition2 are true(i.e all of the above non-zero or false) Execute all commands upto fiFi

Page 19: Computer Practices II - Laboratory Manual

5.for loop:Syntax:For{variable name} in {list}DoExecute 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 loopAs 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++)) ###outer for loop### do

for ((j=1;j<=5;j++)) ###inner for loop### doecho –n “$i”done

Echo “”####print the new line###

Done

7. While loopSyntax: While [condition] Do command1 command2 command3

.. …. Done

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

Page 20: Computer Practices II - Laboratory Manual

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.

Page 21: Computer Practices II - Laboratory Manual

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 .5Date:

CHECK POSITIVE OR NEGATIVE NUMBER

Page 22: Computer Practices II - Laboratory Manual

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 LEAP YEAR DATE:

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.

Page 23: Computer Practices II - Laboratory Manual

3. Get the remainder by dividing the number by 4 (use % operator). 4. Check if remainder is zero then given year is leap otherwise it’s not a leap year.

5. Stop the program

PROGRAM:echo "Enter the year"read yb=`expr $y % 4`if [ $b -eq 0 ]thenecho "$y is a leap year"elseecho "$y is not a leap year"fi

OUTPUT:Enter the year20002000 is a leap year

Enter the year20102010 is not a leap year

RESULT:Thus the program is written and executed successfully.

EX NO: 7 AREA AND CIRCUMFERENCE OF A CIRCLEDATE:

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.

Page 24: Computer Practices II - Laboratory Manual

3. Calculate area and circumference using the formulae. 4. Display the result.

5. Stop the program

PROGRAM:echo "Enter the radius"read rarea=`expr "3.14 * $r * $r" | bc`cir=`expr "2 * 3.14 * $r" | bc`echo "The area is " $areaecho "The circumference is " $cir

OUTPUT:Enter the radius3The area is  28.26The circumference is  18.84

RESULT:Thus the program is written and executed successfully.

EX NO: 8 LARGEST AMONG THREE NUMBERSDATE:

AIM: To write a shell program to find the largest among three numbers.

ALGORITHM:

Page 25: Computer Practices II - Laboratory Manual

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 cif [ $a -gt $b -a $a -gt $c ]thenecho "$a is Greater"elif [ $b -gt $c ]thenecho "$b is Greater"elseecho "$c is Greater"fi

OUTPUT:Enter Three Numbers22 55 3355 is Greater

RESULT:Thus the program is written and executed to find the largest among three numbers.EX NO: 9 INTERCHANGING TWO NUMBERS DATE:

AIM: To write a shell program to interchange two numbers using a temporary variable and without using a temporary variable.

Page 26: Computer Practices II - Laboratory Manual

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

Page 27: Computer Practices II - Laboratory Manual

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 PALINDROME OR NOTDATE:

AIM: To write a shell program to find a given number is palindrome or not.

Page 28: Computer Practices II - Laboratory Manual

ALGORITHM1. 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%10c=s*10+bn=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 ad=$ac=0b=1while [ $a -gt 0 ]dob=`expr $a % 10`c=`expr $c \* 10 + $b`a=`expr $a / 10`doneif [ $d -eq $c ]thenecho "PALINDROME"elseecho "NOT PALINDROME"fi

OUTPUT: Enter a number12321PALINDROME

Page 29: Computer Practices II - Laboratory Manual

Enter a number12345NOT PALINDROME

RESULT: Thus the program is written and executed for checking a number is palindrome or not. EX. NO: 11 ARMSTRONG NUMBERDATE:

AIM:

Page 30: Computer Practices II - Laboratory Manual

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 numx=$numsum=0while [ $num -gt 0 ]doy=`expr $num % 10`z=`expr $y \* $y \* $y`sum=`expr $sum + $z`num=`expr $num / 10`doneif [ $x -eq $sum ]thenecho "$x is an armstrong Number"elseecho "$x is not an armstrong Number"fi

OUTPUT: Enter a Number123123 is not an armstrong Number

Page 31: Computer Practices II - Laboratory Manual

Enter a Number153153 is an armstrong Number

RESULT: Thus the program is written and executed to find the Armstrong number. EX NO: 12 PRIME NUMBERDATE:

AIM:

Page 32: Computer Practices II - Laboratory Manual

To write a shell program to find a given number is prime number or not.

ALGORITHM1. 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%10c=s*10+bn=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 ni=`expr $n - 1`t=0while [ $i -ge 2 ]dop=`expr $n % $i`if [ $p -eq 0 ]thent=`expr $t + 1`fii=`expr $i - 1`doneif [ $t -gt 0 ]thenecho "The Number $n is not a Prime Number"elseecho "The Number $n is a Prime Number"fi

OUTPUT:Enter a Number7

Page 33: Computer Practices II - Laboratory Manual

The Number 7 is a Prime Number

Enter a Number12The 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 FIBONACCI SERIESDATE:

Page 34: Computer Practices II - Laboratory Manual

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 ni=2echo "Fibonacci Series"echo "--------------------"a=0b=1echo $aecho $bwhile [ $i -lt $n ]doc=`expr $a + $b`echo $ca=$bb=$ci=`expr $i + 1`done

OUTPUT:Enter the Limit3

Page 35: Computer Practices II - Laboratory Manual

Fibonacci Series----------------011

RESULT: Thus the program is written and executed to generate Fibonacci series. EX.NO: 14 FACTORIAL OF A GIVEN NUMBER DATE:

Page 36: Computer Practices II - Laboratory Manual

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 ni=`expr $n - 1`p=1while [ $i -ge 1 ]don=`expr $n \* $i`i=`expr $i - 1`doneecho "The Factorial of the given Number is $n"

OUTPUT: Enter a Number6The 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 SUM OF DIGITSDATE:

Page 37: Computer Practices II - Laboratory Manual

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=04. Using while, loop until the number is greater than 0. y=num%10 sum =sum + y num =num/105. Display the result by printing the value of sum.6. Stop the program.

PROGRAM:echo "Enter a Number"read numsum=0while [ $num -gt 0 ]do            y=`expr $num % 10`sum=`expr $sum + $y`num=`expr $num / 10`doneecho "The Sum of the Digits of the Integer is $sum"

OUTPUT:Enter a Number12345The 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 SUM OF SQUARES OF INDIVIDUAL DIGITSDATE:

Page 38: Computer Practices II - Laboratory Manual

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%10c=c + b*ba=a/10

5. Display the result by printing the value of c.6. Stop the program

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

OUTPUT:enter the number234The 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 UNIX COMMANDS USING CASE STATEMENTSDATE:

Page 39: Computer Practices II - Laboratory Manual

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:           MENU1. List of files

Page 40: Computer Practices II - Laboratory Manual

2. Today's date3. Display the Present month of a Calendar4. Logged in users5. Display in current working directory6. Quit

Enter your choice: 1Areacircumference.sh  factorial.sh  nodigits.sh      reverseno.sh  sumsquare.shArithcase.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 SUM OF NUMBERS BETWEEN 50 AND 100DATE:

Page 41: Computer Practices II - Laboratory Manual

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 i7. 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=0i=50b=1c=1while [ $i -le 100 ]dob=`expr $i % 3`c=`expr $i % 5`if [ $b -eq 0 ] && [ $c -ne 0 ]thensum=`expr $sum + $i`fii=`expr $i + 1`doneecho "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 GIVEN STRING IS PALINDROME OR NOT DATE:

Page 42: Computer Practices II - Laboratory Manual

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 $len5. 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 Iwc—c

while [ $len — ge 0] do

temp=’expr$1 Icut—c$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 STUDENTS GRADEDATE:

Page 43: Computer Practices II - Laboratory Manual

AIM: To write a shell program to find the grade of a student.

ALGORITHM:1. Start2. Get the marks of the students and add it.3. Find the percentage of marks4. 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 m5total=`expr $m1 + $m2 + $m3 + $m4 + $m5`echo "Total Marks = $total"percent=`expr $total \* 100 / 500`echo "Percentage of Marks = $percent"if [ $percent -lt 40 ]thenecho "D Grade"elif [ $percent -ge 40 -a $percent -lt 65 ]thenecho "C Grade"elif [ $percent -ge 65 -a $percent -lt 75 ]thenecho "B Grade"elif [ $percent -ge 75 -a $percent -lt 90 ]thenecho "A Grade"elseecho "A++ Grade"fi

OUTPUT:Enter 5 Marks67 98 89 78 89

Page 44: Computer Practices II - Laboratory Manual

Total Marks = 421Percentage of Marks = 84A Grade

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

EX NO: 21 COUNTING NO. OF VOWELSDATE:

Page 45: Computer Practices II - Laboratory Manual

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 i7. 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 Stringread stringlen=`expr length $string`count=0i=1while [ $i -le $len ]dochar=`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`fii=`expr $i + 1`doneecho Vowel Occurence = $count

OUTPUT:abcdeVowel Occurrence = 2

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

EX NO:22 SMALLEST NUMBERDATE:

Page 46: Computer Practices II - Laboratory Manual

AIM: To write a shell program to find the smallest number from given ‘n’ numbers.

ALGORITHM1.Start the program2.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 nfor((i=0;i<n;i++))doecho "Enter the value for a[$i]:"read a[$i]donefor((i=0;i<$n;i++))dofor((j=0;j<`expr $n - 1`;j++))doif ((${a[$j]}>${a[`expr $j + 1`]}))thent=${a[$j]}a[$j]=${a[`expr $j + 1`]}a[`expr $j + 1`]=$tfidonedoneecho the smallest element from the given n element is "${a[0]}"

OUTPUT:Enter the range: 5Enter the value for a[0]: 4Enter the value for a[1]:3Enter the value for a[2]:6Enter the value for a[3]:2Enter the value for a[4]:8The 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 SECOND LARGEST NUMBERDATE:

Page 47: Computer Practices II - Laboratory Manual

AIM: To write a shell program to find the second largest number from the set of numbers.

ALGORITHM:1. Start the program2.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 nfor((i=0;i<n;i++))doecho "Enter the value for a[$i]:"read a[$i]donefor((i=0;i<$n;i++))dofor((j=0;j<`expr $n - 1`;j++))doif ((${a[$j]}>${a[`expr $j + 1`]}))thent=${a[$j]}a[$j]=${a[`expr $j + 1`]}a[`expr $j + 1`]=$tfidonedoneecho sorted array elementsfor((i=0;i<$n;i++))doecho "${a[$i]}"doneecho the second largest element from the given n element is "${a[`expr $n - 2`]}"

OUTPUT:Enter the range: 5Enter the value for a[0]: 4

Page 48: Computer Practices II - Laboratory Manual

Enter the value for a[1]:3Enter the value for a[2]:6Enter the value for a[3]:2Enter the value for a[4]:8The 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 C PROGRAMMINGDATE:

ASCENDING ORDER

Page 49: Computer Practices II - Laboratory Manual

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: 5Enter the elements one by one: 22 55 33 44 11

Page 50: Computer Practices II - Laboratory Manual

11      22      33      44      55     

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

EX.NO:25 MATRIX ADDITIONDATE:

Page 51: Computer Practices II - Laboratory Manual

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++)

Page 52: Computer Practices II - Laboratory Manual

{ 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

Page 53: Computer Practices II - Laboratory Manual

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

EX.NO:26 MATRIX MULTIPLICATIONDATE:

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++)

Page 54: Computer Practices II - Laboratory Manual

{ 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

Page 55: Computer Practices II - Laboratory Manual

Enter the row and column of second matrix:2 2 Matrix multiplication is possibleEnter 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 MEMORY REALLOCATION USING REALLOCDATE:

Page 56: Computer Practices II - Laboratory Manual

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 MADRASMemory now contains CHENNAI

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

EX.NO:28 SUM OF ‘N’ NUMBERS USING FUNCTIONDATE:

Page 57: Computer Practices II - Laboratory Manual

AIM: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[20],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

Page 58: Computer Practices II - Laboratory Manual

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.

EX.NO:29 SUM OF DIGITS USING FUNCTIONDATE:

Page 59: Computer Practices II - Laboratory Manual

AIM:To write a C program to find the sum of digits of a number using function.

ALGORITHM:1. Start the program2. 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 REVERSE OF A NUMBER USING FUNCTIONDATE:

Page 60: Computer Practices II - Laboratory Manual

AIM: To write a C program to check whether the given number and its reverse are same using function.

ALGORITHM:1.Start the program2.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

Page 61: Computer Practices II - Laboratory Manual

The given number 12321 and its reverse are sameEnter 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 SWAPPING OF TWO NUMBERSDATE:

Page 62: Computer Practices II - Laboratory Manual

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

Page 63: Computer Practices II - Laboratory Manual

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.

EX.NO:32 FILE COPY OPERATIONDATE:

Page 64: Computer Practices II - Laboratory Manual

AIM: 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

Page 65: Computer Practices II - Laboratory Manual

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 LINEAR SEARCH DATE:

Page 66: Computer Practices II - Laboratory Manual

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 location6.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");}

OUTPUTEnter total number of items: 5

Page 67: Computer Practices II - Laboratory Manual

Enter the elements one by one:58934

Enter the value to be searched: 8

8 is located at location 2

RESULT: Thus c program is written and executed to to perform linear search.