Sie sind auf Seite 1von 33

1.

UNIX COMMANDS

1.A. STUDY OF UNIX OPERATING SYSTEMS

AIM:

To study about the UNIX operating system.

OPERATING SYSTEM:

An operating system is a layer of software, which takes care of technical aspects of


a computer's operation. It shields the user of the machine from the low-level details of
the machine's operation and provides frequently needed facilities. Simply saying, It is a
collection of programs that acts as an interface between the user and the computer by
coordinating the operations of hardware and software.

Classification of Operating System:

1. Single user or Multi-user -- how many users can be using the system
`simultaneously'.

2. Single task or Multi-tasking -- how many tasks the OS can perform


`simultaneously'.

INTRODUCTION TO UNIX OPERATING SYSTEM:

UNIX is an operating system designed for multiprocessing, multitasking, and multi-


users. It originated at AT&T's Bell Laboratories in the late 60s. Because UNIX
operating systems are generally written in the C programming language, they are easily
portable. They have been implemented on a wide variety of machines ranging from
microcomputers to mainframes.

Applications of UNIX:

UNIX is now used extensively in the federal government and the military and is
beginning to have much more widespread use in universities and business. UNIX is fast
becoming the operating system for government, scientific, engineering, and business
users.

STRUCTURE OF UNIX:

The UNIX operating system is made up of the following three parts:

1. Kernel

2. Shell

3. Tools and Applications

1
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. Simply saying, Kernel is the heart of the UNIX – it is the master program that
controls the computer resources.

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

Tools and Applications

Tools are also called as commands. It is used for file processing, editing,
redirection, communication etc..

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.

Examples of files:

v a document (report, essay etc.)

v the text of a program written in some high-level programming language

v instructions comprehensible directly to the machine and incomprehensible to a


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

v a directory, containing information about its contents, which may be a mixture of


other directories (subdirectories) and ordinary files.

Directories:

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.

2
SALIENT FEATURES OF UNIX:

v Multi-user - Support more than one user session, simultaneously, on the same
system, at a time.

v Multiprogramming - Support more than one program, in memory, at a time.


Amounts to multiple user processes on the system.

v Multitasking - A single process can initiate multiple threads of execution


concurrency in a process.

v Supports virtual memory, programs larger than the physical RAM of the
system, can be executed.

v System communication and documentation, System portability, System Security


are the other features of UNIX.

ARCHITECTURE OF UNIX SYSTEM:

DIFFERENCES BETWEEN LINUX AND UNIX OS


Command-line-wise, emacs
almost none, although this has been changing (for better or worse).
Linux has a much larger market appeal and following than any commercial UNIX. GUI-
wise there are alsosh whodifferences--Linux, as most other UNIX, uses an X-
no major
Windowing system.
kernel date
S. cpp LINUX UNIX
No.
hard ed
as is free
1 ccLinux
Many UNIX Operating Systems are very
ware expensive.
Linux wc
ldruns on many hardware platforms, A typical UNIX is proprietary-hardware-
the commodity Intel-x86/IBM-spec bonded (and this hardware tends to be much
2 grep
personal computers being the most more expensive than a typical PC clone).
prominent. nroff
Linux feels very much like DOS/Win in the A typical UNIX account feels like a
3 Other
late 80s/90s, but apps
is much sturdier and richer mainframe from the 60s/70s.

CONCLUSION:
Thus the features of UNIX Operating System were studied successfully.

1.B. BASIC UNIX COMMANDS

AIM:
To study the basic UNIX commands and their syntax.

COMMANDS:

Command is a Series of characters that invokes the shell and tells the Unix
operating system to perform some operations.

3
CLASSIFICATION OF COMMANDS:

1. General Purpose Commands


2. Directory Commands
3. File Commands
4. Pattern Searching Commands
5. File Permission Commands

GENERAL PURPOSE COMMANDS:

1. COMMAND : date
PURPOSE : To display the current date and time
SYNTAX : $date
EXAMPLE : $date
OUTPUT : Thu Nov 15 16:24:10 IST 2007

2. COMMAND : cal
PURPOSE : To display the calendar
SYNTAX : $cal
EXAMPLE : $cal 1 2008
OUTPUT :
January 2008
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

NOTE : Without any argument ‘cal’ displays the current, previous and next
month calendar along with date and time.

3. COMMAND : echo
PURPOSE : To display the message on the screen.
SYNTAX : $echo
EXAMPLE : $echo COMPUTER SCIENCE
OUTPUT : COMPUTER SCIENCE
4. COMMAND : who
PURPOSE : To show the users currently logged on.
SYNTAX : $who
EXAMPLE : $who
OUTPUT : root :0 Nov 15 15:00
root pts/1 Nov 15 15:01 (:0.0)
student pts/1 Nov 15 15:09 (ws205)

5. COMMAND : whoami
PURPOSE : To know in which terminal the user is currently logged on

4
SYNTAX : $whoami
EXAMPLE : $whoami
OUTPUT : student

6. COMMAND : tty
PURPOSE : To report the name of the device the user is currently using for a
terminal
SYNTAX : $tty
EXAMPLE : $tty
OUTPUT : /dev/pts/3

7. COMMAND : df
PURPOSE : To show disk usage
SYNTAX : $df
EXAMPLE : $df
OUTPUT : Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/VolGroup00-LogVol00
38059528 4901880 31224336 14% /
/dev/hdc1 101086 8967 86900 10% /boot
none 62664 0 62664 0% /dev/shm

8. COMMAND : man
PURPOSE : It gives the online help to all commands with all options that a
command can support, followed by additional information
SYNTAX : $ man <command>
EXAMPLE : $man ls
OUTPUT :
LS(1) User Commands LS(1)

NAME
ls - list directory contents

SYNOPSIS
ls [OPTION]... [FILE]...

DESCRIPTION
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuSUX nor --sort.
…….

9. COMMAND : history
PURPOSE : To print the recently used commands
SYNTAX : $history
EXAMPLE : $history 5
1119 whoami
1120 tty
1121 $bc 12 * 5
1122 man ls

5
1123 history 5

10. COMMAND : clear


PURPOSE : To clear the screen
SYNTAX : $clear
EXAMPLE : $clear

DIRECTORY COMMANDS:

1. COMMAND : pwd
PURPOSE : To display the pathname of the current working directory
SYNTAX : $pwd
EXAMPLE : $pwd
OUTPUT : /home/student

2. COMMAND : mkdir
PURPOSE : To create a new Directory
SYNTAX : $mkdir <directory name>
EXAMPLE : $mkdir Oslab
OUTPUT :$

3. COMMAND : cd
PURPOSE : To change from one directory (working) to another directory
specified by its arguments
SYNTAX : $ cd <directory name>
EXAMPLE : $ cd Oslab
OUTPUT : Oslab]$
NOTE : Without any argument, ‘cd’ changes to the home directory

4. COMMAND : rmdir
PURPOSE : To remove the existing directory
SYNTAX : $rmdir <directory name>
EXAMPLE : $rmdir Oslab
OUTPUT :$

5. COMMAND : ls
PURPOSE : To list out the names of all files in the current working directory
SYNTAX : $ls
EXAMPLE : $ls
OUTPUT : asha joy keerthi

FILE COMMANDS:

6
1. COMMAND : cat
a) PURPOSE : To create a new file
SYNTAX : $cat > <filename>
EXAMPLE : $cat > sample
UNIX <ctrl+D>
OUTPUT :$

b) PURPOSE : To append the file contents


SYNTAX : $cat >> <filename>
EXAMPLE : $cat sample
Linux <ctrl+D>
OUTPUT :$

c) PURPOSE : To display the file contents


SYNTAX : $cat <filename>
EXAMPLE : $cat sample
OUTPUT : UNIX.
Linux

d) PURPOSE : To concatenate the multiple files into a single file


SYNTAX : $cat <file1> <file2> >> <file3>
EXAMPLE : $cat sample sample1 >> sample3
OUTPUT : $

2. COMMAND : sort
PURPOSE : To sort the file contents in some particular order
SYNTAX : $sort <filename>
EXAMPLE : $sort sample
OUTPUT : Linux
UNIX

3. COMMAND : cp
PURPOSE : To copy a file to another file.
SYNTAX : $cp <source file> <destination file>
EXAMPLE : $cp sample sam
OUTPUT :$
NOTE : Using ‘cp’ , we can copy file(s) to a directory and also copy a
directory to another directory.

4. COMMAND : mv
PURPOSE : To move the contents of file to another (that is, rename a file)
SYNTAX : $mv <source file> <destination file>
EXAMPLE : $ mv sam sam1
OUTPUT :$
NOTE : Using ‘mv’, we can move file(s) to a directory and also move a
directory to another directory (that is, rename a directory).

5. COMMAND : rm

7
PURPOSE : To delete a file permanently
SYNTAX : $rm <filename>
EXAMPLE : $rm sam1
OUTPUT :$

6. COMMAND : file
PURPOSE : To find the type of file present in that particular directory
SYNTAX : $file <filename>
EXAMPLE : $file sample1
OUTPUT :ASCII text
NOTE : To find the type of all files in a directory, can use the syntax,
$file <directory name> / *

7. COMMAND : wc
PURPOSE : To count the number of lines, words and characters in a file
SYNTAX : $wc <filename>
EXAMPLE : $wc sample
OUTPUT : 2 2 10 sample

8. COMMAND : lp
PURPOSE : To print the contents of a file to the printer
SYNTAX : $lp <filename>
EXAMPLE : $lp sample
OUTPUT :$

PATTERN SEARCHING COMMANDS:


These commands are used to search for a particular pattern in one or more files and
display the result on the Standard Output.

1. COMMAND : grep (global search for regular expression and print)


PURPOSE : To search and display a line for a given word or given pattern
SYNTAX : $grep <pattern> <filename>
EXAMPLE : $grep i sample
OUTPUT : Linux
NOTE : egrep ( extended version of grep) and grep (fast grep) are the other
pattern searching commands.

FILE PERMISSION COMMANDS:


Different modes or permissions associated with the file and directory in the UNIX
are : (i) Owner Permissions
(ii) Group Permissions

8
(iii) Other Permissions
The actions that can be performed on a file or a directory by Owner, group or others
are read(4), write(2) and execute(1) permissions.

1. COMMAND : chmod
PURPOSE : To change the access permissions for the owner, group and others.
SYNTAX : $chmod <mode > <filename>
EXAMPLE : $chmod 754 sample
OUTPUT :$

2. COMMAND : chown
PURPOSE : To change the ownership of a file
SYNTAX : $chown <owner> <filename>
EXAMPLE : $chown directory sample
OUTPUT :$

RESULT:
Thus the basic UNIX commands were studied successfully.

1.C. STUDY OF UNIX EDITORS

AIM:
To Study about the UNIX Editors.

Introduction to the ex and ed editors

Line editors means that whatever operation has to be performed it concerns a line or
specified number of lines. ex text editor is based on ed but has many extensions and
improvements on ed. ex is more communicative than the ed editor , as it tells the user
what is wrong with what he has done and also in many cases tells how to fix the error.

Both the ex and ed editors use an edit buffer i.e. the changes made to the file do not
affect the file directly. This is so because the file to be changed is copied into a
temporarylocation – which is called an edit buffer or simply the buffer.

Changes that the user makes are made to the copy of the file in the buffer, and to
make the changes permanent the buffer has to be written to the permanent storage.

The most easy way of addressing a line or referring a line in ed is through line
numbers. There are other ways of referring a line – by the line’s textual contents.

9
To edit any file the command line for ex or ed is ed filename – if this file exists the
file will be copied to a temporary edit buffer. If the file does not exist ed will respond with
a question mark as its way of communicating that this file doesnot exist.

Ed has a help feature by which it can be told to specify its error messages more
verbosely. The ‘h’ alphabet will inform ed that specific error message is required. The
lower ‘h’ will force ed to respond that particular error only and for the rest of the time it
will revert to its cryptic message of ‘?’.

If this is not required and an error message is always wanted, then the uppercase
‘H’ will force ed to respond to error messages in a more verbose manner. This ‘H’ can be
used as a toggle to turn the message off and on.

If the file exists ed tells the user the number of bytes/character read from the file
into the edit buffer. The ed prompt is ‘go’ which indicates the user that ed is ready and
waiting for the user to enter a command to process.

The Visual Editor


An ASCII editor which comes along with the Operating System itself.

- vi the full screen editor – an introduction

vi which stands for visual editor is a powerful and sophisticated tool for creating
and editing files. It displays one full screen of text and allows you to move the
cursor to any point of the screen or the file. There are more than 100 commands in
vi
.exrc ( Pronounced as dot exrc ) file, if present is the initial batch file that is
executed from your home directory every time you load vi. This file contains the
options that control vi’s editing environment.

How to create a text file in vi

There are three ways of invoking the vi editor to create a file or edit an existing
file , they are
vi Invokes vi in full screen mode with default setting
view Invokes vi in read-only mode , no updates allowed to the files opened in this mode
vedit Designed for beginners. The report flag is set to 1, so all changes are reported. The
showmode and the novice options are set for more interactive information.

Once you have entered vi the cursor is like a pencil and eraser that may
Be moved around on the screen to write(insert) or erase (delete/change)as needed. The
buffer can be thought of as a scroll of paper with a picture frame placed over the flat
exposed part of the scroll. The data inside the frame can be globally manipulated using vi.
The data on the entire scroll can be globally manipulated using ex, the line editor.

Using any of the above options you can invoke vi to create or edit file by typing the
command followed by the file name at the $ prompt

$ vi {filename}

Limits The vi editor has some limits. These limits control how vi functions.

10
The following table lists the maximum allowed limits.

Maximum Description

1 MB Buffer size, The max size of file that can be opened in vi.
512 or 1020 Characters on one line.
250,000 Lines per file.
128 Characters per filename.
256 Characters in a global command list.
100 Characters in the UNIX escape command.
32 Total string macros.
512 Total Characters in string macros.

The vi editor has three modes of operation. Each mode is a separate entity from the
other two. The three modes are
COMMAND MODE
EDIT MODE
ESCAPE COLON OR EX MODE

These are some terminologies related to the editor.

Regular Expressions Regular Expressions are patterns used to match strings in


searches and substitutions.

Buffers The vi editor uses a session buffer to maintain a copy of the file that
is being edited. There are two session buffers that one can switch between.

Registers The vi editor maintains various registers where text may be stored.
Registers are used to save and retrieve text. One can reference the named registers
with a single alphanumeric name (a to z, 1 to 9, A to Z).

The command mode

:w write to the file and continue editing

:q quit vi when the file is not modified

:wq write to the file and quit vi

ZZ write to the file and quit vi

:q! quit without saving changes

:x write and quit

11
Mapping keys to commands

The mapping function allows the user to set keys for commands that used
more frequently. Commands like the colon commands with ranges and special
characters are often long and time consuming to type. The simple solution to
overcome is to map the entire command to a single key. Then from the command
mode, a single press of a key will run the entire command .

Some keys are mapped by vi itself. For example the cursor movement keys
like j, k, l and h are mapped by default to their respective cursor movement
commands. The map command maps any character or escape sequences to
command sequences. TO check out the default mapped sequences, type in

:map

This will display all the keys that are mapped.

Customising vi

Vi is widely used editor program, but it has many shortcomings when compared to
other ‘State of Art’ editors available. How-ever there are a few rigidly fixed
parameters about vi. Many of its characteristics can be altered by the user.

The .exrc file

Every time you invoke vi , a file called .exrc is searched for in the home
directory. If it exists then it is read and interpreted and vi customizes itself
according to the contents of the .exrc file.

12
Conclusion:
Thus the features of UNIX editors were studied successfully.

2. SHELL PROGRAMMING

2.A SIMPLE SHELL PROGRAM

2.A.1. ARITHMETIC EXPANSION

AIM:
choose a option
5
operation closedchoose a option
5
operation closed illustrate the Arithmetic expansion concept.

ALGORITHM:

1. Start.
2. Get the values of A and B from the user.
3. Print the sum of A and B.
4. Stop.

PROGRAM:

clear
echo "Enter the value of a:"
read a
echo "enter the value of b:"
read b
echo "$a + $b = $(($a+$b))"

OUTPUT:

13
[login45@localhost ~]$ sh arith.sh.sh
Enter the value of A:
50
Enter the value of B:
50
50 + 50 = 100

RESULT:
Thus the Shell script illustrating the use of Arithmetic Expansion was executed
successfully.

2.A.2 SORTING THE CONTENT OF THE FILE

AIM:
To write and execute the shell program for sorting the content of the file.

ALGORITHM:
1. Start
2. Enter the file name
3. Sort the file using Sort command
4. Display the Sorted file
5. Stop

PROGRAM:
echo "enter the file name"
read file
echo "sorted content of the file"
sort $file

OUTPUT:
[login45@localhost ~]$ cat > mal
raje
ah
vij
log

14
[login45@localhost ~]$ sh sor.sh
enter the file name
mal
sorted content of the file

ah
log
raje
vij

RESULT:

Thus the Shell script illustrating the use of sorting was executed
successfully.

2.A.3 ARITHMETIC OPERATION

AIM:
To write and execute the shell program to perform the basic arithmetic
operation.

ALGORITHM:
1. Start
2. Read the First number
3. Read the Second number
4. Display the menu to user
5. Get the choice from the user
6. Perform the arithmetic operation
7. Print the Result
8. Stop

PROGRAM:
echo "enter the first number:"
read a
echo "enter the second number:"
read b
while true
do
echo "menu"
echo "1.addition"
echo "2.subraction"
echo "3.multiplication"
echo "4.division"
echo "0.break"
echo "enter your choice"
read ch

15
case $ch in
0) break;;
1) c=`expr $a + $b`;;
2) c=`expr $a - $b`;;
3) c=`expr $a \* $b`;;
4) c=`expr $a / $b`;;
esac
echo "the result $c"
done

OUTPUT:
enter the first number
4
enter the second number
2

menu
1.addition
2.subtraction
3.multiplication
4.division
0.break
enter your choice
1
the result is 6

menu
1.addition
2.subtraction
3.multiplication
4.division
0.break
enter your choice
2
the result is 2

menu
1.addition
2.subtraction
3.multiplication
4.division
0.break
enter your choice
3

16
the result is 8

menu
1.addition
2.subtraction
3.multiplication
4.division
0.break
enter your choice
4
the result is 2

RESULT:
Thus the Shell script illustrating the Arithmetic operation was
executed successfully.

2.B. CONDITIONAL STATEMENTS


2.B.1. LOGGED IN OR NOT

AIM:

To write a shell program to check whether the given user has logged in or not.

ALGORITHM:

1. Start
2. Read the Input
3. Using who and grep command display the original user name
4. Else display the user is not currently logged in.
5. Stop

PROGRAM:

echo "enter the name of the login"


read n
if who | grep "$n"
then
echo the user has logged in
else
echo the user has not logged in
fi

OUTPUT:

[user1@unixlab ~]$ sh log1.sh


enter the name of the login

17
user1
user1 pts/2 Apr 2 12:03 (192.168.5.250)
the user has logged in

RESULT:

Thus the shell program to check whether the given user user has been
logged in or not has been verified.

2.B.2 LARGEST OF TWO NUMBERS

AIM:

To write a shell program to find the largest of two numbers.

ALGORITHM:

1. Start
2. Read the first number and store it in variable a
3. Read the second number and store it in variable b
4. If a is greater Print a , else b.
5. Stop

PROGRAM:
echo "enter the first no"
read a
echo "enter the second no"
read b
if test $a -gt $b
then
echo $a is greater
else
echo $b is greater
fi

OUTPUT:
[login45@localhost ~]$ sh lar.sh
enter the first no
23
enter the second no
32

18
32 is greater

RESULT:

Thus the program to find the largest of two numbers has been verified
successfully.

2.B.3 CHECK FOR PALINDROME

AIM:
To write a shell program to reverse a string and check for Palindrome.

ALGORITHM:
1. Start
2. Read the given input
3. Store it in Variable c
4. Check if c is greater than 0
5. Check if the reversed string is same
6. If it is same it is a Palindrome.
7. Stop

PROGRAM:
echo enter any string
read str
c=’echo $str | wc –c’
while [ $c –gt 0]
do
s=’echo $ | cut –c $c’
c=’expr $c – 1’
temp=’echo $temp$s’
done
echo reverse string is $temp
if [ $str = $temp ]
then
echo the given string is palindrome
else
echo the given string is not a palindrome
fi

OUTPUT:
$ sh pa
enter any string
madam
reverse string is madam

19
the given string is palindrome

$ sh pa
enter any string
computer
reverse string is retupmoc
the given string is not a palindrome

RESULT: Thus the Shell program is written to reverse the string and also
checked for Palindrome.

2.B.4 GENERATING FIBONACCI SERIES

AIM:
To write a shell program to generate the Fibonacci series.

ALGORITHM:
1. Start
2. Read the input
3. Initialize the fibonacci as 0
4. Check whether the number is 0 or not
5. If it is 0, Print the number is 0.
6. If it is not equal to 0, start the loop as 0.
7. Increment the value by 1.
8. Print the result.
9. Stop the process.
PROGRAM:
echo enter the number
read n
fib=0
a=0
b=1
echo the fibonacci series is
if [ $n –eq 0 ]
then
echo the number is zero
else
i=0
while [ $i –lt $n ]
do
fib=’expr $fib + $a’
a=$b
b=$fib
i=’expr $i + 1’
echo $fib
done
fi

OUTPUT:
Enter the number

20
4
the fibonacci series is
0
1
1
2
RESULT: Thus the program for generating fibonacci series has been verified
and executed successfully.

2.C. TESTING AND LOOPS


2.C.1. STRING COMPARISON
AIM:
To write and execute a Shell script to compare two strings, using the test command.

ALGORITHM:

1. Start.
2. Scan two strings, A and B, from user.
3. Test whether A and B are equal. If so, echo that they are equal.
4. Else, echo that A and B are not equal.
5. Stop.

PROGRAM:
echo enter the string, A:
read A
echo enter the string, B:
read B
if test $A = $B
then
echo A is equal to B
else
echo A and B are not equal
fi

OUTPUT:
[login45@localhost ~]$ sh string.sh
enter the string, A:
sample
enter the string, B:
sample
A is equal to B

[login45@localhost ~]$ sh string.sh


enter the string, A:
sample
enter the string, B:
Sample
A and B are not equal

21
RESULT:
Thus the Shell script to compare two strings, using test command was executed
successfully.

2.C.2 SORTING AN ARRAY

AIM:
To write and execute a shell script to sort an array in ascending order, using for
loop.

ALGORITHM:

1. Start.
2. Declare the array values.
3. Display the array (using for loop).
4. For i = 0 to 4, repeat the following:
a. For j = i to 4, repeat the following:
i. If the number in the ith position of array is greater than that of in
the jth position, then swap those two numbers.
5. Display the sorted array (using for loop).
6. Stop.

PROGRAM:

declare nos[5]=(4 -1 2 66 10)


echo "unsorted array:"
for((i=0;i<=4;i++))
do
echo ${nos[$i]}
done
for((i=0;i<=4;i++))
do
for((j=$i;j<=4;j++))
do
if [ ${nos[$i]} -gt ${nos[$j]} ]; then
t=${nos[$i]}
nos[$i]=${nos[$j]}
nos[$j]=$t
fi
done
done
echo "sorted array:"
for((i=0;i<=4;i++))
do
echo ${nos[$i]}
done

22
OUTPUT:

[login45@localhost ~]$ sh sort.sh


unsorted array:
4
-1
2
66
10
sorted array:
-1
2
4
10
66

RESULT:
Thus the shell script for sorting of an array, using for loop, was executed
successfully.

23
2.C.3 SUM OF DIGITS

AIM:
To write and execute a shell script to find the sum of digits of a given number,
using while loop.

ALGORITHM:

1. Start.
2. Input number n.
3. Set sum=0, sd=0.
4. Find single digit in sd as n % 10. ( It will give left most digit).
5. Construct sum as sum+sd
6. Decrement n by 1
7. Is n is greater than zero, if yes go to step 5, otherwise next step
8. Print sum.
9. Stop.

PROGRAM:

echo "enter a number:"


read n
sum=0
sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
sum=`expr $sum + $sd`
n=`expr $n / 10`
done
echo "sum of digits for number is" $sum

OUTPUT:

[login45@localhost ~]$ sh sum.sh


enter a number:
1234
sum of digits for number is 10

RESULT:
Thus the shell script to find the sum of digits of a given number, using while loop, was
executed successfully.

24
2.C.4 REVERSING THE NUMBER

AIM:
To write and execute a shell script to find the reverse of a given number, using until
loop.

ALGORITHM:

1. Start.
2. Input number n.
3. Set rev=0, sd=0.
4. Repeat the following steps until n=0.
4.1. Find single digit in sd as n % 10. ( It will give left most digit)
4.2. Construct reverse no as rev * 10 + sd
4.3. Decrement n by 1
4.4. Is n is greater than zero, if yes go to step 3, otherwise next step
5. Print rev.
6. Stop.

PROGRAM:
echo "enter the number to be reversed:"
read n
rev=0
sd=0
until test $n = 0
do
sd=`expr $n % 10`
rev=`expr $rev \* 10 + $sd`
n=`expr $n / 10`
done
echo "Reverse numberis $rev"

OUTPUT:

[login45@localhost ~]$ sh rev.sh


enter the number to be reversed:
123
Reverse numberis 321

RESULT:
Thus the shell script to find the reverse of digits of a given number, using until loop,
was executed successfully.

25
3.A. POINTERS IN ONE- DIMENSIONAL ARRAY

AIM:

To write a Program using pointers to compute the sum of all elements stored in an array.

ALGORITHM:
1. Start
2. Get the Element and Value and Display the Address.
3. Increment every Array Pointer
4. Point it to the next Element.
5. Add one to p each time it goes through the loop.
6. Stop.

PROGRAM:

#include<stdio.h>
main()
{
int *p, sum, i;
static int x[5] = {5,9,6,3,7};
i = 0;
p = x;
sum = 0;
printf("element value address\n\n");
while(i < 5)
{
printf(" x[%d] %d %u\n", i, *p, p);
sum = sum + *p;
i++, p++;
}
printf("\n sum = %d\n", sum);
printf("\n &x[0] = %u\n", &x[0]);
printf("\n p = %u\n", p);
}

26
OUTPUT:
[login45@localhost ~]$ ./a.out 16,30 All
element value address 15,2 All

x[0] 5 134518356 13,16 All


x[1] 9 134518360 12,44 All
x[2] 6 134518364 11,2 All
x[3] 3 134518368 10,13 All
x[4] 7 134518372 9,37 All

sum = 30 -- 7,7 All

&x[0] = 134518356 p = 134518376

RESULT:
Thus a Program is written using pointers to compute the sum of all
elements stored in an array.

3.B.POINTERS AS FUNCTION PARAMETERS

AIM:

27
To write a function using pointers to exchange the values stored in two locations in the
memory.

ALGORITHM:
1. Start
2. Initialize the values with Variables
3. The Function exchange() receives the addresses of the Variables x and y and
exchanges their contents.
4. Stop

PROGRAM:

#include<stdio.h>
main()
{
int x, y;
x = 100;
y = 200;
printf("before exchange : x = %d y = %d\n\n", x, y);
exchange(&x,&y);
printf("after exchange : x = %d y = %d\n\n", x, y);
}
exchange(a,b)
int *a, *b;
{
int t;
t = *a;
*a = *b;
*b = t;
}

OUTPUT

[login45@localhost ~]$ cc fp.c


[login45@localhost ~]$ ./a.out
before exchange : x = 100 y = 200

after exchange : x = 200 y = 100

RESULT:
Thus a function using pointers is written to exchange the values stored in two
locations in the memory.

3.C.WRITING TO AND READING FROM A FILE

AIM:
To write a program to read data from the keyboard ,write it to a file called INPUT ,

28
again read the same data from the INPUT file, and display it on the screen.

ALGORITHM:
1. Start
2. Enter the Input Data.
3. Program writes it character by character, to the file INPUT.
4. End of Data is indicated by by entering an EOF character, which is control- D.
5. The file INPUT is closed at the signal.
6. File INPUT is Reopened for reading
PROGRAM:

#include<stdio.h>
main()
{
FILE *f1;
char c;
printf("data input\n\n");
f1 = fopen("INPUT", "w");
while((c=getchar()) != EOF)
putc(c,f1);
fclose(f1);
printf("\ndata output\n\n");
f1 = fopen("INPUT", "r");
while((c=getc(f1)) != EOF)
printf("%c",c);
fclose(f1);
}

OUTPUT:
[login45@localhost ~]$ ./a.out
data input
hai ^D

data output
hai

RESULT:
Thus a program is written to read data from the keyboard, write it to a file called
INPUT, again read the same data from the INPUT file, and display it on the screen.

3.D.USE OF malloc FUNCTION


AIM:
To write a program that uses a table of integers whose size will be specified interactively at
run time.

29
ALGORITHM:

1. Start
2. Test for availability of memory space of required size.
3. If it is available , then the required space is allocated and the address of the first
byte of the space allocated is displayed.
4. Stop

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
#define NULL 0
main()
{
int *p, *table;
int size;
printf("\nwhat is the size of table ?");
scanf("%d", size);
printf("\n");
if((table = (int *)malloc(size * sizeof(int))) == NULL)
{
printf("no space available \n");
exit(1);
}
printf("\naddress of the first byte is %u\n",table);
printf("\ninput table values\n");
for(p = table; p < table + size; p++)
scanf("%d", p);
for(p = table + size -1; p >= table; p--)
printf("%d is stored at address %u \n", *p, p);
}

OUTPUT:

[login45@localhost ~]$ cc malloc.c


[login45@localhost ~]$ ./a.out
what is the size of table ?2

30
what is the size of table ?2
Address of the first byte is 2262
Input table values
11 12
12 is stored at address 2263
11 is stored at address 2264

RESULT:
Thus a program is written that uses a table of integers whose size will be specified
interactively at run time.

3.E. HANDLING OF INTEGER DATA FILES

AIM:
To write a program to read a series of integer numbers and then write all odd
numbers to a file to be called ODD and all even numbers to a file to be called EVEN.

ALGORITHM:
1. start
2. Define three File Pointers f1, f2, f3.

31
3. DATA containing Integer values is created.
4. Open the Files.
5. DATA for reading, ODD and EVEN for writing.
6. Stop

PROGRAM:

#include<stdio.h>
main()
{
FILE *f1, *f2, *f3;
int number, i;
printf("contents of DATA file\n\n");
f1 = fopen("DATA", "w");
for(i = 1;i <= 30; i++)
{
scanf("%d", &number);
if(number == -1) break;
putw(number,f1);
}
fclose(f1);
f1 = fopen("DATA", "r");
f2 = fopen("ODD", "w");
f3 = fopen("EVEN", "w");
while((number = getw(f1)) != EOF)
{
if(number %2 == 0)
putw(number, f3);
else
putw(number, f2);
}
fclose(f1);
fclose(f2);
fclose(f3);
f3 = fopen("ODD", "r");
f3 = fopen("EVEN", "r");
printf("\n\ncontents of ODD file\n\n");
while((number = getw(f2)) != EOF)
printf("%4d", number);
printf("\n\ncontents of EVEN file\n\n");
while((number = getw(f3)) != EOF)
printf("%4d", number);
fclose(f2);
fclose(f3);
}

32
OUTPUT:
[login45@localhost ~]$ cc file.c
[login45@localhost ~]$ ./a.out
contents of DATA file
111 222 333 444 555 666 777 888
contents of ODD file
111 333 555 777
contents of EVEN file
222 444 666 888

RESULT:

Thus a program is written to read a series of integer numbers and then write all odd
numbers to a file to be called ODD and all even numbers to a file to be called EVEN

33

Das könnte Ihnen auch gefallen