cp lab manual

55
EASWARI ENGINEERING COLLEGE RAMAPURAM, CHENNAI-89 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING LAB MANUAL 185253 COMPUTER PRACTICE LABORATORY II Prepared By Approved by Ms.S.PONMANI HOD/CSE Ms.K.AKILA Ms.V.SUDHA Mr.N.DURAIMURUGAN Mr.N.BHARATHIRAJA

Upload: nano6174

Post on 24-Oct-2014

145 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Cp Lab Manual

EASWARI ENGINEERING COLLEGE

RAMAPURAM, CHENNAI-89

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

185253 COMPUTER PRACTICE LABORATORY II

Prepared By Approved by

Ms.S.PONMANI HOD/CSEMs.K.AKILA Ms.V.SUDHAMr.N.DURAIMURUGANMr.N.BHARATHIRAJA

Page 2: Cp Lab Manual

185253 COMPUTER PRACTICE LABORATORY – II L T P C 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

1

Page 3: Cp Lab Manual

LIST OF EXPERIMENTS

I UNIX COMMANDS

1. Study of UNIX OS

2. Basic Shell Commands

3. Unix Editor

II SHELL PROGRAMMING

1. Greatest among three numbers

2. Factorial of a given number

3. Sum of Odd numbers upto n

4. Generation of Fibonacci numbers

5. Implement the Arithmetic calculator

6. Converting temperature in Fahrenheit to Degree Centigrade.

7. Check whether given string is a palindrome or not

8. Check whether the given year is leap year or not

9. The largest digit of a number

10. Sum of ‘n’ different numbers

11. sum of digits of a number

12. Generate prime numbers between 1 and 50

13. Area and circumference of a circle

14. Check the given number and its reverse are same

15. Sum of odd and even numbers from a set of numbers

2

Page 4: Cp Lab Manual

C Programming on UNIX

1. Program to reallocate the string using dynamic memeory allocation

2. Program to interchange the values stored in 2 variables using function with pointers.

3. Program to create a file and display its content

4. Program to perform file copy operation

5. Program to create two files and perform merge operation on it

6. Program to find the sum of ‘n’ numbers using function.

7. Program using dynamic memory allocation to develop salary details of 5 employees.

8. Program using dynamic memory allocation to find the sum of elements of a matrix.

9. Program to print addition, subtraction and multiplication values using functions.

10.Program to perform file manipulation like copying file, changing the case of the entire file and to count the number of words, spaces and lines in a file..

3

Page 5: Cp Lab Manual

STUDY OF UNIX OPERATING SYSTEM

UNIX Introduction

What is UNIX? UNIX is an operating system which was first developed in the 1960s, and has been under constant development ever since. By operating system, we mean the suite of programs which make the computer work. It is a stable, multi-user, multi-tasking system for servers, desktops and laptops.

UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows which provides an easy to use environment. However, knowledge of UNIX is required for operations which aren't covered by a graphical program, or for when there is no windows interface available, for example, in a telnet session

Types of UNIX

There are many different versions of UNIX, although they share common similarities. The most popular varieties of UNIX are Sun Solaris, GNU/Linux, and MacOS X.

Here in the School, we use Solaris on our servers and workstations, and Fedora Linux on the servers and desktop PCs.

The UNIX operating system

The UNIX operating system is made up of three parts; the kernel, the shell and the programs.

The kernel

The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs and handles the filestore and communications in response to system calls.

As an illustration of the way that the shell and the kernel work together, suppose a user types rm myfile (which has the effect of removing the file myfile).

4

Page 6: Cp Lab Manual

The shell searches the filestore for the file containing the program rm, and then requests the kernel, through system calls, to execute the program rm on myfile. When the process rm myfile has finished running, the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further commands.

The shell

The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The shell is a command line interpreter (CLI). It interprets the commands the user types in and arranges for them to be carried out. The commands are themselves programs: when they terminate, the shell gives the user another prompt (% on our systems).

The adept user can customise his/her own shell, and users can use different shells on the same machine. Staff and students in the school have the tcsh shell by default.

The tcsh shell has certain features to help the user inputting commands.

Filename Completion - By typing part of the name of a command, filename or directory and pressing the [Tab] key, the tch shell will complete the rest of the name automatically. If the shell finds more than one name beginning with those letters you have typed, it will beep, prompting you to type a few more letters before pressing the tab key again.

History - The shell keeps a list of the commands you have typed in. If you need to repeat a command, use the cursor keys to scroll up and down the list or type history for a list of previous commands.

Files and processes

Everything in UNIX is either a file or a process. A process is an executing program identified by a unique PID (process identifier). A file is a collection of data. They are created by users using text editors, running compilers etc.

5

Page 7: Cp Lab Manual

Examples of files:

a document (report, essay etc.) the text of a program written in some high-level programming language instructions comprehensible directly to the machine and incomprehensible

to a casual user, for example, a collection of binary digits (an executable or binary file);

a directory, containing information about its contents, which may be a mixture of other directories (subdirectories) and ordinary files.

The Directory Structure

All the files are grouped together in the directory structure. The file-system is arranged in a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root (written as a slash / )

In the diagram above, we see that the home directory of the dergraduate student "ee51vn" contains two sub-directories (docs and pics) and a file called report.doc. The full path to the file report.doc is "/home/its/ug1/ee51vn/report.doc"

6

Page 8: Cp Lab Manual

Starting an UNIX terminal

To open an UNIX terminal window, click on the "Terminal" icon from the drop-down menus

UNIX - Basic Commands

The basic form of any UNIX command is:command_name options argument(s) Unix is case-sensitive. Unix distinguishes between upper and lower case letters in the names of

files and programs. Thus, while ls is a valid Unix command, LS is not. Login names and passwords are also case-sensitive. A filename in Unix can consist of any combination of characters on the

keyboard except for the space bar and all of the following : * ? ! \ \ ‘ “ > ;, ^ ( ) $ ~. These characters cannot be used in filenames because they have special meaning to the shell. For instance, the first two characters are used as “wildcards”.

7

Page 9: Cp Lab Manual

Directory Related Commands:

S.No Command Description1. pwd Print working directory2. mkdir Create an empty directory in the disk3. rmdir Remove a directory from the disk.

(Directory must be empty)4. cd Change current working directory

pwd1.Syntax:$ pwd

Output: /root/user1where user1 refers to the present working directory

mkdir2.Syntax: $ mkdir dirname Example: $ mkdir asha This creates a directory with name asha

rmdir3.Syntax:$ rmdir dirname Example:$ rmdir asha This deletes the directory named ashacd4.Syntax:$ cd dirname Example:$ cd uma Changes from current directory to directory uma

File Related Commands

S.No Command Description1. cat To create a new file on the system and to

display the contents of a file.2. cp To copy the contents of a file.3. rm To remove a file4. mv To rename a file5. ls To list files and directories6. ln To make a link or to create aliases7. wc To count the total number of lines,words

and characters of a given file.

8

Page 10: Cp Lab Manual

8. find Locates the files both in the directories and subdirectories by performing recursive searches.

9. file To get the type of the file.10. chmod To set the access permission for

Owner,Group and Others.11. nl Adding line numbers to a file.12. more To display the contents of a file one screen

at a time13. less To display the contents of a file one screen

at a time14. pg To display the contents of a file one page

at a time15. spell To fine spelling errors in a file and to

display them on the standard output in alphabetical order

Cat

1 .Syntax:$ cat options filename

To create a file Syntax: $ cat > filename

Example: $ cat > file1Creates a file named file1

To display the contentsSyntax: $ cat filenameExample: $ cat file1

Display the contents of file1

To append contents to a fileSyntax: $ cat >> filenameExample: $ cat >> file1

Append the contents to file1

Option : -n Number the lines of the file including blank lines

9

Page 11: Cp Lab Manual

Cp

2.Syntax:$ cp sourcefile destinationfile Example: $ cp file1 file2 Copies the contents of file1 to file2

rm3. Syntax:$ rm filename Example: $ rm file1

Deletes file1

mv4. Syntax:$ mv sourcefile destinationfile Example: $ mv file2 file3

Contents of file2 are moved to file3.(Nothing but renaming file2 as file3.file2 no longer exists)

ls5.Syntax:$ ls -options

ls -l list the files in long format ls -t list the files in the order of last modification time ls –a list all files including hidden files ls –c list all files column-wise ls –d list the directory rather than its contents ls –m list all files separated by columns

ln6.Syntax:$ ln options filename1 filename2 Example:$ ln file1 file2

file1 will have two names as file1 & file2 but with a single copy of contents

wc7.Syntax:$ wc option(s) file(s) wc –c counts the number of characters in the file wc –w counts the number of words in the file wc –l counts the number of lines in the file

find8.Syntax:$find search_path search_expression Example:$find /usr1 ab*.c

10

Page 12: Cp Lab Manual

The above command will search for the files starting with letters ab and with extension c in the path /usr1

file9.Syntax:$file filename Example:$file file1

Will determine the type of file1

chmod10.Syntax:$chmod usertype operation access_permission file(s)

where usertype - owner(u),group(g),others(o) or all(a) operation - add(+) or remove(-) access_permission- read(r),write(w) and execute(x) file(s) - one or more files

Example:$chmod g -r o –r uma.datThis denies the read access of group and others for

filename priya.dat

Octal Notation:Read Permission 4Write Permission 2Execute Permission 1

(e.g) chmod 761 file1Assigns all permissions to the owner, read and write permissions to

the group, and only executable permission to the others for file1

nl11.Syntax :$ nl options filename Example:$ nl file1

This will add line numbers to the left of each line in file1 Option:

-p Doesn’t restart numbering when encounters page break

more12.Syntax:$ more options file(s)

Options: -c Clears the screen and displays the file contents by beginning at

the top of the screen-d Displays the prompt-h Displays help information for all more commands

11

Page 13: Cp Lab Manual

less13.Syntax:$ less options file(s)

Options: -c Clears the screen and displays the file contents by

beginning at the top of the screen-N Displays the contents of the file with its line numbers-h Displays help information for all more commands

pg14.Syntax:$ pg options file(s)

Options: -c Clears the screen and displays the file contents by beginning at the top

of the screen+n Displays the contents of the file starting from line number n -n

Issues a pg command without waiting for you to press the Enter key

spell15.Syntax:$spell options(s) file(s)

Option:-b Uses British dictionary for checking

Example:$spell –b file1This will check for spelling mistakes in file1 using British dictionary

General Purpose Commands

S.No Command Description1. date To display both system date and time.2. bc (Binary calculator)

To perform simple mathematical calculations3 echo Displays each of the arguments on the standard

output4 cal To display the calendar of any specific month of the

year or a complete year.5 man To obtain online help on any command.6. clear To clear the screen.7. expr To evaluate an expression8. factor Factorise a number and print its prime factors

12

Page 14: Cp Lab Manual

date1.Syntax:$date option(s) Options:

‘+%a’ Displays the abbreviated weekday(sun to sat)‘+%A’ Displays the full weekday name(Sunday to Saturday)‘+%B’ Displays the full month name‘+%c’ Displays the current date and time‘+%d’ Displays the day of month ‘+%H’ Dislays the hour‘+%M’ Displays the minute‘+%S’ Dislays the seconds‘+%Y’ Displays the four digit year Example:$date ‘+TIME: %H: %M: %S’

Output: TIME: 14:38:32

bc2.Syntax:$bc

Example:$bc sqrt(9) 3.00 1+2 3

Ctrl+d(to quit from bc)

echo3.Syntax:$echo string Example:$echo “Introduction to unix” Output: Introduction to unix

cal4.Syntax:$cal [month] [year] Example:$cal 10 2003

This displays the calendar for the month of October in year 2003

man5.Syntax:$man command Example:$man ls This displays information about ls command

13

Page 15: Cp Lab Manual

clear6.Syntax:$ clear

expr7.Syntax:$expr `expression` Example:$expr ` 100 + 50 `

150 Ctrl+d(to quit)

factor8.Syntax:$factor Example:$factor

28 2 2 7 Ctrl+d(to quit)

About Yourself and Other People

S.NoCommand Description

1. who am i Returns the current username. This command can be used to find out if someone is already logged on and had forgotten to log out.

2. du Shows the disk usage of the files and the directories in filename

du –sk will give a total of all files and directories on the disk3. w Tells you who’s logged in, and what they’re doing.4. who Tells you who’s logged on, and which computer they

are logged on to.. 5. talk Lets you have a typed conversation with another user6. write Lets you exchange one line messages with another user

who am i1.Syntax:$who am i

du2.Syntax:$du option filename Example:$du –k file1

14

Page 16: Cp Lab Manual

w3.Syntax:$ w

who4.Syntax:$ who

talk5.Syntax:$ talk username

write6.Syntax:$ write username

Input/Output RedirectionApart from the standard input available in Unix, input can be taken from other

sources and can be passed to any destination other than the standard outputs.

This process is called redirection.

There are two types of redirection:1.Input Redirection2.Output redirection

Output RedirectionWhen output from a process is redirected to any destination other than the

standard output (i.e) terminal, it is called output redirection

Syntax:$ command > filename

Here the output is redirected to the file specified.Example:

$date > todayThis command sends the output of date command to the file today.

We can also redirect the output of a command to a file in an append mode.Syntax:

$command >> filename

15

Page 17: Cp Lab Manual

Example:$who >> students

The output of the who command will be appended to the students file.

Input Redirection

When the input is redirected from a source file rather than a standard input it is called as input redirection.Syntax:

$command < filenameHere filename is the input source.

Example:$cat < student

The contents of the student file is the input to the cat command.

Combining standard input and output redirectionBoth input and output redirection can be combined in a command. The <

and > operators can be combined to use both forms of redirection in a single command line.Example:

$wc < student > student1First the contents of the student file is given as input to wc command

whose output is redirected to student1.

Pipes and FiltersIn Unix, commands are used to perform single tasks only. If at all we want

to perform multiple tasks in one command, it is not possible. Redirection provides solution to this problem. But, it creates lot of temporary files, which are redundant and occupy more disk space. Pipes and filters provides the solution to this problem.

PipesPipes is a mechanism which takes the output of a command as the input for

the next command.

16

Page 18: Cp Lab Manual

Example:

$ who > student$ wc –l student4The above example illustratres there are four users currently logged in. This

command uses the files and direction operators to get the number of users. The same result can be obtained with the help of pipes as shown below

$ who | wc –l4

The output of the ‘who’ command is the input for the ‘wc –l’ command

Exercise

1. Create the following directory structure in UNIX CSE

PG UG

2. Create files under CSE with extensions like *.txt, *.c etc.

3. Display all files with extension ‘txt’

4. Rename all files with extension ‘txt’ to ‘dat’

5. Copy the files with extension C to UG directory

6. Delete all the files with extension C from CSE directoryrm *.c

7. Display all files with 2 character filename and extension ‘.txt’

8. To create a file with a list of subject name and to display the first and last three subjects stored in that file

17

Page 19: Cp Lab Manual

9. To list the contents of a file from fourth subject from the end of file and also to list the contents of a file from seventh subject from the beginning of the file

10.Create a file named INDIA, which contains the following dataIndia is my countryAll Indians are myBrothers and SisterI love my country

a) Use the filter command to search for the pattern ‘my’ b) Display all the lines that do not contain the above pattern c) Count the total number of lines containing the pattern ‘my’ d)Display all the lines which contains the pattern ‘country’

11.Create a file containing 10 lines of information. Count the number of lines, number of words and number of characters. 12.Redirect the contents of ls –p to a file called LISTING.

13.Create a file called EMP as given below: E002: malar: mktg: 5000 E001: balan: acct: 7000

a) Sort the file on the employee’s department.b) List the employees who earn between 4000 and 6000.

14. Add line numbers to the content of a file INDIA

15. Display who is on the system.

16.Display the entire text of the file EMP in uppercase.

17. write sa command to Combine two strings.

18. Write and execute the following the following commands (i) Create two files with the name of name.txt, which contain only names,

and reg.txt with the content of register number respectively. (ii) Combine the two files in the form of register number followed by name (iii) Sort the two files in ascending order

18

Page 20: Cp Lab Manual

19.. Write and execute the following UNIX commands (i) Execute more than one command at a time (using semi-colon ;) (ii) Display the user’s full details. (iii) Display the user-id / Group-id. (iv) Execute more than one command at a time (using logical-AND &&).

20. Write and execute the following UNIX commands (i) Demonstrate pipe command (ii) Demonstrate tee command

21. Write and execute the following UNIX commands (i) Use finger command (ii) Use grep command (iii) Use diff command (iv) Use uniq command (v) Use cmp command

22. Write and execute the following UNIX commands (i) Count the specific number of lines from a file start from the beginning of the file (ii) To destroy a specific file from a user directory (iii) Send a greeting message to other user

23. Write and execute the following UNIX commands (i) To view all the files and directories page by page (ii) To view only the directories page by page (iii) Display the complete path of the working directory

24. Write and execute the following UNIX commands (i) To check the working directory (ii) Change the password (iii) To display today’s date (iv) To display the calendar of this month (v) To display a message “University Exam” using a special character

19

Page 21: Cp Lab Manual

VI EDITOR

It is used to create and edit a text file or program. The vi editor has the following three modes.

1. Command mode 2. Colon mode 3. Input mode

COMMAND MODE:In this mode the user can move anywhere in the screen.

VI EDITOR COMMANDS IN COMMAND MODE:

Press Esc key and then use the following keysi used to enter text before the cursor.a used to enter text at the end of the line.x used to delete a character at the cursor position.dd used to delete a line at the cursor position.dw used to delete a word at the cursor position.e used to move the cursor to the beginning of the word.o used to open a new line position the cursor at the start of the line and enter text.^ used to move the cursor to the beginning of the line.$ used to move the cursor to the end of the current line.ctrl+d used to move down the file half a screen.ctrl+u used to move up the file half a screen.

COLON MODE In this mode complicated operations that are normally not possible using simple key strokes can be performed.

VI EDITOR COMMANDS IN COLON MODE

Press Esc then use following keys.:q used to quit vi editor.:q! used to quit vi editor without saving file.:w used to save the file and to remain in the vi editor.:wq used to save the file and to quit the vi editor.:o used to move cursor to the beginning of the file.:$ used to move cursor to the end of the file.:n used to move cursor to the start of particular number.:setnu used to set the line number.

20

Page 22: Cp Lab Manual

INPUT MODE: In this mode the cursor is allowed to enter text after pressing the Esc key followed by any other commands.

Shell Programming

Shell or the command interpreter is a program that interprets ur request to run the UNIX commands.

Set of commands can be grouped together under a single filename and executed and this is done using shell scripts.

Types of shell:

Bourne shell shC shell cshKorne Shell ksh

Creation and execution of shell scripts using command line editor:

1. creation$ cat > greetecho “please enter your name:”read nameecho “hi! Welcome to this session $name”Ctrl + D

21

Page 23: Cp Lab Manual

2. Execution$ sh greetplease enter your name: jayahi! Welcome to this session jaya”

VALID SHELL VARIABLES:nareaa1accounta_count

ASSIGNING VALUES TO VARIABLE:Variable=value

DISPLAYING VALUES OF VARIABLES:1. $ echo value of n is $n

OperatorsArithmetic Operators provided by the shell are +,- * and /Note: precede * symbol by backslash(\) to make a difference from wildcard character (ex . \* 5)

Logical operators -a and -o or ! not

Relational operators -eq : check fro equality of integers

-ne : check for inequality -gt : check if one integer is greater than the other

-lt : check if one integer is lesser than the other -ge : check if one integer is greater than or equal to the other -le : check if one integer is lesser than or equal to the other.

-f : check if a file is an ordinary file -d : check if a file is a directory -r : check if a file is readable -w : check if a file is write able -x : check if a file is executable

22

Page 24: Cp Lab Manual

String comparison operators= equal to!= not equal to

Logical operators-a and-o or-! Not

Conditional execution operations

&& used to execute a command on successful execution of another command.

|| used to execute another command on failure of another command.

Read commandUsed to read the value of the shell variable from a user.

Comment statement# this is a text program.

Programming language construct

1.a)if..then…else…fi b) if..then..elif..else ..fi

2.for…do…done

3.while..do..done

4.until…do..done

5.case …esac

1)if construct

useful for executing a set of commands based on the condition being true and alternate set of commands to be executed if the condition is false.

Ex. if (grep India countri.dat)then

echo “pattern found”else

echo “pattern not found”fi

23

Page 25: Cp Lab Manual

2)for construct

used to perform same set of operations on a list of values.

for variable in value1 value2 value3 …doCommandsdone

Ex. for k in 1 2 3 4 5do

echo “the number is $k”echo “the square of the number is `expr $k \* $k` “

done

3)while construct

Repeatedly executing group of commands as long as the condition is true.while conditiondoCommandlistdone

Ex.to print 3 numbers

a=1while [$a -le 3]doecho $a$a=`expr $a+1`doneo/p. 1 2 3

4.until construct

Repeatedly executing group of commands until a condition is true.until conditiondoCommandlistdone

24

Page 26: Cp Lab Manual

Ex.to print 3 numbers

a=1until [$a -le 3]doecho $a$a=`expr $a+1`doneo/p. 1 2 3

5. case construct

case value inchoice1) commands;;choice2)commands;;….esac

Ex. $echo “enter a value”read myvalcase “$myval” in0) echo zero;;1) echo one;;2) echo two;;3) echo three;;*) echo “invalid argument”;;esac

test command:Used to test for equality and it returns a true or false as a result.

Syntax: test condition

Exercise:1. Greatest among three numbers

Algorithm:Step 1. Read 3 numbers n1,n2 and n3 Step 2. Check if n1 is greater than n2

check n1 is greater than n3 also announce n1 as greatest

announce n3 as greatest else, check whether n2 is greater than n3

if yes, announce n2 as greatest else announce n3 as greatest

25

Page 27: Cp Lab Manual

2. Factorial of a given numberAlgorithm:Step 1. Read nStep 2. Initialize fact to 1 and i to nStep 3. Repeat the following until i>0

Assign fact * i to fact Decrement i by 1

3. Sum of Odd numbers upto nAlgorithm:Step 1. Read nStep 2. Initialize x=1 and sum=0Step 3. Repeat the following until x < n

Assign sum + x to sum Increment x by 2

4.Generation of Fibonacci numbersAlgorithm:Step 1. Read nStep 2. Initialize p=-1, q=1 and I=1Step 3. Repeat the following until I < n

Assign p + q to r Assign q to p Assign r to q Increment I by 1

5.Implement the Arithmetic calculator Algorithm:Step 1. Read a, b and optionStep 2. According to the option perform the operation

6. Write a shell program to convert temperature in Fahrenheit to Degree Centigrade.

Algorithm:Step 1. Read fStep 2. Assign (f-32) * 5/9 to c

26

Page 28: Cp Lab Manual

7.Check whether given string is a palindrome or not.

Algorithm:Step 1. Read a String Step 2. Find the length of the string Step 3. Start reading from the last character to the first character and store it as a new string in tempStep 4. Compare both the strings, if it is same the given string is palindrome

8. Check whether the given year is leap year or notAlgorithm:Step 1. Read yearStep 2. Divide the year by 4, if the remainder is zero the given year is leap.

9. Write a Shell program to find the largest digit of a number.Algorithm:Step 1: Get a number from the userStep 2: Obtain individual digit for the above number using modulo operatorStep 3: Initialize variable max with first digitStep 4; Compare the value of max with the other digits,

if the value of max is lesser update the value of max Step 5: Display the value of max

10.Write a Shell program to find the sum of ‘n’ different numbersAlgorithm:Step 1: Get array of n numbersStep 2; Using for loop , add the numbersStep 3: Display the sum.

11.Write a Shell program to find the sum of digits of a numberAlgorithm:Step 1: Get a number from the userStep 2: Obtain individual digit for the above number using modulo operatorStep 3: perform sum Step 4: Display the sum

27

Page 29: Cp Lab Manual

12.Write a Shell program to generate prime numbers between 1 and 50Algorithm:Step 1: Get a number and initialize i as 2Step 2: if i<=number/2 goto step 3 Step 3: if number mod i == 0 print not prime Step 4: increment I by 1 and goto step 2Step 5: if i==number print the number is primeStep 6: Repeat above steps for numbers between 2 and 50.

13.Write a Shell program to find the area and circumference of a circleAlgorithm:Step 1: Get the radius of circleStep 2: Calculate area = 3.14*r*rStep 3: Calculate circumference = 2*3.14*rStep 4: Display the results

14.Write a Shell program to check the given number and its reverse are sameAlgorithm:

Step 1: Get a number from the userStep 2: Set a loop upto the number is not equal to zero

Step 3: reminder=number%10 Step 4:rnum=rnum*10+reminder Step 5: number=number/10 Step 6: if number==rnum print both are same

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

Algorithm:Step 1: Get n numbers Step 2: initialize evensum and oddseum as 1Step 3: create a loop for n times

if (a[i]%2==0)evensum =evensum+a[i]

else oddsum=oddsum+a[i]Step 3: Display the result.

28

Page 30: Cp Lab Manual

C Programs on UNIX

1. To Demonstratea. malloc() b) calloc() c)realloc

malloc: Allocates memory Declaration: void *malloc(size_t size);

malloc allocates a block of size bytes from the memory heap. It allows a program to allocate memory explicitly as it's needed, and in the exact amounts needed. The heap is used for dynamic allocation of variable-sized blocks of memory. Many data structures, such as trees and lists, naturally employ heap memory allocation.

All the space between the end of the data segment and the top of the program stack is available for use in the small data models, except for a small margin immediately before the top of the stack. This margin is intended to allow the application some room to make the stack larger, in addition to a small amount needed by DOS. In the large data models, all the space beyond the program stack to the end of available memory is available for the heap. Return Value: ■ On success, malloc returns a pointer to the newly allocated block of memory. ■ On error (if not enough space exists for the new block), malloc returns null. The contents of the block are left unchanged. ■ If the argument size == 0, malloc returns null.

calloc :Allocates main memory

Declaration: void *calloc(size_t nitems, size_t size);

calloc provides access to the C memory heap, which is available for dynamic allocation of variable-sized blocks of memory.

29

Page 31: Cp Lab Manual

Many data structures, such as trees and lists, naturally employ heap memory allocation. calloc allocates a block (nitems * size) bytes and clears it to 0. To allocate a block larger than 64K, use farcalloc. Return Value: ■ On success, returns a pointer to the newly allocated block. ■ On failure (not enough space exists for the new block, or nitems or size is 0), returns null. Example: str=(char *)calloc(10,sizeof(char));realloc: ■ realloc reallocates main memory Declaration: ■ void *realloc(void *block, size_t size);

realloc adjusts the size of the allocated block to size, copying the contents to a new location if necessary. Argument What it is/Doesblock Points to a memory block previously obtained by

calling malloc, calloc, or realloc. If block is a null pointer, realloc works just like malloc.

oldblock Points to a memory block previously obtained by calling farmalloc, farcalloc, or farrealloc.

size New size for allocated block nbytes New size for allocated far block (in bytes) . Return Value: ■ On success, both functions return the address of the reallocated block, which might be different than the address of the original block. ■ On failure (if the block can't be reallocated, or if size == 0 for realloc), the functions return null. Example

#include <stdio.h>#include<string.h>#include<alloc.h>

30

Page 32: Cp Lab Manual

#include<process.h>void main() {

char *str;str=(char *)malloc(10);strcpy(str,”Hello World”);printf(“Address of String is %d”, str);str=(char *)realloc(str,20);printf(“New Address of String is %d”, str);free(str);}

FILES

A File is a collection of related information, that is permanently stored on the disk and allows us to access and alter the information whenever necessary.

HIGH LEVEL FILE Operations (Opening and Closing of File)We can perform the following basic operations on Files.

Naming a file Opening a file Reading data from a file Writing data to a file Closing a file

There are large number if standard library functions available for performing disk files.

i. High level file I/O functionsii. Low level file I/O functions

High level file I/O functions do their own buffer management, whereas in low level file I/O functions buffer management has to be done by the programmer.

Some of the high level file I/O functions.

Function Purposefopen() Used to create or open a file.fprintf() Used to write data to the filefscanf() Used to read data from the file.fseek() Used to position the desired point.ftell () Used to specify the current position.

31

Page 33: Cp Lab Manual

fclose() Used to close an opened file.feof() Used to find, if end of file is encountered.fputc() Used to write a character to a file.fgetc() Used to read a character from file.rewind() Used to move control to the beginning of the file.remove() Used ti erase a fileffush() Used to flush a file.

OPENING AND CLOSING OF FILE

Opening a fileA data file must be opened before it can be created or processed, this

associates the file name with buffer area.Opening a file means,creating a new file with specified file name and with

accessing mode

Syntax:

The data structure of the file s defined as FILE in the standard I/O library function definitions. Therefore, all files should be declared as type FILE before they are used.

The first statement declares the variable, ‘fp’ as a pointer to the data type FILE. The Second statement opens the file named filename and assigns identifier to the FILE type pointer ‘fp’. This pointer which contains all the information about the file and it is used as a communication link between the system and the program.

The mode in the second statement specifies the purpose of accessing the file like read, write etc.

File accessing modes

Mode Purpose

r Used to open the file for reading purpose.

w Used to open the file for writing purpose.

a Used to appending data into the file.

r+ Used to open an existing file for reading and writing.

w+ Used to open a new file for both reading and writing.

a+ Used to open an existing file for both reading and writing.

32

FILE *fp;fp=fopen(“filename”,”mode”);

Page 34: Cp Lab Manual

When the file is opened in the write mode, if the file does not exist it is created, and the contents are deleted if that file already exists.

When the file is opened in the read mode if the file exists the file is opened with the current contents safe, otherwise and error occurs.

Example : fp=fopen(“Input”,”w”);

It opens the file input in the write mode. If input file already exists its contents are deleted. If it does not exist, the input file is created.

We can open and use a number of files at the time. This number however depends on the system we use.

Closing a file

A file must be closed after all the operation of the file have been completed.

Syntax :

By doing this all the information associated with the file is flushed out from the buffers and all links to the file are broken. It also prevents any accidental measure of the file.

Example : fclose(fp);

In the above example the statement fclose(fp) is used to close a file, after all operations on them are completed and used to change the mode of operation. File pointer can be used for another file. All files are closed automatically whenever a program terminates.

OPERATIONS ON SEQUENTIAL AND RANDOW ACCESS FILES

Types of files

We are going to discuss three types of files mainly, and these types of files are formed depending on the organization of data in the file.

33

fclose(file-pointer);

i. Sequential fileii. Random Access file.

Page 35: Cp Lab Manual

sequential file

As the name implies that the records are stored and retrieved sequentially i.e.,one after another. Sequential file is a data structure which consists of a sequence of records of the same type and size. The records in the file can be read only sequentially. i.e., One after another starting from the beginning of the file

The primary advantage of a sequential file compared to an any other file is that it can grow or shrink dynamically. The sequential access is the disadvantage. Usually the records in the file are arranged in ascending or descending order of the key fields.

To understand the sequential file, lets start with an example. Consider the example of a tape or cassette where the songs are stored sequentially. Storing data sequentially is the simplest form of file, but a tedious one. Reading data to a file or writing data from it takes a lot of time as the data is not stored. The data is stored on FCFS (First Come First Server) basis. Taking example where we want to retrieve as record which is unfortunately stored at the last position in the

Random Access FilesIn case of sequential file , we are writing records in the sequential file as they come. But in direct access files, we write the record to a particular position. Since we are deciding the position of the particular record, there is some relation between the key using which we are deciding the position of the record. Hence using the relation between the key and record number, we can determine if a given record is present in the file or not.

To access particular part of file we have the following functionsftell( ) fseek( ) rewind( )

i)ftell( ) – this function is used to specify the current position of a file. It makes the file pointer and returns a number of type long, that corresponds to the current position. n=ftell(p); where n is the relative offset of the current position in bytes

ii) fseek( )- It is usd to move the file position to a desired location within a file.

fseek(fileptr,offset,position);fileptr-is a pointer in the file concernedoffset-is a number or variable of type longposition – is an integer, its specifies the number to be moved from the location specified by position.

34

Page 36: Cp Lab Manual

iii)rewind( )It is used to takes a file pointer to the starting position of the file and resets

the position to the start of the file. rewind(fp); n=ftell(fp); where 0 is assigned to n, because the file position has been set to the start of the file by rewind.

Exercise1. Write a C program using pointers to allocate a memory for the string “University” and reallocate the memory for the string to “University Examinations”.

Algorithm:

Step 1: Declare a string variableStep 2: Allocate memory for the string university using malloc functionStep 3: Reallocate memory for the variable with the string university examination using realloc function

2.Write a program to interchange the values stored in 2 variables using function with pointers.

Algorithm:Step 1: Declare the function to interchange the variablesStep 2: Declare and initialize the two integer variablesStep 3: Print the values of two variables before interchangeStep 4: Call the function to interchange the values of two variables Step 5: Print the interchanged values

3.Write a C program to create a file, which contains register number, name, age etc. and display the content of the file.

Algorithm: Step 1: Create a file with the above data .

Step 2: Open the file and display the content. Step 3: Close the file.

4.Write a program to perform file copy operation.

Algorithm: Step 1: Open a the above the file in read mode Step 2: Open destination file in write mode

Step 3: Read the content of source file and write it in destination file. Step 4: Close both the files.

35

Page 37: Cp Lab Manual

5.Write a program to create two files and perform merge operation on itAlgorithm:

Step 1: open a file1 in read mode and file2 in write mode Step 2: using fseek( ) move file2 ptr to end of the file

Step 3: Read the content of file1 and write it in file2Step 4: close both the files.

6.Write a C program to find the sum of ‘n’ numbers using function.Algorithm:

Step 1: Create a function sum( )Step 2: Get n numbers from the userStep 3: Perform sum on it.Step 4: Display the sum.

7.Write a C program using dynamic memory allocation to develop salary details of 5 employees.

Algorithm:Step 1: Declare the structure for emp Step 2: Allocate the memory for the structure using malloc( )Step 3: Get the salary details for 5 employeesStep 4: Display it.

8.Write a C program using dynamic memory allocation to find the sum of elements of a matrix.

Algorithm: Step 1: Declare 3 arrays a[10][10], b[10][10], add[10][10],

Step 2: Get the number of rows and columns as m and n respectively Step 3: Scan the values of the matrices according to the values of m and n. Step 5: Add the two matrices directly and store the values in ‘add[10][10]’ Step 6: Using ‘for loop’ print the values of add[10][10] Step 7: End the loop

36

Page 38: Cp Lab Manual

9.Write a program to print addition, subtraction and multiplication values using functions.

Algorithm: Step 1: Create separate function for each operation. Step 2: Within each function definition, get two values from the user,

perform the respective operation and print values. Step 3: Call the user definied function from the main function.

10.Write a program to perform following file manipulation: Read a fileCopy a fileChange the case of the entire fileCount the number of words, spaces and lines in a file.

Algorithm:Step 1: open a file a.txt using fp1 in read modeStep 2: Read the content of the file and display itStep 3: copy operation : Open another file b.txt using fp2 , Set fp1 to starting of the file using fseek( ) Read the content of a.txt using fp1 and put it in the b.txt Display the content of b.txt Close the files Step 4: To change the case :

Open another file b.txt in read modeRead the content of file using ch=getc( )

If ch is between 91 to 65 add 32 to it else if ch is between 97 to 122 subtract 32 from it now print the ch close the file

Step 5:To count the no. of words, spaces and lines in a file Open another file b.txt using fp2 in read mode

Read the content of file using ch=fgetc( ) If ch== “ “ then words++ else if ch== “\n” then lines++

else character++Display no. of words is lines+space

No. of lines is lines No. of letters is words+space+lines

No. of spaces is spaces

37