COMPUTER PROGRAMMING LAB-II
Dept :Mechanical I Year
Section:A&B
Program list:
Introduction to Unix
VI editor
Basic Unix Commands
Shell Programs
Sum Of Two Numbers
Greatest Of Three Numbers
Reverse Number
Sum of digit
Sum Of N Numbers
PayRoll Calculation
Menu Driven Using Switch Case
Unix In C Programs:
Factorial of given number
Fibonacci Series
Swapping of two numbers
Dynamic Memory Allocation
File Handling
INTRODUCTION ABOUT UNIX OS
UNIX is a computer operating system. An operating system is the program that controls all the other parts of a computer system, both the hardware and the software. It allocates the computer's resources and schedules tasks. It allows you to make use of the facilities provided by the system. Every computer requires an operating system. UNIX is a multi-user, multi-tasking operating system. Multiple users may have multiple tasks running simultaneously. This is very different than PC operating systems.
UNIX is a machine independent operating system. Not specific to just one type of computer hardware. Designed from the beginning to be independent of the computer hardware. UNIX is a software development environment. Was born in and designed to function within this type of environment. The "UNIX" trademark, previously owned by AT&T and then deeded to UNIX Systems Laboratories (USL), an AT&T subsidiary, passed to Novell when it acquired USL. After a brief period of negotiations with rival Unix vendors Sun Microsystems, Santa Cruz Operation, International Business Machines, and Hewlett-Packard, Novell granted exclusive licensing rights to the UNIX trademark to X/Open Co. Ltd., an Open Systems industry standards branding agent based in the United Kingdom. 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). 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
Whenever you login to a Unix system you are placed in a shell program. The shell's prompt is usually visible at the cursor's position on your screen. To get your work done, you enter commands at this prompt. The shell is a command interpreter; it takes each command and passes it to the operating system kernel to be acted upon. It then displays the results of this operation on your screen. Several shells are usually available on any UNIX system, each with its own strengths and weaknesses. Different users may use different shells. Initially, your system adminstrator will supply a default shell, which can be overridden or changed. The most commonly available shells are: Bourne shell (sh)
C shell (csh)
Korn shell (ksh)
TC Shell (tcsh)
Bourne Again Shell (bash) Each shell also includes its own programming language. Command files, called "shell scripts" are used to accomplish a series of tasks.
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:
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 undergraduate 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"
UNIX: vi Editor
General Introduction
The vi editor (short for visual editor) is a screen editor which is available on almost all Unix systems. Once you have learned vi, you will find that it is a fast and powerful editor. vi has no menus but instead uses combinations of keystrokes in order to accomplish commands. If you are just beginning to learn Unix, you might find the Pico editor easier to use (most command options are displayed at the bottom of the screen). If you use the Pine email application and have composed or replied to a message you have probably already used Pico as it is used for text entry. For more information please refer to the Pine/Pico page.
Starting vi
To start using vi, at the Unix prompt type vi followed by a file name. If you wish to edit an existing file, type in its name; if you are creating a new file, type in the name you wish to give to the new file.
%vi filename
Then hit Return. You will see a screen similar to the one below which shows blank lines with tildes and the name and status of the file.
~
~
"myfile" [New file]
Entering Text
To begin entering text in an empty file, you must first change from the command mode to the insert mode. To do this, type the letter i. When you start typing, anything you type will be entered into the file. Type a few short lines and hit Return at the end of each of line. Unlike word processors, vi does not use word wrap. It will break a line at the edge of the screen. If you make a mistake, you can use the Backspace key to remove your errors. If the Backspace key doesn't work properly on your system, try using the Ctrl h key combination.
Shortcuts
Two short cuts for moving quickly on a line include the $ and the 0 (zero) keys. The $ key will move you to the end of a line, while the 0 will move you quickly to the beginning of a line.
Screen Movement
To move the cursor to a line within your current screen use the following keys:
H moves the cursor to the top line of the screen.
M moves the cursor to the middle line of the screen.
L moves the cursor to the last line of the screen.
To scroll through the file and see other screens use:
ctrl-f scrolls down one screen
ctrl-b scrolls up one screen
ctrl-u scrolls up a half a screen
ctrl-d scrolls down a half a screen
Two other useful commands for moving quickly from one end to the other of a document are G to move to the end of the file and 1G to move to the beginning of the file. If you precede G with a number, you can move to a specific line in the document (e.g. 15G would move you to line 15).
Closing and Saving Files
When you edit a file in vi, you are actually editing a copy of the file rather than the original. The following sections describe methods you might use when closing a file, quitting vi, or both.
Quitting and Saving a File
The command ZZ (notice that it is in uppercase) will allow you to quit vi and save the edits made to a file. You will then return to a Unix prompt. Note that you can also use the following commands:
:w to save your file but not quit vi (this is good to do periodically in
case of machine crash!).
:q to quit if you haven't made any edits.
:wq to quit and save edits (basically the same as ZZ).
Quitting without Saving Edits
Sometimes, when you create a mess (when you first start using vi this is easy to do!) you may wish to erase all edits made to the file and either start over or quit. To do this, you can choose from the following two commands:
:e! reads the original file back in so that you can start over.
:q! wipes out all edits and allows you to exit from vi.
A Quick Word about Customizing Your vi Environment
Useful vi Commands
Cut/Paste Commands:
x delete one character (destructive backspace)
dw delete the current word (Note: ndw deletes n numbered words)
dd delete the current line (Note: ndd deletes n numbered lines)
D delete all content to the right of the cursor
d$ same as above
:u undo last command
p,P paste line starting one line below/above current cursor location
J combine the contents of two lines
"[a-z]nyy yank next n lines into named buffer [a-z]
"[a-z]p/P place the contents of selected buffer below/above the current line
Cursor Relocation commands:
:[n] goto line [n]
shift g place cursor on last line of text
h/l/j/k move cursor left, right, down and up
^f/^b move forward, backward in text, one page
^u/^d move up, down one half page
$ move to end of line
0 move to beginning of line
Extensions to the Above:
b move backwards one word (Note: nb moves back n number of words)
e move to end of current word
( move to beginning of curent block
) move to the end of current block
Searching and Substitution commands:
/ [string] search forward for string
? [string] search backwards for string
n repeat last search
N repeat search in opposite direction
cw change the contents of the current word, (use ESC to stop
replacement mode)
c$ Replace all content to the right of cursor (exit replacement
mode with ESC)
c0 Replace all content to the left of cursor (exit with ESC)
:1,$s/s1/s2/g (Yow!) global replacement of string1 with string2
r replace current character with next character typed
Entering the Insert Mode:
i Begin inserting text at current cursor location
I Begin inserting text at the beginning of the current line
a Begin appending text, one character to the right of current
cursor location
A Begin appending text at the end of the current line
o/O Begin entering text one line below\above current line
ESC Exit insertion mode and return to command mode
Exiting and Entering VI
ZZ save file and exit VI
:wq same as above
:e! return to last saved version of current file
:q quit without save, (Note :q! is required if changes have been made)
:w write without exit (:w! to force write)
OUTPUT
1. COMMAND :date
OUTPUT :[mech@serverlinux mech]$ date
Fri Mar 5 15:32:40 IST 2010
2. COMMAND :cal
OUTPUT :[mech@serverlinux mech]$ cal
March 2010
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
3.COMMAND : echo.
OUTPUT :[mech@serverlinux mech]$ echo welcome to tce
welcome to tce
4. COMMAND : who.
OUTPUT :[mech@serverlinux mech]$ who
s08cse211 pts/45 Mar 5 14:01 (192.168.100.124)
s08cse42 pts/44 Mar 5 15:22 (192.168.101.61)
mech pts/46 Mar 5 15:28 (192.168.100.140)
s08cse56 pts/50 Mar 5 13:53 (192.168.101.23)
s08cse48 pts/49 Mar 5 15:20 (192.168.100.160)
5. COMMAND :who am i
OUTPUT :[ mech @serverlinux mech]$ who am i
serverlinux!mech pts/46 Mar 5 15:28 (192.168.100.140)
6. COMMAND :list
OUTPUT :[mech@serverlinux mech]$ ls
anil mech1 ex1 hari
mech ex1 ex2 ss
7.a)COMMAND :mkdir directory
OUTPUT :[mech@serverlinux mech]$ mkdir xyz
[mech@serverlinux mech]$ ls
anil mech1 ex1 hari xyz
mech ex1 ex2 ss
b)COMMAND :cd directory
OUTPUT :[mech@serverlinux mech]$ cd xyz
[mech@serverlinux xyz]$
c)COMMAND :cd directory
OUTPUT :[mech@serverlinux xyz]$ cd
[mech@serverlinux mech]$
d)COMMAND :rmdir directory
OUTPUT :[mech@serverlinux mech]$ rmdir xyz
[mech@serverlinux mech]$ ls
anil mech1 ex1 hari
mech ex1 ex2 ss
8.a)COMMAND :cat
OUTPUT :[mech@serverlinux mech]$ cat > e1
Welcome
To
Mechmobile department
[mech@serverlinux mech]$ ls
anil mech1 e1 ex1 ss
mech ex1 ex1 hari
b) COMMAND :cat
OUTPUT :[mech@serverlinux mech]$ cat e1
Welcome
To
Mechmobile department
c)COMMAND :remove file
OUTPUT :[mech@serverlinux mech]$ rm e1
[mech@serverlinux mech]$ ls
anil mech1 ex1 hari
mech ex1 ex2 ss
d)COMMAND :remove file
OUTPUT :[mech@serverlinux mech]$ rm ex1
[mech@serverlinux mech]$ rm -i ex1
rm: remove `ex1'? y
[mech@serverlinux mech]$ ls
anil mech1 ex2 ss
mech ex1 hari
9.COMMAND :copy
OUTPUT : [mech@serverlinux mech]$ cat > e1
Welcome
[mech@serverlinux mech]$ cat > e2
Hai
[mech@serverlinux mech]$ cp e1 e2
[mech@serverlinux mech]$ cat e2
Welcome
[mech@serverlinux mech]$ ls
anil mech1 e2 ex2 ss
mech e1 ex1 hari
10.COMMAND :move
OUTPUT :[mech@serverlinux mech]$ cat > e3
hello
[mech@serverlinux mech]$ mv e1 e3
[mech@serverlinux mech]$ cat e3
Welcome
[mech@serverlinux mech]$ ls
anil mech1 e3 ex2 ss
mech e2 ex1 hari
11.a)COMMAND :head
OUTPUT :[mech@serverlinux mech]$ cat > e1
Welcome
To
Mechmobile department
[mech@serverlinux mech]$ head -1 e1
Welcome
[mech@serverlinux mech]$ head -2 e1
Welcome
To
[mech@serverlinux mech]$ head -3 e1
Welcome
To
Mechmobile department
b)COMMAND :tail
OUTPUT : [mech@serverlinux mech]$ tail -1 e1
Mechmobile department
[mech@serverlinux mech]$ tail -2 e1
To
Mechmobile department
[mech@serverlinux mech]$ tail -3 e1
Welcome
To
Mechmobile department
12.COMMAND :sort
OUTPUT :[mech@serverlinux mech]$ sort e1
Mechmobile department
To
Welcome
13.COMMAND :word count
OUTPUT :[mech@serverlinux mech]$ wc e1
3 4 33 e1
14. COMMAND :pwd
OUTPUT :[mech@serverlinux mech]$ pwd
/home/mech
15.COMMAND :command grouping
OUTPUT :[mech@serverlinux mech]$ pwd;wc e1
/home/mech
3 4 33 e1
shell programs
Sum of two numbers
Program:
[mech@serverlinux mech]$ vi addtwo.sh
echo enter two numbers
read a b
c=`expr $a + $b`
echo sum =$c
Output:
[mech@serverlinux mech]$ sh addtwo.sh
enter two number
3 4
sum=7
[mech@serverlinux mech]$
GREATEST OF THREE NUMBERS
Program:
[mech@serverlinux mech]$ vi greatestthree.sh
echo "enter any three numbers"
read a b c
if [ $a -gt $b -a $a -gt $c ]
then
echo $a is big
elif [ $b -gt $a -a $b -gt $c ]
then
echo $b is big
else
echo $c is big
fi
Output:
[mech@serverlinux mech]$ sh greatestthree.sh
enter any three numbers
3 4 5
5 is big
[mech@serverlinux mech]$
Reverse Number
Program:
[mech@serverlinux mech]$ vi reversenum.sh
echo enter a value
read n
a=0
while [ $n -gt 0 ]
do
r=`expr $n \% 10`
a=`expr $a \* 10 + $r`
n=`expr $n \/ 10`
done
echo reverse no= $a
Output:
[mech@serverlinux mech]$ sh reversenum.sh
enter a value
345
reverse no= 543
Sum of Digit
Program:
[mech@serverlinux mech]$ vi sumofdigit.sh
echo enter a number
read n
s=0
while [ "$n" -gt "0" ]
do
r=`expr $n % 10`
s=`expr $s + $r`
n=`expr $n / 10`
done
echo sum of $n is $s
Output:
[mech@serverlinux mech]$ sh sumofdigit.sh
enter a number
234
sum of 0 is 9
SUM OF N NUMBERS
Program:
[mech@serverlinux mech]$ vi sumnnum.sh
echo enter the numbers
read n
sum=0
for (( i=1;i<=$n;i++ ))
do
sum=`expr $sum + $i`
done
echo $sum is sum of $n numbers
Output:
[mech@serverlinux mech]$ sh sumnnum.sh
enter the numbers
3
6 is sum of 3 numbers
[mech@serverlinux mech]$
Payroll Calculation
Program:
[mech@serverlinux mech]$ vi payroll.sh
echo enter the employee name
read name
echo enter the basic pay
read a
hra=`expr $a "*" 3 / 100`
cca=`expr $a "*" 5 / 100`
ns=`expr $a + $hra + $cca`
echo the employee net salary is $ns
Output:
[mech@serverlinux mech]$ sh payroll.sh
enter the employee name
kannan
enter the basic pay
20000
the employee net salary is 21600
Menu Driven using switch case
Program:
[mech@serverlinux mech]$vi menudriven.sh
echo 1.Addition
echo 2.Subtraction
echo 3.Multiplication
echo 4.Division
read ch
echo enter two numbers
read a b
case $ch in
1)c=`expr $a + $b`
echo sum=$c;;
2)c=`expr $a - $b`
echo difference =$c;;
3)c=`expr $a "*" $b`
echo product= $c;;
4)c=`expr $a \/ $b`
echo quotient =$c;;
esac
Output:
[mech@serverlinux mech]$ sh menudriven.sh
1.Addition
2.Subtraction
3.Multiplication
4.Division
1
enter two numbers
2 3
sum=5
[mech@serverlinux mech]$ sh menudriven.sh
1.Addition
2.Subtraction
3.Multiplication
4.Division
2
enter two numbers
4 3
difference =1
[mech@serverlinux mech]$ sh menudriven.sh
1.Addition
2.Subtraction
3.Multiplication
4.Division
3
enter two numbers
3 4
product= 12
[mech@serverlinux mech]$ sh menudriven.sh
1.Addition
2.Subtraction
3.Multiplication
4.Division
4
enter two numbers
4 2
UNIX IN C PROGRAMMING
Factorial of a Given Number
Program:
[mech@serverlinux mech]$ vi fact83.c
#include
main()
{
int n;
void fact(int);
printf("Enter the number");
scanf("%d",&n);
fact(n);
} fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("Factorial of number is %d",f);
}
Output:
[mech@serverlinux mech]$ cc fact83.c
[mech@serverlinux mech]$ ./a.out
Enter the number
3
Factorial of number is 6
Fibonacci Series
Program:
[mech@serverlinux mech]$ vi fib61.c
#include
main()
{
int n;
void fibo(int);
printf("\n Enter the number: ");
scanf("%d",&n);
fibo(n);
}
void fibo(int n)
{
int i, a=0, b=1, c;
printf("Fibonacci series is \n");
printf("%d\n",a);
printf("%d\n",b);
for(i=2;i<=n;i++)
{
c=a+b;
a=b;
b=c;
printf("%d\n",c);
}
}
Output:
[mech@serverlinux mech]$ cc fib61.c
[mech@serverlinux mech]$ ./a.out
Enter the number: 6
Fibonacci series is
0
1
1
2
3
5
8
[mech@serverlinux mech]$
SWAPPING OF TWO NUMBERS
Program:
[mech@serverlinux mech]$ vi swap83.c
#include
int swap(int*,int*);
main()
{
int x,y;
printf("Enter the Number");
scanf("%d%d",&x,&y);
printf("\n The values before swapping are %d%d",x,y);
swap(&x,&y);
printf("\n the values after swapping are %d%d\n",x,y);
}
int swap(int *a,int *b)
{
int z;
z=*a;
*a=*b;
*b=z;
}
Output:
[mech@serverlinux mech]$ cc swap83.c
[mech@serverlinux mech]$ ./a.out
Enter the Number 5 6
The values before swapping are 56
the values after swapping are 65
[mech@serverlinux mech]$
DYNAMIC MEMORY ALLOCATION
Program:
[mech@serverlinux mech]$vi dma.c
#include
#include
main()
{
int number;
int *ptr;
int i;
printf("How many ints would u like to store?");
scanf("%d",&number);
ptr = malloc(number*sizeof(int));
if(ptr!=NULL)
{
for(i=0;i0;i--)
{
printf("%d\n",*(ptr+(i-1)));
}
free(ptr);
return 0;
}
Output:
[mech@serverlinux mech]$ cc dma.c
[mech@serverlinux mech]$ ./a.out
How many ints would u like to store?5
4
3
2
1
0
[mech@serverlinux mech]$
FILE HANDLING
Program:
[mech@serverlinux mech]$vi file.c
#include
main()
{
FILE *fp;
char c;
fp=fopen("data.txt","w");
printf("Data i/p \n");
while((c=getchar())!='*')
putc(c,fp);
fclose(fp);
fp=fopen("data.txt","r");
printf("data o/p \n");
while((c=getc(fp))!=EOF)
printf("%c",c);
fclose(fp);
}
OUTPUT:
[mech@serverlinux mech]$ cc file.c
[mech@serverlinux mech]$ ./a.out
Data i/p
welcome to tce
*
data o/p
welcome to tce