UNIX Lab Exp

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 46

STUDY ON UNIX

Ex No: 1
Date:

AIM:
To perform a study on UNIX

An operating system is the software component of the computer system that is


responsible for the management and coordination of activities and the sharing the limited
resources effectively. The figure 1 shows the layered structure of the system and where the
operating system is located in it.

Fig 1. Layered Structure

Operating systems offer a number of services to application programs and users. Users may
also interact with the operating system with some kind of software user interface (UI) like
typing commands by using command line interface (CLI) or using a graphical user interface
(GUI). For hand-held and desktop computers, the user interface is generally considered part of
the operating system. On large multi-user systems like UNIX and Unix-like systems, the user
interface is generally implemented as an application program that runs outside the operating
system.

There are basically two types of operating system.


1. Single user operating system
2. Multi user operating system

In single user operating system only one person can use the system at the same time. The
examples are DOS, Windows 95 and Windows 98.
In multi-user operating system more than one person can use the system at the same time. The
examples are UNIX, LINUX and WINDOWS NT etc.

1
The UNIX operating system is made up of two major parts, the kernel and the shell.

a) The kernel

The kernel of UNIX is the hub of the operating system: it allocates time and memory to
programs and handles the file store 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.

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

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.

THE DIRECTORY STRUCTURE


A file is a collection of information that is assigned a name that is used to identify the file.
Files are grouped under directory to avoid cluttering of files. A directory can have one or more
directories in it called sub–directories. In UNIX files and directories are arranged in a
hierarchical manner. The top of the hierarchy is traditionally called root.

LOGGING IN AND LOGGING OUT


These are the security for the system with many users.
Logging into a UNIX system requires two information. They are

2
1. User name
2. Password

Logging out is done if we want to quit. The command used for this is exit.

1. ADVANTAGES OF UNIX OPERATING SYSTEM

1. UNIX is more flexible and can be installed on many different types of machines, including
mainframe computers, supercomputers and microcomputers.
2. UNIX is more stable and does not go down as often as Windows does, therefore requires
less administration and maintenance.
3. UNIX has greater built-in security and permissions features than Windows.
4. UNIX possesses much greater processing power than Windows.

RESULT:

Thus basic of UNIX Commands was studied.

3
Ex.No:2 BASIC UNIX COMMANDS
Date:

1.Date command
The date command tells us the current date and time
Format: $date Eg:$date
The date command can also be used with the following format specification.
$date +%m : To display only month
$date +%h : To display month name
$date +%y : To display last two digits of the year
$date +%H : To display Hours
$date +%M : To display Minutes
$date +%S : To display Seconds
2.who command
This command gives us the details of who all have logged into the UNIX system
currently.
Format:$who Example: $who am I
This tells us to when we had logged in and the system’s name for connection
being used.
3.man command
This command prints manual page.
Format :$man<command name> Example:$man who
4.pwd command
It tells us the full path for the current directory
Format:$pwd
5.ls command
The ls command displays the list of files in the current directory.
Format :$ls
Various options for ls command
ls -l :List files in login format. The files are displayed along with their mode,
number of links, owner of files, file size, modification date &time and
file name.
ls -t : Lists in order of last modification time
ls –a : List all entries, including hidden files.
ls – d : Lists directory files instead of contents.
ls –p : puts a slash after each directory.
ls –u : Lists in order of last access time
6.mkdir command
This command helps us to make a directory.
Format :$mkdir<directory name>
Example:$mkdir abc
7.rmdir command
This command is used to remove a directory from the disk.
Format :$rmdir<directory name>
Example:$rmdir abc
8.cd command
This command is used to move from one directory to another.

4
Format:$cd<directory name>
Example:$cd abc

9.cat command
This command is used to create a file.
Format:$cat[path]filename
Example :$cat xyz
$cat>abc
Have a nice day
Ctrl d
10.cp command
This command helps us to create duplicate copies of ordinary files.
Format:$cp[path]source filename [path]destination filename
Example:$cp abc def
11.ln command
This command is used to establish an additional file name for the same ordinary file.
Format:$ln oldfilename newfilename
Example:$ln abc def
12.mv command
This command move a file from one place to another place.
Format :$mv source destination
Example: $mv abc def
13.rm command
This command is used to remove one or more files from a directory. This can be used
to delete all files as well as the directory.
Format: $rm[path]file
rm –i asks the user if he wants to delete the files mentioned.
rm –r recursively delete the entire contents of directory as well as the
directory itself
14.echo command
This command is used to display whatever message we want to display on the screen.
Format:$echo”message”
Example:$echo “learning UNIX is easy”
15.grep command
The grep utility searches one or more files to see if any contain a specified string of
characters.
Format: grep’string’filename
Example:$grep ’lily’ flower
16.diff command
The diff utility compares two files and displays a list of the difference between them.
It displays the list of actions to be taken to convert one file into another.
Format: $diff filename1 filename2
Example:$diff flower1 flower2
17.read command
This command is used in shell scripts.this command waits for the user to input the
value of the variable.
Format: $read variablename
18. clear/tput clear commands

5
The clear/tput clear utility clears the screen.
Format:$clear
$tput clear

19.exit command
Press(ctrl+D) in response to the shell prompt to logout.
Format:$exit

6
Ex No:3 SHELL PROGRAMMING
Date:

A Linux shell is a command language interpreter, the primary purpose of which is to


translate the command lines typed at the terminal into system actions. The shell itself is a
program, through which other programs are invoked

What is a shell script ?


• A shell script is a file containing a list of commands to be executed by the Linux shell.
shell script provides the ability to create your own customized Linux commands
• Linux shell have sophisticated programming capabilities which makes shell script
powerful Linux tools

How to work with shell ?

Step1:
In the dollar prompt type
$ vi < file name>
Where vi is the editor ,it will open a new window in which you can type the program you want

Step2:
After typing the program press ESC and : together then at the bottom of the vi screen you can
see i.e. prompt .In that type as wq which means write and quit i.e. the content what is typed
will be written and saved into that file that has been created

Step3:
Once wq is typed at the : prompt ,the prompt would change to $ symbol in which you have to
do the following

$ sh < file name >

Sh – command is used to run the shell program


<file name> - is the name of the file for which the output is to be got

Basically to print a text in the your shell programs echo command is used

SYNTAX FOR LOOPING STATEMENTS

IF –THEN-ELSE CONSTRUCT

if [ condition]

then <action>
else
statements

7
fi (end of if)

WHILE
while <condition>
do
<statements>
Done

CASE

Case $<option> in
1) <statements>;;
2) <statements>;;
3) ..
4)
.
.
.
*) <error statement>;;
esac

For loop

For(( intitialization;condition;incremetation/decrementation))

8
Ex No 3.a DISPLAYING WISHES
Date:

AIM:
To write a shell program to display the wishes based on the time.

ALGORITHM:

1.Find the time


2.Based on the time display the wishes as either good morning or good afternoon or
good evening or good night
3.Display both time and wishes
4.Terminate the process

PROGRAM:

d=`date +%H`
echo $d
[ $d -gt 00 -a $d -lt 12 ] && echo "Good Morning"
[ $d -lt 16 -a $d -gt 12 ] && echo "Good Afternoon"
[ $d -gt 19 -a $d -lt 19 ] && echo "Good Evening"
[ $d -gt 19 -a $d -lt 23 ] && echo "Good Night"

OUTPUT

RESULT:
Thus the time was found and a wish was displayed using the shell program.

9
Ex no: 3b BIGGEST OF TWO NUMBERS
Date:

AIM:
To write a shell program to find the bigger of two numbers.

ALGORITHM:

 Start the program


 Read the 2 numbers a & b
 Check whether ‘a’ is greater than ‘b’. If true, display ‘a’ is greater
 Or display “b” is greater.
 Terminate

PROGRAM:

echo enter the first no


read a
echo enter the second no
read b
if [ $a -gt $b ]
then echo the biggest no is $a
else echo the biggest no is $b
fi

OUTPUT

Enter The First No 4

Enter The Second No 3

The Biggest No Is 4

RESULT:
Thus the bigger of 2 numbers was found using the shell program

10
ExNo3.c BIGGEST OF THREE NUMBERS
Date:

AIM:
To write a shell program to find the biggest of three numbers.

ALGORITHM:

 Start the program


 Read the three numbers a, b, c
 Check if a > b and a > c
 If true, display ‘a’ is greater
 Or check if b > c
 If true, display ‘ b’ is greater
 Or display ‘ c ‘ is greater
 Terminate

PROGRAM:

echo Enter the first number:


read a
echo Enter the second number:
read b
echo Enter the third number:
read c
if [ $a -gt $b -a $a -gt $c ]
then
echo "$a is greater."
elif [ $b -gt $c ]
then
echo " $b is greater. "
else
echo "$c is greater."
Fi

OUTPUT

Enter The First No 4


Enter The Second No 3
Enter The Third No 5

5 Is Greater

RESULT:

Thus the biggest of 3 numbers was found using the shell program.

11
Ex No.3d STRING COMPARISON
Date:

AIM:

To write a shell program for performing string comparison

ALGORITHM:

 Start the program


 Read the two strings
 Check if they are equal
 If true, display ‘ the strings are equal’
 Or display ‘the strings are not equal’
 Terminate

PROGRAM

echo enter string 1


read s1
echo enter string2
read s2
if [ $s1 == $s2 ]
then
echo the given string are equal
else
echo The given strings are not equal
fi

OUTPUT

Enter string 1 : unix


Enter string 2 :linux

The given strings are not equal

RESULT:

Thus two strings were compared using the shell program

12
Ex no : 3e ARITHMETIC OPERATIONS
Date:

AIM:
To write a shell program to perform arithmetic operations using switch statement

ALGORITHM:

1. Enter the input


2. Enter the choice
3. Perform corresponding arithmetic operation on the inputs
4. Display the result

PROGRAM:

echo "enter the first no:"


read a
echo "enter the second no:"
read b
echo "enter ur choice"
read n
case $n in
1) echo "addition" ;
c=`expr $a + $b `;
echo "The sum is $c." ;
exit ;;
2) echo "subtraction" ;
c=`expr $a - $b `;
echo "The difference is $c." ;
exit ;;
3) echo "multiplication" ;
c=`expr $a \* $b `;
echo "The product is $c." ;
exit ;;
4) echo "division" ;
c=`expr $a / $b `;
echo "The quotient is $c." ;
exit ;;
*) echo "Invalid" ;
esac;;

13
OUTPUT

Enter the first no: 10


Enter the second no: 2
Enter ur choice : 1
The sum is 12

Enter the first no:10


Enter the second no:2
Enter ur choice 2
The difference is 8

Enter the first no:10


Enter the second no:2
Enter ur choice 3
The product is 20

Enter the first no: 10


Enter the second no: 2
Enter ur choice 4
The quotient is 5

Enter the first no:10


Enter the second no: 2
Enter ur choice *
Invalid

RESULT:

Thus the arithmetic operations were performed using the shell program.

14
Ex No: 3f SUM OF N EVEN NUMBERS
Date:

AIM:
To write a shell program for calculating the sum of ‘ n ‘ even numbers

ALGORITHM:

1.Read the value of ‘ n ‘


2.Initialize the variables ‘sum’ and ‘i’ as zero
3.Using while loop, increment the value if ‘i’ by 2
4.Calculate the value of sum
5.Display the result
6.Terminate

PROGRAM:

echo -----------------------
echo Sum of 'n' even numbers
echo -----------------------
echo enter the value of n
read n
sum=0
i=2
while [ $i -le $n ]
do
sum=`expr $sum + $i`
i=`expr $i + 2`
done
echo The sum of even numbers upto $n is $sum

OUTPUT

Sum of 'n' even numbers

Enter The Value Of 5


The sum of even numbers upto 5 is 6

RESULT:

Thus the sum of even numbers upto n was found using the shell program.

15
Ex No:3g SUM OF N NATURAL NUMBERS
Date:

AIM:

To write a shell program for calculating the sum of ‘ n ‘ natural numbers

ALGORITHM:

1. Read the value of ‘ n ‘


2. Initialize the variables ‘sum’ and ‘i’ as zero
3. Using while loop, increment the value if ‘i’
4. Calculate the value of sum
5. Display the result
6. Terminate

PROGRAM:

echo --------------------------
echo Sum of 'n' natural numbers
echo --------------------------
echo Enter the value of n
read n
sum=0
i=0
while [ $i -le $n ]
do
sum=`expr $sum + $i`
i=`expr $i + 1`
done
echo The sum of first $n natural numbers is $sum

OUTPUT

Sum of 'n' natural numbers

Enter The Value Of 5


The sum of first 5 natural numbers is 15

RESULT:

Thus the sum of ‘ n ‘ natural numbers was found using the shell program.

16
Ex No: 3h GENERATION OF FIBONACCI SERIES
Date:

AIM:

To write a shell program to generate Fibonacci series

ALGORITHM:

1.Initialize a and b with 0 and 1


2.Get the limit and initialize i with 0
3.Initialize i
4.Add a and b and assign to c
5.Print c
6.Assign the value of b to a and the value of c to b
7.Increment i by 1
8.Repeat the above steps until i is less than n

PROGRAM:

echo -----------------------------------
echo Generation of fibonaaci series
echo -----------------------------------
a=0
b=1
c=0
echo "Enter the limit:"
read n
i=3
echo -----------------------------
echo "FIBONACCI SERIES"
echo -----------------------------
echo $a
echo $b
for((i=0;$i<$n;i++))
{
c=` expr $a + $b `
echo $c
a=$b
b=$c
}

17
OUTPUT

Generation Of Fibonaaci Series

Enter the limit 5

FIBONACCI SERIES

0 1123

RESULT:

Thus the fibonacci series was generated using shell program .

18
VI EDITOR
Ex No: 4
Date:

AIM:
To study about the Vi Editor in Linux.

The vi editor is available on almost all Unix systems. You can use vi from any type of
connection to UNIX because it does not depend on arrow keys and function keys: it uses the
standard alphabetic keys for commands. vi is short for visual editor; it displays a window into
the file being edited that shows 24 lines of text.

MODES:
There are three basic modes of operations in VI.

a) Command mode
b) Insertion mode
c) Last Line mode

A) Command Mode:
The command mode is one which user is able to enter commands. The
command mode allows the entry of commands to manipulate text. These commands are
usually one or two characters long, and can be entered with few keystrokes.

B) Insertion Mode:
The insertion mode is one in which, the user can enter the data or edit the data.
The insert mode puts anything typed on the keyboard into the current file.

C) Last Line Mode:


The Last line mode is one in which user is able to enter special commands.

STARTING VI EDITOR:
To start using vi, at the UNIX prompt type vi followed by a file name.
$vi newname
at the Unix $ prompt, where newname is the name you wish to give the new file. On the screen
you will see blank lines, each with a tilde at the left, and a line at the bottom giving the name
and status of the file:

~
~
"testvi" [New file]

Use vi to open an already existing file by typing vi filename where filename is the name of the
existing file. If the file is not in your current directory, you must use the full pathname.

ENTERING TEXT:

19
vi has two modes: command mode and insert mode. In command mode, the letters of
the keyboard perform editing functions (like moving the cursor, deleting text, and so on). In
insert mode, the letters you type form words and sentences. Unlike word processors, vi starts
up in command mode. To begin entering text in an empty file, you must change from
command mode to insert mode. To do this, type the letter i. You may see INSERT MODE at
the bottom right of the screen, or nothing may appear to change, but you are now in insert
mode and can begin typing text. If you make a mistake, pressing the Backspace or Delete key
may or may not remove the error, depending on the configuration of the software you are using
to connect to the Login Service.

ENDING THE EDIT SESSION:

While editing, VI keeps the edited text in an area called work buffer. When editing is
finished, the user must write out the contents of the work buffer to disk file.
Keeping VI in command mode,
1. The ZZ (upper case) command can be used to write the newly entered text to the disk
and then end the editing session and returns the control to the shell.
2. To exit without saving the work, use :q! command
3. To quit after writing change to the disk file :wq command is used
4. To quit after replacing the old copy of the file with the new one, :x command is used.

COMMANDS:

a) Getting out
When we want to get out of the editor, switch to command mode(press ESC) if
necessary, then

:q Quit vi

:q! Quit vi without saving changes

:w Save and continue working in vi

:wq Save the changes and exit from vi

:x Save and exit from vi

ZZ Save the changes and exit from vi

b) Inserting Text
From command mode, these keystrokes switch you into insert mode with new text
being inserted.

20
i Invokes insert mode inserts before character

I Same as ‘i’ but insertion is at beginning of line

o Opens blank line before current line

O Same as ‘o’ but puts blank line after current line

a Same as ‘i’ but appends after cursor

A Same as ‘a’ but appends at end of line

c) Deleting Text
The following commands allow you to delete text

x Deletes one character at the cursor position

nx Delete the n ext ‘n’ characters at the cursor position

dw Deletes one word at the cursor position

n dw Deletes ‘n’ words at the cursor position

d0 Deletes from the cursor position till the beginning of the line

d$ Deletes from the cursor position till the end of the line

dd Deletes one line at the cursor position

n dd Deletes the next ‘n’ lines from the cursor position

d) Moving Around
When in command mode we can use the arrow keys to move the cursor
up,down,left,right. In addition, these keystrokes will move the cursor:

k Same as the ‘up’ arrow key


h Same as the ‘left’ arrow key
l Same as the ‘right’ arrow key
j Same as the ‘down’ arrow key
w Moves forward by a word
nw Moves forward by ‘n’ number of words

21
e Moves to the last character of this word or that of the next
ne Moves to the last character of n the next word
b Takes the user back by a word
nb Takes the user back by ‘n’ number of words
0(zero) or Takes the user to the beginning of the line
‘^’
$ Takes the user to the end of the line
nG Takes the user to the ‘n’ the line
L Takes the user to the last line

Cutting, Copying, Pasting:


From command mode, use these keystroke (or keystroke-combination) commands for
the described cut/copy/paste function:

yy Copy a line into temporary storage


‘n’yy Copy n number of lines into temporary storage
dd Move a line into temporary storage
‘n’dd Move n lines into temporary storage
p Move the text from temporary storage into the current position of cursor

Searching for text:


Instead of using the “moving around” commands above, we can go directly forward or
backward to specified text using “/” and “?”

/g Search for a pattern ‘g’ forwards


?g Search for a pattern ‘g’ backwards
/ Repeat the last search forward
? Repeat the last search backward

Replacing Text:
This amounts to combining two steps; deleting, then inserting text.

r Replace a single character at the current cursor position


R Invoke insert mode and go on replacing till <ESC> is pressed
s Deletes the current character and inserts character until <ESC> is pressed
S Removes all characters on the current line and allows the user to enter data

22
Undoing your changes:

u Undoing the previous changes

Screen Manipulation:
The following commands allow the vi editor to move up and down several lines and to
be refreshed

Ctrl-f Scrolls screen forward


Ctrl-b Scrolls screen backward
Ctrl-u Scrolls half a screen backward
Ctrl-d Scrolls half a screen forward
Ctrl-L Refreshes the screen

23
“C” PROGRAMMING

24
C Programming on UNIX

Ex No: 5: Functions in C
Date:

Function:
A function is a complete and independent program, which is used (or invoked) by the main
program or other subprograms. A subprogram receives values called arguments from a calling
program, performs calculations and returns the results to the calling program.
Advantages of using functions:
There are many advantages in using functions in a program they are:
 It facilitates top down modular programming. In this programming style, the
high level logic of the overall problem is solved first while the details of each lower level
functions is addressed later.
 The length of the source program can be reduced by using functions at appropriate
places. This factor is critical with microcomputers where memory space is limited.
 It is easy to locate and isolate a faulty function for further investigation.
 A function may be used by many other programs this means that a c programmer
can build on what others have already done, instead of starting over from scratch.
 A program can be used to avoid rewriting the same sequence of code at two or more
locations in a program. This is especially useful if the code involved is long or
complicated.
 Programming teams does a large percentage of programming. If the program is
divided into subprograms, each subprogram can be written by one or two team
members of the team rather than having the whole team to work on the complex
program
C supports the use of library functions and use defined functions. The library functions are
used to carry out a number of commonly used operations or calculations. The user-defined
functions are written by the programmer to carry out various individual tasks.
Function Definition:
Datatype functionname (argument list);
argument declaration;
{
local variable declarations;
statements;
[return expression];
}
Example:
mul(int a,int b)
{
int y;
y=a*b;
return y;
}
Types of functions:
A function may belong to any one of the following categories:
1. Functions with no arguments and no return values.

25
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
1. Functions with no arguments and no return values.
When a function has no arguments it does not receive any data from the calling function.
Similarly when it does not return value the calling function does not receive any data from the
called function. A function that does not return any value cannot be used in an expression it
can be used only as independent statement.
2. Functions with arguments but no return values:
The nature of data communication between the calling function and the arguments to
the called function and the called function does not return any values to the calling function.
3. Functions with arguments and return values:
The function of the type Arguments with return values will send arguments from the calling
function to the called function and expects the result to be returned back from the called
function back to the calling function.
Return value data type of function:
A C function returns a value of type int as the default data type when no other type is specified
explicitly. For example if function does all the calculations by using float values and if the
return statement such as return (sum); returns only the integer part of the sum. This is since we
have not specified any return type for the sum. There is the necessity in some cases it is
important to receive float or character or double data type. To enable a calling function to
receive a non-integer value from a called function we can do the two things:
1. The explicit type specifier corresponding to the data type required must be mentioned in
the function header. The general form of the function definition is
Type_specifier function_name (argument list)
Argumentdeclaration;
{
functionstatement;
}
The type specifier tells the compiler, the type of data the function is to return.
2. The called function must be declared at the start of the body in the calling function, like
any other variable. This is to tell the calling function the type of data the function is
actually returning. The program given below illustrates the transfer of a floating-point
value between functions done in a multiple function program.
Void functions:
The functions that do not return any values can be explicitly defined as void. This prevents any
accidental use of these functions in expressions.

26
Ex No: 5a SORTING NUMBERS
Date:

AIM:
To write a C program to sort ‘n’ numbers.
ALGORITHM:

1. Get the number of elements to be sorted.


2. Get the array elements to be sorted.
3. Sort array of elements by calling the function sort (a, n).
4. Print the sorted array of elements.

PROGRAM:

#include<stdio.h>
void sort(int a[],int n)
{
int i,t,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("The sorted values are :");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
main()
{
int i,a[20],n;
void sort(int a[],int n);
printf("Enter the number of values to be sorted:");
scanf("%d",&n);
printf("Enter the elements to be sorted:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
sort(a,n);
}

27
OUTPUT

Enter the number of values to be sorted: 5

Enter the elements to be sorted:


12
9
14
5
78

The sorted values are


5
9
12
14
78

RESULT:
Thus the program to sort ‘n’ numbers was executed and sorted array of elements
was obtained.

28
Ex.No: 5b PALINDROME CHECKING USING FUNCTIONS
Date:

AIM
To write a C program to find whether the given string is a palindrome or not.
ALGORITHM
5. Read a string
6. Find the length of the string read.
7. Reverse the string.
8. Compare and check whether the given strings are equal.
9. Set a flag value
10. If the flag=1 then the given string is a palindrome.
11. Otherwise, the given string is not a palindrome.

PROGRAM
#include<stdio.h>
char str[50];
int len=0,i=0,j,flag=1;
main()
{
printf("Enter a String:");
scanf("%s",str);
palindrome();
}

palindrome()
{
while(str[i++]!='\0')
len++;
for(i=0,j=(len-1);i<len/2;i++,j--)
{
if(str[j]!=str[i])
{
flag=0;
break;
}
}
if(flag==1)
printf("The given String is a Palindrome\n");
else
printf("The given String is not a Palindrome\n");
}

29
OUTPUT

Enter a String:madam
The given String is a Palindrome

Enter a String:unix
The given String is not a Palindrome

RESULT
Thus the C program to find whether the given string is a palindrome or not was written
and the output was verified.

30
Ex No: 6 POINTERS
Date:

Introduction:
In c a pointer is a variable that points to or references a memory location in which data is
stored. Each memory cell in the computer has an address that can be used to access that
location so a pointer variable points to a memory location we can access and change the
contents of this memory location via the pointer.
Pointer declaration:
A pointer is a variable that contains the memory location of another variable.
The syntax is as shown below. You start by specifying the type of data stored in the location
identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable.
Finally you give the name of the variable.
Syntax:
datatype *variablename;
Example:
int *ptr;
float *string;
Address operator:
Once we declare a pointer variable we must point it to something we can do this by assigning
to the pointer the address of the variable you want to point as in the following example:
ptr=&num;
This places the address where num is stores into the variable ptr. If num is stored in memory
21260 addresses then the variable ptr has the value 21260.
Pointer expressions & pointer arithmetic:
Like other variables pointer variables can be used in expressions. For example if p1 and p2 are
properly declared and initialized pointers, then the following statements are valid.
y=*p1**p2;
sum=sum+*p1;
Pointers and function:
The pointers are very much used in a function declaration. Sometimes only with a pointer a
complex function can be easily represented and success. The usage of the pointers in a function
definition may be classified into two groups.
1. Call by reference
2. Call by value
Call by value: When a function is invoked there will be a link established between the formal
and actual parameters. A temporary storage is created where the value of actual parameters is
stored. The formal parameters picks up its value from storage area the mechanism of data
transfer between actual and formal parameters allows the actual parameters mechanism of data
transfer is referred as call by value. The corresponding formal parameter represents a local
variable in the called function. The current value of corresponding actual parameter becomes
the initial value of formal parameter. The value of formal parameter may be changed in the
body of the actual parameter. The value of formal parameter may be changed in the body of the
subprogram by assignment or input statements. This will not change the value of actual
parameters.
Call by Reference: When we pass address to a function the parameters receiving the address
should be pointers. The process of calling a function by using pointers to pass the address of

31
the variable is known as call by reference. The function, which is called by reference, can
change the values of the variable used in the call.

32
Ex No: 6a SWAPPING TWO NUMBERS
Date:

AIM:
To write a C program to swap two numbers using pointers

ALGORITHM:

1. Enter the values of a and b


2. Swap the numbers by calling the function interchange (&a, &b)
3. Print the values of a and b after swapping

PROGRAM:

#include<stdio.h>
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
main()
{
int a,b;
printf("Enter the value of a and b:");
scanf("%d%d",&a,&b);
swap(&a,&b);
printf("The values of a and b after interchanging:\n");
printf("a=%d\nb=%d",a,b);
printf("\n");
}

OUTPUT

Enter the value of a and b


3 4
The values of a and b after interchanging
4 3

RESULT:
Thus the program was executed and the two numbers were swapped using pointers.

33
Ex No: 6b SUM OF ‘N’ NUMBERS
Date :

AIM:
To write a C program to find out sum of ‘n’ numbers.
ALGORITHM:
 Read the value of ‘n’
 Get the values
 Perform the summation of given ‘n’ numbers using pointers
PROGRAM:
#include<stdio.h>
main()
{
int a[10];
int n,i,*p,sum=0;
p=a;
printf("Enter the number of values\n");
scanf("%d",&n);
printf(" Enter the values\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
sum=sum + *(p+i);
printf(" The sum of given n numbers is : %d",sum);
}

OUTPUT

Enter the number of values


4
Enter the values
2 3 4 1
The sum of given n numbers is : 10

RESULT:
Thus the program to find sum of ‘n’ numbers was found using C program.

34
Ex No: 7 Dynamic Memory Allocation
Date :

Dynamic Memory Allocation


The process of allocating memory at run time is known as dynamic memory allocation.
Although c does not inherently have this facility there are four library routines, which allow
this function
C supports with memory management functions, which can be used to allocate and free
memory during the program execution. The following functions are used in c for purpose of
memory management.

Functio Task
n

malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated
space

calloc Allocates space for an array of elements initializes them to zero and returns a pointer to the
memory

free Frees previously allocated space

realloc Modifies the size of previously allocated space.

Allocating a block of memory:


A block mf memory may be allocated using the function malloc. The malloc function reserves
a block of memory of specified size and returns a pointer of type void. This means that we can
assign it to any type of pointer. It takes the following form:

ptr=(cast-type*)malloc(byte-size);

where ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of
memory with size byte-size.

Example:
x=(int*)malloc(100*sizeof(int));

On successful execution of this statement a memory equivalent to 100 times the area of int
bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer
x of type int
Allocating multiple blocks of memory:
Calloc is another memory allocation function that is normally used to request multiple blocks
of storage each of the same size and then sets all bytes to zero. The general form of calloc is
ptr=(cast-type*) calloc(n,elem-size);
The above statement allocates contiguous space for n blocks each size of elements size bytes.
All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned.
If there is not enough space a null pointer is returned.
Releasing the used space:

35
Compile time storage of a variable is allocated and released by the system in accordance with
its storage class. With the dynamic runtime allocation, it is our responsibility to release the
space when it is not required. The release of storage space becomes important when the storage
is limited. When the data stored in a block of memory is not then the allocated block of
memory for future use can be released , using the free function.
free(ptr);
ptr is a pointer that has been created by using malloc or calloc.
To alter the size of allocate memory:
The memory allocated by using calloc or malloc might be insufficient or excess sometimes in
both the situations we can change the memory size already allocated with the help of the
function realloc. This process is called reallocation of memory. The general statement of
reallocation of memory is:
ptr=realloc(ptr,newsize);
This function allocates new memory space of size newsize to the pointer variable ptr and
returns a pointer to the first byte of the memory block. The allocated new block may be or may
not be at the same region.

36
Ex No: 7a CONCATENATION OF TWO STRINGS
Date :

AIM:
To write C program to concatenate two strings
ALGORITHM:

1. Get two strings to concatenated


2. Concatenate the two strings
3. Display the concatenated string
PROGRAM:

#include<stdio.h>
#include<malloc.h>
#define s 40
main()
{
char *s1,*s2,*s3,c;
int i,j,k;
s1=(char*)malloc(s*sizeof(char));
s2=(char*)malloc(s*sizeof(char));
s3=(char*)malloc(2*s*sizeof(char));
printf("Enter the stirng one:");
scanf("%s",s1);
printf("Enter the stirng two:");
scanf("%s",s2);
i=0;
while((c=*(s1+i))!='\0')
{
*(s3+i)=c;
i=i+1;
}
k=0;
while((c=*(s2+k))!='\0')
{
s3[i+k]=c;
k=k+1;
}
printf("Concatenated string is:\n");
printf("%s\n",s3);
}

37
OUTPUT

Enter the stirng one :


unix
Enter the stirng two :
lab
Concatenated string is :
unixlab

RESULT:
Thus the two string was concatenated using the C program.

38
ExNo: 7b ALTERING THE ALLOCATED MEMORY
Date :

AIM:
To write a program to alter the allocated memory

ALGORITHM:

1. Allocate memory space for the character pointer


2. Initialize the character pointer with the string MADRAS
3. Reallocate memory for storing new string
4. Reinitialize the character pointer with new string
5. Print the reallocated string

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
main()
{
char *p;
p=(char *)malloc(6);
strcpy(p,"MADRAS");
printf("Memory contains:%s\n",p);
p=(char *)realloc(p,7);
strcpy(p,"CHENNAI");
printf("Memory after altering:%s\n",p);
free(p);
}

OUTPUT

RESULT:
Thus the program to alter the allocated memory was executed and the output was verified.

39
Ex No: 8 FILES IN C
Date :

Files:
A file is a block of arbitrary information, or resource for storing information, which is
available to a computer program and is usually based on some kind of durable storage. A file is
durable in the sense that it remains available for programs to use after the current program has
finished.
File operations:
C supports a number of functions that have the ability to perform basic file operations, which
include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
1. Real life situations involve large volume of data and in such cases, the console oriented
I/O operations pose two major problems
2. It becomes cumbersome and time consuming to handle large volumes of data through
terminals.
3. The entire data is lost when either the program is terminated or computer is turned off
therefore it is necessary to have more flexible approach where data can be stored on the
disks and read whenever necessary, without destroying the data. This method employs
the concept of files to store data.
File operation functions in C:
Function Name Operation

fopen() Creates a new file for use


Opens a new existing file for use
fclose Closes a file which has been opened for use

getc() Reads a character from a file

putc() Writes a character to a file

fprintf() Writes a set of data values to a file

fscanf() Reads a set of data values from a file

getw() Reads a integer from a file

putw() Writes an integer to the file

fseek() Sets the position to a desired point in the file

ftell() Gives the current position in the file

rewind() Sets the position to the begining of the file

40
Defining and opening a file:
In order to store data in a file into the secondary memory, certain things must be specified
about the file to the operating system. They include the fielname, data structure, and purpose.
The general format of the function used for opening a file is
FILE *fp;
fp=fopen(“filename”,”mode”);
The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier,
File is a structure that is defined in the I/O Library. The second statement opens the file named
filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all
the information about the file, is subsequently used as a communication link between the
system and the program. The second statement also specifies the purpose of opening the file.
The mode does this job.
R open the file for read only.
W opens the file for writing only.
A open the file for appending data to it.
Consider the following statements:
FILE *p1, *p2;
p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);
In these statements the p1 and p2 are created and assigned to open the files data and results
respectively the file data is opened for reading and result is opened for writing. In case the
results file already exists, its contents are deleted and the files are opened as a new file. If data
file does not exist error will occur.
Closing a file:
The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);
A file must be closed as soon as all operations on it have been completed. This would close the
file associated with the file pointer.
Observe the following program
….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
…..
…..
fclose(p1);
fclose(p2);
The above program opens two files and closes them after all operations on them are completed,
once a file is closed its file pointer can be reversed on other file.
getc and putc functions:
The getc and putc functions are analogous to getchar and putchar functions and handle one
character at a time. The putc function writes the character contained in character variable c to
the file associated with the pointer fp1. ex putc(c,fp1); similarly getc function is used to read a
character from a file that has been open in read mode. c=getc(fp2).
The getw and putw functions:

41
These are integer-oriented functions. They are similar to get c and putc functions and are used
to read and write integer values. These functions would be usefull when we deal with only
integer data. The general forms of getw and putw are:
putw(integer,fp);
getw(fp);
The fprintf & fscanf functions:
The fprintf and scanf functions are identical to printf and scanf functions except that they work
on files. The first argument of theses functions is a file pointer, which specifies the file to be
used. The general form of fprintf is
fprintf(fp,”control string”, list);
Where fp id a file pointer associated with a file that has been opened for writing. The control
string is file output specifications list may include variable, constant and string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here name is an array variable of type char and age is an int variable .The general format of
fscanf is
fscanf(fp,”controlstring”,list);
This statement would cause the reading of items in the control string.
Example:
fscanf(f2,”5s%d”,item,&quantity”);
Like scanf, fscanf also returns the number of items that are successfully read.
Random access to files:
Sometimes it is required to access only a particular part of the and not the complete file.
This can be accomplished by using the fseek function.
fseek function:
The general format of fseek function is a s follows:
fseek(file pointer,offset, position);
This function is used to move the file position to a desired location within the file. Fileptr
is a pointer to the file concerned. Offset is a number or variable of type long, and position in an
integer number. Offset specifies the number of positions (bytes) to be moved from the location
specified bt the position. The position can take the 3 values.

Value Meaning
0 Beginning of the file
1 Current file
2 End of the file

Ex.No: 8a DISPLAY THE CONTENTS IN A FILE


Date :

AIM
To write a C program to display the contents available in a file.

42
ALGORITHM

1. Read the file to be displayed.


2. The file to be read is opened in read mode.
3. Read the contents of the file character by character.
4. Print the characters read.
5. Close the file when all its contents are read.
PROGRAM

#include<stdio.h>
main()
{
FILE *fopen(),*fp;
int c;
fp=fopen("Read_File","r");
c=getc(fp);
while(c!=EOF)
{
putchar(c);
c=getc(fp);
}
fclose(fp);
}

OUTPUT

RESULT
Thus the C program to read the contents available in a file was written successfully and
the output was verified.
Ex.No: 8b REVERSING A FILE
Date :

43
AIM

To write a C program to read the contents available in a file and to reverse it.

ALGORITHM

1. Read the file whose content is to be reversed in read mode.


2. Open another file in write mode in to which the reversed information is to be
written.
3. Move the file pointer to the end of the file whose contents is to be reversed
using the function fseek().
4. Bring the position back to the last but one character in the file.
5. The function getc() is used to read the next character and after reading, the file
pointer is incremented to the next position.
6. The output thus obtained is displayed in the screen.

PROGRAM

#include<stdio.h>
main()
{
char ch;
FILE *fp1,*fp2;
fp1=fopen("Input_File","r");
fp2=fopen("Output_File","w");
fseek(fp1,0,2);
while(fseek(fp1,-2,1)==0)
{
ch=getc(fp1);
putchar(ch);
putc(ch,fp2);
}
}

OUTPUT

44
RESULT
Thus the C program to reverse the contents available in a file was written successfully
and the output was verified.

Ex.No: 8c TRANSPOSE MATRIX


Date :

45
AIM
To write a C program to find the transpose of a matrix and to write into a file.

ALGORITHM
1. Initialize a matrix.
2. Open a file write mode into which the transpose matrix is to be written.
3. Perform transpose of a matrix and write the contents into the opened file.
4. The transpose of the matrix is written into the file.
PROGRAM

#include<stdio.h>

main()
{
int i,j;
int matrix[2][3]={{1,2,3},{4,5,6}};
FILE *fp;
fp=fopen("matrix","w");
fprintf(fp,"\t \n Transpose of the given matrix \n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
fprintf(fp,"\t%d\t",matrix[j][i]);
fprintf(fp,"\n");
}
}

OUTPUT

RESULT
Thus the C program to write the transpose of a matrix into a file was written
successfully and the output was verified.

46

You might also like