Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
NAME
REG NO :
BONAFIDE CERTIFICATE
REGISTER.NO:
I YEAR/ II SEM
INTERNAL EXAMINER
EXTERNAL EXAMINER
TABLE OF CONTENTS
CHAPTER
NO
EXERCISE
NO
DATE
LAB
EXPERIMENT/CHAPTER
NAME
STUDY OF UNIX
OPERATING SYSTEM
BASIC SHELL COMMANDS
PRACTICE-I
PRACTICE-II
PRACTICE-III
PRACTICE-IV
I-3
II
PRACTICE-V
PRACTICE-VI
UNIX EDITORS
SHELL PROGRAMMING
II-1
SEQUENTIAL LOGIC
II-1.1
AREA AND
CIRCUMFERENCE OF A
CIRCLE
SIMPLE INTEREST
II-1.2
II-1.3
II-2
FARENHEIT TO
CENTIGRADE CONVERSION
SWAPPING VALUES OF
TWO VARIABLES
DECISION LOGIC
II-2.1
ODD/EVEN
II-2.2
II-3
CHECK POSITIVE OR
NEGATIVE NUMBER
BIGGEST OF THREE
NUMBERS
STUDENT GRADE
DETERMINATION
CASE LOGIC
II-3.1
VOWEL/CONSONANT
II-3.2
SIMPLE CALCULATOR
SIMULATION
II-1.4
II-2.3
II-2.4
PAGE
NO
SIGN
II-4
LOOPING LOGIC
II-4.1
MULTIPLICATION TABLE
II-4.2
ARMSTRONG NUMBER
II-4.3
FIBONACCI SERIES
II-4.4
PRIME NUMBER
II-4.5
FACTORIAL OF A GIVEN
NUMBER
II-4.6
III
C PROGRAMMING IN UNIX
III-1
FUNCTIONS
III-1.1
XY COMPUTATION
III-1.2
FACTORIAL [RECURSION]
III-1.3
III-2
STRING CONCATENATION
WITHOUT USING STRCAT
FUNCTION
STRING COPY WITHOUT
USING STRCPY FUNCTION
POINTERS
III-2.1
CALL BY REFERENCE
III-3
FILE HANIDLING
III-3.1
III-1.4
III-3.2
III-4
III-4.1
III-4.2
III-4.3
DYNAMIC MEMORY
ALLOCATION
STRING REVERSE USING
DMA
STUDENT AGGREGATE
USING DMA
SORTING USING DMA
STAFF-IN-CHARGE
REGISTER NUMBER:
Operating System-Definition:
An Operating System is a set of programs that:
that controls and manages the operations of computer.
acts as an intermediate between hardware and user.
Functions of Os:
Resource management.
Task management.
Scheduling.
Fault Tolerance.
File management.
OS Types:
1. Single UserThe system will have its own hard disk, memory, CPU and other resources all
dedicated to a single user. Eg. MS-DOS
2. Multi UserThe users having access to a multi-user system will have just a terminal and a
keyboard. The other resources such as hard disk, printers are centrally located. The user is
expected to simply hook onto his account, perform the work, disconnect and leave quietly. Eg.
UNIX
UNIX History:
The spade work for UNIX began at AT&T Bell Laboratories in 1969 by Ken Thompson
and Dennis Ritchie. The OS was initially known as UNICS (jokingly UNiplexed Information and
REGISTER NUMBER:
Computing System). In 1970 UNICS finally became UNIX. In 1973, UNIX was rewritten in
1973 in C principally authored by Ritchie.
UNIX Features:
1. Multi-user systemMulti-user capability of UNIX allows several users to use the same
computer to perform their tasks. Several terminals [Keyboards and Monitors] are connected to a
single powerful computer [UNIX server] and each user can workwith their terminals.
3. Programming FacilityUNIX is highly programmable, the UNIX shell has all the necessary
ingredients like conditional and control structures, etc.
4. SecurityUNIX allows sharing of data; every user must have a single login name and
password. So, accessing another users data is impossible without his permission.
5. PortabilityUNIX is portable because it is written in a high level language. So, UNIX can be
run on different computers.
Apart from these features, UNIX has an extensive Tool kit, exhaustive system calls and
Libraries and enhanced GUI (X Window).
REGISTER NUMBER:
Organization of UNIX:
The UNIX system is functionally organized at three levels and are:
1. The kernel, which schedules tasks and manages storage;
2. The shell, which connects and interprets users' commands, calls programs from memory, and
executes them; and
3. The tools and applications that offer additional functionality to the OS
UNIX Structure:
The kernel is the heart of the system, a collection of programs written in C that directly
communicate with the hardware. There is only one kernel for any system. It's that part of UNIX
system that is loaded into memory when the system is booted. It manages the system resources,
allocates time between user and processes, decides process priorities, and performs all other
tasks. The kernel, in traditional parlance, is often called the Operating system. The shell, on the
other hand, is the "sleeping beauty" of UNIX. It is actually the interface between the user and the
kernel. The shell is the agency which takes care of the features of redirection and has a
REGISTER NUMBER:
programming capability of its own. The Tools and Applications consist of Application Software,
Compilers, Database Package, Internet tools, UNIX commands, etc.
File System:
A file in UNIX is nothing but a storehouse of information and everything is treated as a
file by UNIX. The files can be broadly classified as follows:
Ordinary filesContains stream of data. All data, text, source programs, object and
executable code, commands fall into this category.
Directory filesContains no external data. It contains an entry, name of the file and
its inode (identification number) for each file and subdirectory under that directory.Directory
files are not created by the user but by the UNIX system itself.
Device filesEven physical devices are treated as files. These are special in the sensethat any
output directed to it will be reflected onto the respective device
REGISTER NUMBER:
All files in UNIX are related to one another. The file system of UNIX resembles a tree
that grows from top to bottom as shown in the figure. The file system begins with a directory
called root (at the top). The root directory is denoted by a slash (\). Branching from root there are
several directories such as bin, lib, etc, tmp, dev. Each of these directories contains several subdirectories and files.
RESULT:
Thus the study of UNIX Operating System has been completed successfully.
Exercise: I-2
REGISTER NUMBER:
AIM
To study and execute Unix commands.
Directory Commands:
Command
mkdir
rmdir
cd
cd ..
Usage
To create a directory
To delete a directory
To change the directory
To come back to previous
directory
To come back to home directory
directly
Lists the contents of directory
To print current working
directory
To delete the nonempty
directories
Syntax
mkdir <directoryname>
rmdir <directoryname>
cd <directoryname>
cd ..
Commands
Usage
Syntax
cat
cat >filename
cat <filename>
cat <file1> < file2>
cp
cp <src> <dest>
cd ~
ls
pwd
rm r
cd ~
ls
pwd
rm r <directoryname>
File Commands:
mv
vi
sort
grep
rm
head
mv <src> <dest>
vi <filename>
sort <filename>
grep <word*> <filename>
rm <filename>
head <filename>, head [-n]
REGISTER NUMBER:
Usage
Lists who is on computers in the
lab
Print the present date
Print the present time.
To print the calendar of the
current month.
Lists commands you've done
recently
Checks the current user
To logout
To clear the window
Online help
Syntax
finger
User Commands:
Commands
finger
date
time
cal
history
whoami
exit
clear
man
date
time
cal
cal <month_no> <year>
history
whoami
exit
clear
man
LAB PRACTICES:
Practice-I Write and execute the Unix Commands for the following:
i] Change your working directory.
ii] Return to home directory.
iii] Lists the contents of the home directory.
iv] Delete the created directory.
REGISTER NUMBER:
Practice-II Write and execute the Unix Commands for the following:
i] Create a file A and enter BE-CSE
ii] Create another file B and enter First year
iii] Copy the contents of file A to File B.
iv] Move the contents of file B to File A.
REGISTER NUMBER:
REGISTER NUMBER:
Practice-III Write and execute the Unix Commands for the following:
i] Change your working directory as SREC within that create a file CSE.
ii] Remove the duplicate contents of the file and count the number of lines.
REGISTER NUMBER:
Practice-IV Write and execute the Unix Commands for the following:
i] Create two directories ABC and DEF.
ii] Inside ABC and DEF create files CBA and FED respectively.
iii] Display the first 3 lines in the file CBA.
iv] Move the contents of FED to CBA.
REGISTER NUMBER:
Practice-V Write and execute the Unix Commands for the following:
i] Change your working directory as ABACUS within that create a file CSE-B and enter the
theory and lab of current semester.
ii] Display the line containing the word Lab and its count.
iii] Display the line containing the word Theory.
REGISTER NUMBER:
Practice-VI Write and execute the Unix Commands for the following:
i] Display the current date time.
ii] Display the calendar of this month.
iii] Display the calendar of Oct 1987.
iv] Usage of bc command.
Result:
Thus various UNIX commands were studied and efficient practices were made
successfully.
Exercise: I-3
REGISTER NUMBER:
UNIX EDITORS
UNIX system starts a special version of a shell called an interactive shell, and shows a
shell prompt, usually in the form of a dollar sing ($), a percent sign( %), or a pound sign (#),
When we type a line of input at a shell prompt, the shett tries to interpret it. Input to a shell
prompt is sometimes called a command line.
Modes in vi Editor:
The UNIX vi editor is a full screen editor and has three modes of operation:
Command mode
This is the default when you enter vi. In command mode, most letters, or short sequences of
letters, that you type will be interpreted as commands, without explicitly pressing Enter. If you
press Esc when you're in command mode, your terminal will beep at you. This is a very good
way to tell when you're in command mode.
Insert mode
In insert mode, whatever you type is inserted in the file at the cursor position. Type a
(lowercase letter a, for append) to enter insert mode from command mode; press Esc to end
insert mode, and return to command mode.
Line mode
Use line mode to enter line oriented commands. To enter line mode from command mode,
type a colon . Your cursor moves to the bottom of the screen, by a colon prompt. Type a line
mode command, then press Enter. Any sensible command from the Unix line editor ex will
work, and a few are good to know about. These commands are indicated in this handout by a
colon in front of the command. Each time you use a line mode command, you must type a colon
to enter line mode, then type the command by the colon prompt at the bottom of the screen, then
press Enter when you finish typing the command.
Command
dw
d$
d0
yy
yw
p /P
?text/text
ZZ/ :wq
:q/:q!
U
U
x
dd
:n
$
:w_file1
REGISTER NUMBER:
Usage
delete the entire word
delete a line from cursor position to the end of the
line
Delete from the cursor position to the start of the
line
Copies (yanks) the entire line
Copies the entire word
Pastes the text
Locates the text in the file. If not found, the
message "Pattern not found" appears. Use n to
repeat the forward search and N for backward
search.
Save a file and exit vi
Quit without saving
Undo last command
Undo all commands used in the Unix prompt
Deletes the character positioned by cursor
Deletes the line currently positioned by the cursor
Goto line n
Move to end of line
Save to new file file1
Result:
Thus the vi editors was studied clearly and vastly.
CHAPTER-II
REGISTER NUMBER:
SHELL PROGRAMMING
The UNIX operating systems is flexible in a way that it is not tied to any particular
command interpreter. A programs high-level language statements are stored in a file called the
source file, which programmer creates using editors. In order to execute, high-level source files
must be converted into a low-level machine language file. A compiler is a program that converts
source files into executable machine-language files. The complier reads the lines of code the
programmer wrote in the source file and converts them to the appropriate machine language
instructions. If a source file contains syntax errors, it cannot be converted into an executable file.
A programmer must correct these errors before the program can be run. Unlike high-level
language programs, shell scripts do not have to be converted into machine language by a
compiler. The UNIX shell acts as an interpreter when reading script files. Interpreters read
statements in script files and immediately translate them into executable instructions and cause
them to run. Its collections of executables or commands placed in a file and executed. It
provides user an option to execute a command based on some condition.
Features of Shell:
Interactive.
Allows command execution.
Allows looping.
Allows file creation.
Types of Shell:
Bourne shell (sh) [not popular for interactive use].
C shell (csh) [similar to C adding own commands].
TC shell (tcsh) [edit your command line].
Korn shell (ksh) [inc all features of C and TC].
Bourne Again SHell (bash) [all interactive features of csh and ksh]
REGISTER NUMBER:
Shell Operators:
Bash shell operators are in three groups:
Defining and Evaluating operators are used to set a variable to a value and to check
variable values. The equal sign (=) is an example.
Arithmetic operators are used to perform mathematical equations. The plus sign (+) is an
example
Redirecting and piping operators are used to specify input and output data specifications
The greater than sign (>) is an example
Exercise-II-1
REGISTER NUMBER:
SEQUENTIAL LOGIC
Shell Variables:
Variables are used to store values used in the programs. No need to declare the data_type.
To assign a value to a variable:
$var_name=value
echo command:
Syntax: $echo <sentence>
Ex:1 $var=100
$echo $var
o/p: 100
Ex:2 $var=distinction
$echo Uve secured $var in BE[CSE]
o/p: Uve secured distinction in BE[CSE]
Ex:3 $var=12;$var1=25
echo $var $var1
o/p: 12 25
REGISTER NUMBER:
read command:
Syntax: $read var_name
Used to read the input from the user and assign this input to the variable.
expr command:
Syntax: $expr arg1 operator arg2
Used to evaluate an arithmetic expressions
Ex:1 c=expr a*b
echo $c
Ex:2 echo Enter the value of a and b
read a b
Sum=expr a+b
echo $Sum
Exercise: II-I.1
REGISTER NUMBER:
AIM:
To create a Shell program for calculating the Area and Circumference of a Circle.
ALGORITHM:
Step 1 : Start
Step 2 : Define constant pi = 3.14
Step 3 : Read the value of radius
Step 4 : Calculate area using formulae: pi radius radius
Step 5 : Calculate circumference using formulae: 2 pi radius
Step 6 : Print area and circumference
Step 7 : Stop
SHELL SCRIPT:
clear
pi=`expr "scale=2; 22 / 7" | bc`
echo "Enter value for radius : "
read radius
area=`expr "scale=2; $pi * $radius * $radius" | bc`
circum=`expr "scale=2; 2 * $pi * $radius" | bc`
echo "Area : $area"
echo "Circumference : $circum"
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for Calculating the Area and Circumference of a Circle was created
and executed successfully.
Exercise: II-I.2
REGISTER NUMBER:
SIMPLE INTEREST
AIM:
To create a Shell program for calculating the Simple Interest.
ALGORITHM:
Step 1 : Start
Step 2 : Read the values principal, rate and years
Step 3 : Compute Simple Interest using the formulae: (principal rate years) / 100
Step 4 : Print Simple Interest
Step 5 : Stop.
SHELL SCRIPT:
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for Calculating the Simple Interest was created and executed
successfully.
Exercise: II-I.3
REGISTER NUMBER:
AIM:
To create a Shell program for Farenheit To Centigrade Conversion.
ALGORITHM:
Step 1 : Start
Step 2 : Read fahrenheit value
Step 3 : Convert fahrenheit to centigrade using the formulae: (fahrenheit 32) 5/9
Step 4 : Print centigrade
Step 5 : Stop
SHELL SCRIPT:
# Degree conversion
echo "Enter Fahrenheit : "
read f
c=`expr \( $f - 32 \) \* 5 / 9`
echo "Centigrade is : $c"
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for Farenheit To Centigrade Conversion was created and executed
successfully.
Exercise:II-I.4
REGISTER NUMBER:
AIM:
To create a Shell program for Swapping values of two Variables.
.
ALGORITHM:
Step 1 : Start
Step 2 : Read the values of a and b
Step 3 : Interchange the values of a and b using another variable t as follows:
t=a
a=b
b=t
Step 4 : Print a and b
Step 5 : Stop
SHELL SCRIPT:
# Swapping values
echo "Enter value for A : "
read a
echo "Enter value for B : "
read b
t=$a
a=$b
b=$t
echo "Values after Swapping"
echo "A Value is $a"
echo "B Value is $b"
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for Swapping values of two variables was created and executed
successfully.
Exercise: II-2
REGISTER NUMBER:
DECISION LOGIC
Shell supports decision-logic using if statement. The if statement like its counterpart in
programming languages has the following formats. The first construct executes the statements
when the condition is true. The second construct adds an optional else to the first one that has
different set of statements to be executed depending on whether the condition is true or false.
The last one is an elif ladder, in which conditions are tested in sequence, but only one set of
statements is executed.
Syntax: ifthen
if [ condition ]
then
statements
fi
Syntax: ifthenelse
if [ condition ]
then
statements
else
statements
fi
Syntax: ifelifelse
if [condition ]
then
statements
elif [ condition ]
REGISTER NUMBER:
then
statements
.. .
else
statements
fi
The set of relational and logical operators used in conditional expression is given below.
The numeric comparison in the shell is confined to integer values only.
Numerical Comparators:
Operator
-eq
-ne
-gt
-lt
-ge
-le
Meaning
Equal
Not equal
Greater than
Less than
Greater than or equal to
Less than or equal to
Logical Operators:
Operator
-a
-o
-!
Meaning
AND
OR
Negation
Arithmetic Operators:
Operators
+
\*
/
Meaning
Addition
Subtraction
Multiplication
Division
Exercise: II-2.1
REGISTER NUMBER:
ODD/EVEN
AIM:
To create a Shell program to check whether the given number is Odd/Even.
ALGORITHM:
Step 1 : Start
Step 2 : Read number
Step 3 : If number divisible by 2 then
Print "Number is Even"
Step 3.1 : else
Print "Number is Odd"
Step 4 : Stop
SHELL SCRIPT:
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for checking Odd/Even number was created and executed
successfully.
Exercise: II-2.2
REGISTER NUMBER:
AIM:
To write a shell program to check the given number is positive or negative.
ALGORITHM:
SHELL SCRIPT:
clear
echo Enter a number
read n
if [ $n gt 0 ]
then
echo $n is a Positive number
elif [ $n -lt 0 ]
then
echo $n is a Negative number
else
echo $n is a zero
fi
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT :
RESULT:
Thus the shell script was written and executed for checking the given number positive or
Negative.
Exercise: II-2.3
REGISTER NUMBER:
AIM:
To create a Shell program for determining the biggest among three numbers.
ALGORITHM:
Step 1 : Start
Step 2 : Read values of a, b and c
Step 3 : If a > b and a > c then
Print "A is the biggest"
Step 3.1 : else if b > c then
Print "B is the biggest "
Step 3.2 : else
Print "C is the biggest"
Step 4 : Stop
SHELL SCRIPT:
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for checking the largest among three numbers was created and
executed successfully.
Exercise: II-2.4
AIM:
To create a Shell program for Student Grade Determination.
ALGORITHM:
Step 1 : Start
Step 2 : Read mark
Step 3 : If mark > 90 then
Print "S grade"
Step 3.1 : else if mark > 80 then
Print "A grade"
Step 3.2 : else if mark > 70 then
Print "B grade"
Step 3.3 : else if mark > 60 then
Print "C grade"
Step 3.4 : else if mark > 55 then
Print "D grade"
Step 3.5 : else if mark 50 then
Print "E grade"
Step 3.6 : else
Print "U grade"
Step 4 : Stop
REGISTER NUMBER:
SHELL SCRIPT:
clear
echo "Enter the mark : "
read mark
if [ $mark -gt 90 ]
then
echo "S Grade"
elif [ $mark -gt 80 ]
then
echo "A Grade"
elif [ $mark -gt 70 ]
then
echo "B Grade"
elif [ $mark -gt 60 ]
then
echo "C Grade"
elif [ $mark -gt 55 ]
then
echo "D Grade"
elif [ $mark -ge 50 ]
then
echo "E Grade"
else
echo "U Grade"
fi
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for Student Grade Determination was created and executed
successfully.
Exercise: II-3
REGISTER NUMBER:
CASE LOGIC
The case logic is used to compare a variables value against a set of constants integer,
character, string, range). If it matches a constant, then the set of statements followed after) is
executed till a ;; is encountered. The optional default block is indicated by *. Multiple constants
can be specified in a single pattern separated by |.
case variable in
constant1)
statements ;;
constant2)
statements ;;
...
constantN)
statements ;;
*)
statements
esac
Exercise: II-3.1
REGISTER NUMBER:
VOWEL/CONSONANT
AIM:
To create a Shell program to check whether entered characters is vowel / consonant.
ALGORITHM:
Step 1 : Start
Step 2 : Read char
Step 3 : If char is either 'a', 'e', 'i', 'o' or 'u' then
Print "It's a vowel"
Step 3.1 : else
Print "It's a consonant"
Step 4 : Stop
SHELL SCRIPT:
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for checking vowel/consonant using case logic was created and
executed successfully.
Exercise: II-3.2
AIM:
To create a Shell program for Simple Calculator Simulation.
.
ALGORITHM:
Step 1 : Start
Step 2 : Read operands a and b
Step 3 : Display operation menu
Step 4 : Read option
Step 5 : If option = 1 then
Calculate c = a + b
Step 5.1 : else if option = 2 then
Calculate c = a b
Step 5.2 : else if option = 3 then
Calculate c = a * b
Step 5.3 : else if option = 4 then
Calculate c = a / b
Step 5.4 : else if option = 5 then
Calculate c = a % b
Step 5.5 : else
Print "Invalid option"
Step 6 : Print c
Step 7 : Stop
REGISTER NUMBER:
SHELL SCRIPT:
case $option in
1) c=`expr $a + $b`
echo "$a + $b = $c";;
2) c=`expr $a - $b`
echo "$a - $b = $c";;
3) c=`expr $a \* $b`
echo "$a * $b = $c";;
4) c=`expr $a / $b`
echo "$a / $b = $c";;
5) c=`expr $a % $b`
echo "$a % $b = $c";;
*) echo "Invalid Option"
esac
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for Simple Calculator Simulation using case logic was created and
executed successfully.
Exercise: II-4
REGISTER NUMBER:
LOOPING LOGIC
Shell supports a set of loops such as for, while and until to execute a set of statements
repeatedly. The body of the loop is contained between do and done statement.
The for loop doesn't test a condition, but uses a list instead.
Syntax:
for variable in list
do
statements
done
The while loop executes the statements as long as the condition remains true.
Syntax:
while [ condition ]
do
statements
done
The until loop complements the while construct in the sense that the statements are executed
as long as the condition remains false.
Syntax:
until [ condition ]
do
statements
done
Exercise: II-4.1
MULTIPLICATION TABLE
AIM:
To create a Shell program for generating Multiplication Table.
ALGORITHM:
Step 1 : Start
Step 2 : Read the value of n
Step 3 : Initialize 1 to i
Step 4 : Print n, i, ni
Step 5 : Increment i by 1
Step 6 : Repeat steps 4 and 5 until i 10
Step 7 : Stop
REGISTER NUMBER:
SHELL SCRIPT:
clear
# Multiplication table using for loop
clear
echo "Which multiplication table? : "
read n
for x in 1 2 3 4 5 6 7 8 9 10
do
p=`expr $x \* $n`
echo "$n X $x = $p"
done
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for generating Multiplication Table was created and executed
successfully.
Exercise: II-4.2
REGISTER NUMBER:
ARMSTRONG NUMBER
AIM:
To create a Shell program for checking whether the given number is an Armstrong
number or not.
ALGORITHM:
Step 1 : Start
Step 2 : Read number
Step 3 : Initialize 0 to sum and number to num
Step 4 : Extract lastdigit by computing number modulo 10
Step 5 : Cube the lastdigit and add it to sum
Step 6 : Divide number by 10
Step 7: Repeat steps 46 until number > 0
Step 8 : If sum = number then
Print Armstrong number
Step 8.1 : else
Print Not an Armstrong number
Step 9 : Stop
SHELL SCRIPT:
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
[secd52@localhost loops]$ sh armstrong.sh
RESULT:
Thus the Shell Script for checking whether the given number is an Armstrong number or
not was created and executed successfully.
Exercise: II-4.3
FIBONACCI SERIES
AIM:
To create a Shell program for generating Fibonacci Series.
ALGORITHM:
Step 1 : Start
Step 2 : Read number of terms as n
Step 3 : Initialize 0 to f1, 1 to f2 and 2 to i
Step 4 : Print initial fibonacci terms f1, f2
Step 5 : Generate next term using the formula f3 = f1 + f2
Step 6 : Print f3
Step 7 : Increment i by 1
Step 8 : Assign f2 to f1
Step 9 : Assign f3 to f2
Step 10 : Repeat steps 59 until i n
Step 11 : Stop
REGISTER NUMBER:
SHELL SCRIPT:
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for generating Fibonacci Series was created and executed
successfully.
Exercise: II-4.4
REGISTER NUMBER:
PRIME/NOT
AIM:
To create a Shell program for checking whether the given number is Prime/not.
ALGORITHM:
Step 1 : Start
Step 2 : Read the value of n
Step 3 : Initialize i to 2
Step 4 : If n is divisible by i then
Print Not Prime and Stop
Step 5 : Increment i by 1
Step 6 : Repeat steps 4 and 5 until i n/2
Step 7 : Print "Prime"
Step 8 : Stop
SHELL SCRIPT:
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for checking whether the given number is Prime/not was created
and executed successfully.
Exercise: II-4.5
REGISTER NUMBER:
AIM:
To create a Shell program for calculating the Factorial of a given number.
ALGORITHM:
Step 1 : Start
Step 2 : Read number
Step 3 : Initialize 1 to fact and number to i
Step 4 : fact = fact * i
Step 5 : Decrement i by 1
Step 6: Repeat steps 46 until i > 0
Step 7 : Print fact
Step 8 : Stop
SHELL SCRIPT:
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the Shell Script for Calculating the Factorial of given number was created and
executed successfully.
Exercise: II-4.6
REGISTER NUMBER:
AIM:
To write a program to find the Sum and Average of n numbers.
ALGORITHM:
Step1: Start the program.
Step2: Read a number n, which is the limit.
Step3: Initialize i as one and sum as zero.
Step4: Check if i is lesser than or equal to n if it fails goto step7.
Step5: Calculate sum equals to the addition of i with one.
Step6: Calculate i which is the addition of i with one.
Step7:Print sum.
Step8: Calculate the average=sum/n
Step8: Stop the program
SHELL SCRIPT:
clear
echo "----------------sum of n numbers-----------------"
echo "enter the value for the limit"
read n
i=1
sum=0
while [ $i -le $n ]
do
sum=`expr $sum + $i`
i=`expr $i + 1`
done
echo $sum
avg=`expr $sum / n`
echo $avg
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
[Secd52@localhost sequential]$ sh sumofnnumbers.sh
----------------sum of n numbers----------------Enter the value for the limit: 5
15
3
RESULT:
Thus the Shell Script for Computing the Sum and Average of n Numbers was
successfully executed.
CHAPTER-III
C PROGRAMMING IN UNIX
[#include<stdio.h>]
Functions
Variables
REGISTER NUMBER:
Exercise: III-1
REGISTER NUMBER:
FUNCTIONS
A function is a block of code that has a name and it has a property that it is reusable i.e. it
can be executed from as many different points in a C Program as required. Functions are created
when the same process or an algorithm to be repeated several times in various places in the
program. Functions are two types:
1. Built-in / Library function
ex:) printf, scanf etc.
2. User defined function.
User-Defined Functions
Functions defined by the users according to their requirements are called user-defined
functions. These functions are used to break down a large program into a small functions.
REGISTER NUMBER:
Note: The function with return value must be the data type, that is return type and return value
must be of same data type.
REGISTER NUMBER:
Function Parameters:
Parameters provide the data communication between calling function and called function.
Two types:
Actual parameters:
These are the parameters transferred from the calling function[main function] to the
called function[user defined function].
Formal parameters:
Passing the parameters from the called functions[user defined function] to the calling
functions[main function].
Return Statement:
It is used to return the information from the function to the calling portion of the
program.
Syntax:
return;
return();
return(constant);
return(variable);
return(exp);
return(condn_exp);
By default, all the functions return int data type.
REGISTER NUMBER:
Function Call:
A function can be called by specifying the function_name in the source program with
parameters, if presence within the paranthesis.
Syntax:
Fn_name();
Fn_name(parameters);
Ret_value=Fn_name(parameters);
Recursion:
Recursion is calling function by itself again and again until some specified condition has
been satisfied.
Syntax:
int f_name (int x)
{
local variables;
f_name(y); // this is recursion
statements;
}
Call by Value:
When the value is passed directly to the function it is called call by value. In call by value
only a copy of the variable is only passed so any changes made to the variable does not reflects
in the calling function.
Call by reference:
When the address of the value is passed to the function it is called call by reference. In
call by reference since the address of the value is passed any changes made to the value reflects
in the calling function.
Exercise: III-1.1
REGISTER NUMBER:
XY COMPUTATION
AIM:
To create a C Program for computing the expression XY.
ALGORITHM:
Step-1: Start.
Step-2: Read the input c and d.
Step-3:Initialize the variable i=0 and assign z=1.
Step-4: Using for loop, Compute: z=z*x until condition becomes false.
Step-5: Print the result.
Step-6: Stop.
PROGRAM:
#include<stdio.h>
void power(int x, int y);
//Function Declaration
void main()
{
int c,d; //Local Variable Declaration
printf("\n Enter the value of C:");
scanf("%d", &c);
printf("\n Enter the value of D:");
scanf("%d", &d);
power(c,d); //Function Call
}
void power(int x, int y)
//Function Definition
{
int i=0,z=1;
for(i=0;i<y;i++)
{
z=z*x;
}
printf(%d \n,z);
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
[secd52@localhost functions]$ cc power.c
[secd52@localhost functions]$ ./a.out
Enter the value of C:5
Enter the value of D:3
The value of c^d is 125
RESULT:
Thus the C Program for computing xy using functions was created and executed
successfully.
Exercise: III-1.2
REGISTER NUMBER:
FACTORIAL [RECURSION]
AIM:
To create a C Program for computing Factorial using Recursive function.
ALGORITHM:
Step-1: Start
Step-2: Read the input value n
Step-3: call and print function fact(n)
3.1 Initialize i=1 and f=1
3.2 Using while loop call the function f=s*fact(s-1) until the condition remains true.
Step-4: Print the value m
Step-5: Stop
PROGRAM:
#include<stdio.h>
int fact(int s); //Function Declaration
void main()
{
int n,m;
printf("\n Enter the value:");
scanf("%d", &n);
m=fact(n);
//Function Call
//Function Definition
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the C Program for computing Factorial using Recursive functions was created and
executed successfully.
REGISTER NUMBER:
AIM:
To create a C Program to Concatenate two Strings using Function.
ALGORITHM:
Step-1: Start
Step-2: Read two strings as input values.
Step-3: Using while loop, append the characters present in string2 to string1 until string becomes
NULL.
Step-4: Print String2.
Step-5: Stop.
PROGRAM:
#include<stdio.h>
void stringconcat(char[],char[]);
int main()
{
char str1[100],str2[100];
printf("Enter first string:");
scanf("%s",str1);
printf("Enter second string:");
scanf("%s",str2);
stringconcat(str1,str2);
printf("String after concatenation:%s",str1);
return 0;
}
void stringconcat(char str1[],char str2[])
{
int i=0,j=0;
while(str1[i]!='\0')
{
i++;
}
REGISTER NUMBER:
while(str2[j]!='\0')
{
str1[i]=str2[j];
i++;
j++;
}
}
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
[secd11@localhost ~]$ cc strngconc.c
[secd11@localhost ~]$ ./a.out
Enter first string:SREC
Enter second string:A U
String after concatenation:SRECAU
RESULT:
Thus the C Program to concatenate two strings using function was created and executed
successfully.
Exercise: III-1.4
REGISTER NUMBER:
AIM:
To create a C Program for String Copy without using strcpy function.
ALGORITHM:
Step-1: Start.
Step-2: Read String1 value.
Step-3: Using while loop, copy the contents of string1 character by character to String2.
Step-4: Print the String2 value.
Step-5: Stop.
PROGRAM:
#include<stdio.h>
void stringcopy(char[],char[]);
int main()
{
char str1[40],str2[40];
printf("Enter any string:");
scanf("%s",str1);
stringcopy(str1,str2);
printf("After copying string2=%s",str2);
printf("\n string1=%s",str1);
return 0;
}
void stringcopy(char str1[],char str2[])
{
int i=0;
while(str1[i]!='\0')
{
str2[i]=str1[i];
i++;
}
REGISTER NUMBER:
str2[i]='\0';
}
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
[secd11@localhost ~]$ cc strngcopy.c
[secd11@localhost ~]$ ./a.out
Enter any string:CSE
After copying string2=CSE
string1=CSE
RESULT:
Thus the C Program for String Copy without using strcpy function was created and
executed successfully.
Exercise: III-2
REGISTER NUMBER:
POINTERS
Data for a variable is stored at some memory location. Address and Data are two sides an
variable. For instance x = 10 is represented as:
The address of a variable can be obtained using & operator known as reference operator.
The variable's value can be obtained using the dereference operator *.
Pointer Variable:
A Pointer variable or a pointer is a special variable that holds the address of another
variable. Pointer variable are distinguished from other variables by having an asterik (*) prefixed
in the declaration statement.
int x, *iptr;
A pointer variable is a derived data type based on either standard, derived or user-defined
data type. A pointer variable can be made to point any variable of its base type by assigning the
variable's address to the pointer. For instance, an integer pointer can point to an integer variable
only. A pointer variable is allocated 2 bytes irrespective of the data type it points.
ptr = &x; /* Assigning address X to pointer */
Value of the variable pointed to can be accessed by applying the dereference operator
printf("Value of the variable pointed to %d",*ptr);
A pointer of type void is referred to as generic pointer i.e. it can point to any data type.
Since pointer variables hold address, integers could be added or subtracted to yield another
address. A pointer that holds the address of another pointer variable is known as pointer-topointer.
Exercise: III-2.1
CALL BY REFERENCE
AIM:
To create a C Program for Call by Reference.
ALGORITHM:
REGISTER NUMBER:
PROGRAM:
#include<stdio.h>
void swap(int *a, int *b); //Function Declaration
void main()
{
int x,y;
printf("\n Enter the value of x:");
scanf("%d", &x);
printf("\n Enter the value of y:");
scanf("%d", &y);
printf("\n The value of x & y before swapping: %d %d\n",x,y);
swap(&x,&y); //Function Call
printf("\n The value of x & y after swapping is %d %d:\n",x,y);
}
void swap(int *a, int *b) //Function Definition
{
int t;
t=*a;
*a=*b;
*b=t;
}
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
[secd52@localhost functions]$ cc swap_ref.c
[secd52@localhost functions]$ ./a.out
Enter the value of x:7
Enter the value of y:12
The value of x & y before swapping: 7 12
The value of x & y after swapping is 12 7:
RESULT:
Thus the C Program for Call by Reference was created and executed successfully.
Exercise: III-3
REGISTER NUMBER:
FILE HANIDLING
File is a collection of related data. Files are used to store information permanently and
retrieve it. We need to learn how to write information to a file and how to read information from
a file.
Why we in need of Files?
Some programs expect the same set of data to be fed as input every time it is run.
Better if the data are kept in a file, and the program reads from the file.
REGISTER NUMBER:
Opening a File:
A file must be opened before it can be used.
FILE *fp;
fp = fopen (filename, mode);
fopen returns a pointer to the file which is used in all subsequent file operations.
Closing a File:
After all operations on a file have been completed, it must be closed.
Ensures that all file data stored in memory buffers are properly written to the file.
getc will return an end-of-file marker EOF, when the end of the file has been
reached.
Exercise: II-3.1
REGISTER NUMBER:
AIM:
To create a C Program for counting the number of lines and characters for a given file.
ALGORITHM:
Step-1: Start.
Step-2: Read the file name.
Step-3: Declare the fopen() in reading mode.
Step-4: The lines and Characters are counted when each line of input from a file or keyboard
will be terminated by the newline character \n.
Step-5: Display the line count and character count.
Step-6: Stop.
PROGRAM:
#include<stdio.h>
void main()
{
FILE *fp;
int ch,nc,nline;
char filename[40];
nline=0;
nc=0;
printf("Enter filename:");
gets(filename);
fp=fopen(filename,"r");
if(fp==NULL)
{
printf("Cannot open %s for reading \n ",filename);
exit(1);
}
ch=getc(fp);
while(ch!=EOF)
{
REGISTER NUMBER:
REGISTER NUMBER:
if(ch=='\n')
nline++;
nc++;
ch=getc(fp);
}
Printf(There are %d of characters and %d lines in %s,nc,nline,filename);
Return 0;
}
REGISTER NUMBER:
OUTPUT:
[secd52@localhost file]$ cc countfile.c
[secd52@localhost file]$ ./a.out
Enter filename:file.txt
There are 35 characters and 3 lines in file.txt
RESULT:
Thus the C Program for counting the number of lines and characters for a given file was
created and executed successfully.
Exercise: III-3.2
REGISTER NUMBER:
FILE COPY
AIM:
To create a C Program for copying the contents of old file to new file.
ALGORITHM:
PROGRAM:
#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
int ch;
fp1=fopen("prog.txt","r");
fp2=fopen("prog_old.txt","w");
if((fp1==NULL) || (fp2==NULL))
{
printf("Cannot open for reading \n");
exit(1);
}
else
{
ch=getc(fp1);
while(ch!=EOF)
{
putc(ch,fp2);
ch=getc(fp1);
}
REGISTER NUMBER:
}
fclose(fp1);
fclose(fp2);
printf("\n The files are successfully copied");
}
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the C Program for copying the contents of old file to new file was created and
executed successfully.
Exercise: III-4
REGISTER NUMBER:
malloc()
Used to allocate a single block of memory
ptr = (cast-type*) malloc(bytesize);
calloc()
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.
ptr =(casttype*) calloc(blockcount, blocksize);
free()
Compile time storage of a variable is allocated and released by the system in accordance with
its storage class.
ree(ptr);
realloc()
REGISTER NUMBER:
The memory allocated by using calloc or malloc might be insufficient or excess sometimes. In
both the situations the memory size already allocated could be changed with the help of function
realloc. This process is called reallocation of memory. ptr = realloc(ptr, newsize);
Exercise: III-4.1
AIM:
To create a C Program for String Reverse using DMA.
ALGORITHM:
Step-1: Start the program.
Step 2: Declare the pointer variable s.
Step 3: Allocate the memory space using malloc.
Step 4: If s = = NULL, allocation is not done. Else done successfully.
Step 5: Get the string from the user
Step 6: Read the string from backward and print the result.
Step 7: Stop the program.
REGISTER NUMBER:
PROGRAM:
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main(void)
{
char *s;
register int i;
s = malloc(80);
if(!s)
{
printf("Memory request failed.\n");
exit(1);
}
printf("Enter the string:");
gets(s);
REGISTER NUMBER:
putchar(s[ i ]);
printf("\n");
free(s);
}
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
[secd52@localhost DMA]$ ./a.out
Enter the string: program
The Resultant is:
margorp
RESULT:
Thus the C Program for String Reverse using DMA was created and executed
successfully.
Exercise: III-4.2
REGISTER NUMBER:
STUDENT AGGREGATE
AIM:
To create a C Program for calculating the Aggregate for a student for n subjects.
ALGORITHM:
Step-1: Start.
Step-2: Read the number of Subjects.
Step-3: Allocate the memory space using malloc().
Step-4: Using for loop, Calculate the average of subjects.
Step-5: Print the Average value.
Step-6: Stop.
PROGRAM:
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
main()
{
int n, i, *a;
float avg, sum=0;
printf("Enter the No. of subjects : ");
scanf("%d", &n);
a = (int*) malloc(n * sizeof(int));
if (a == NULL)
{
printf("\n memory allocations not possible");
exit(-1);
}
printf("Enter %d marks : ", n);
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
REGISTER NUMBER:
}
for(i=0; i<n; i++)
sum += a[i];
avg = sum / n;
printf("Average mark : %.2f\n",avg);
}
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the C Program for calculating the Aggregate for a student was created and executed
successfully.
Exercise: III-4.3
SORTING
AIM:
To create a C Program for Sorting the given set of numbers.
ALGORITHM:
Step-1: Start.
Step-2: Allocate the memory space using malloc().
Step-3: Using for loop Read the input values.
Step-4: Using for loop, Sort the input value:
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Step-5: Print the sorted order.
Step-6: Stop.
REGISTER NUMBER:
PROGRAM:
REGISTER NUMBER:
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
REGISTER NUMBER:
REGISTER NUMBER:
OUTPUT:
RESULT:
Thus the C Program for Sorting the given set of numbers was created and executed
successfully.
REGISTER NUMBER:
CHECK-LIST:
Sl.No:
Completion Details
1.
Observation Completion
2.
Assignment Completion
3.
Mini-Project Completion
4.
Attendance Percentage
Status
Signature