C AND SQL LabBook 2013 PDF
C AND SQL LabBook 2013 PDF
(Computer Science)
WorkBook
Name ______________________________________________________
1
Written and Edited by
2
Foreword
It gives me great pleasure to introduce this lab book for the F.Y.B.Sc (Computer Science)
students. This being the first year of the course, a good foundation laid in this year will
make it easier for students to grasp advanced concepts in the years to come. I congratulate
the University of Pune and all faculty members who have taken the initiative and effort in
bringing out this much needed book.
The laboratory assignments are designed in such a way that they consider the different
learning pace of students and encourage original thinking. There is scope for variations in
the questions posed thereby reducing the possibility of duplication of effort. The
continuous assessment will prove beneficial not only to the students but also the
institutions to gauge the performance of the student over the duration of the course. Most
importantly, the collaborative wisdom of all the experts who have worked on this book
will reach learners in the remotest locations.
I understand that this is the first collaborative effort of its kind. I am sure that it will be
very successful and set a precedent for similar efforts in other subjects as well. I wish it
all success.
3
Table of contents
Introduction ......................................................................................................................1
Assignment Completion sheet...……………………………………………………………. 3
Lab Course II
Section I
Exercise 1..........................................................................................................................6
Using basic DOS commands like date, time, dir, copy con, type, ren etc.
Exercise 2.........................................................................................................................11
Creating the directory structure and Batch file in the DOS
Exercise 3.........................................................................................................................15
Using Windows XP graphical user interface (GUI).
Exercise 4.........................................................................................................................21
Using basic Linux commands
Exercise 5.........................................................................................................................28
Using vi editor
Exercise 6.........................................................................................................................42
Shell Programming (Writing simple shell scripts, use of conditional structures).
Exercise 7.........................................................................................................................46
Shell programming (Writing shell scripts using control structures )
Exercise 8.........................................................................................................................49
Creating simple HTML pages
Exercise 9.........................................................................................................................54
HTML programming (use of lists, tables, frames, hyperlinks)
Exercise 10.......................................................................................................................59
HTML programming ( Creation of forms, small case study to create HTML pages using all
the above learnt techniques).
Section II
Exercise 11.........................................................................................................................64
To create simple tables , with only the primary key constraint ( as a table level constraint
& as a field level constraint) (include all data types)
Exercise 12.........................................................................................................................68
To create more than one table, with referential integrity constraint, PK constraint.
Exercise 13.........................................................................................................................74
To create one or more tables with Check ,unique and not null constraint
Exercise 14.........................................................................................................................76
To drop a table from the database and to alter the schema of a table in the Database.
Exercise 15.........................................................................................................................78
To insert / update / delete records using tables created in previous
Assignments. ( use simple forms of insert / update / delete statements)
Exercise 16.........................................................................................................................82
To understand & get a Hands-on on Select statement
Exercise 17.........................................................................................................................86
To query table, using set operations (union, intersect)
Exercise 18.........................................................................................................................89
To query tables using nested queries
Exercise 19.........................................................................................................................92
To query tables , using nested queries ( use of ‘Except’, exists, not exists clauses)
Exercise 20.........................................................................................................................95
Assignment related to small case studies ( Each case study will involve creating tables with
specified constraints, inserting records to it & writing queries for extracting records from
these tables)
4
Lab course I
Exercise 1.........................................................................................................................100
To demonstrate use of data types, simple operators (expressions)
Exercise 2.........................................................................................................................103
To demonstrate decision making statements (if and if-else, nested structures)
Exercise 3.........................................................................................................................106
To demonstrate decision making statements (switch case)
Exercise 4.........................................................................................................................111
To demonstrate use of simple loops
Exercise 5.........................................................................................................................116
To demonstrate use of nested loops
Exercise 6.........................................................................................................................119
To demonstrate menu driven programs and use of standard library functions.
Exercise 7.........................................................................................................................122
To demonstrate writing C programs in modular way ( use of user defined functions)
Exercise 8.........................................................................................................................125
To demonstrate recursive functions.
Exercise 9.........................................................................................................................128
To demonstrate use of arrays (1-d arrays ) and functions
Exercise 10.......................................................................................................................132
To demonstrate use of multidimensional array(2-d arrays ) and functions
Exercise 11......................................................................................................................136
To demonstrate use of pointers
Exercise 12......................................................................................................................140
To demonstrate concept of strings (strings and pointers)
Exercise 13......................................................................................................................144
To demonstrate array of strings.
Exercise 14......................................................................................................................146
To demonstrate use of bitwise operators.
Exercise 15......................................................................................................................149
To demonstrate structures (using array and functions )
Exercise 16......................................................................................................................152
To demonstrate nested structures and Unions
Exercise 17......................................................................................................................157
To demonstrate command line arguments and preprocessor directives.
Exercise 18......................................................................................................................160
To demonstrate file handling (text files)
Exercise 19......................................................................................................................164
To demonstrate file handling (binary files and random access to files)
Exercise 20......................................................................................................................167
Problem solving using C
References 180
5
Introduction
This workbook is intended to be used by F.Y.B.Sc (Computer Science) students for the two
Computer Science laboratory courses in their curriculum. In Computer Science, hands-on
laboratory experience is critical to the understanding of theoretical concepts studied in the theory
courses. This workbook provides the requisite background material as well as numerous
computing problems covering all difficulty levels.
1) You are expected to carry this book every time you come to the lab for computer science
practicals
2) A file should be maintained separately by each student which should contain the algorithms,
flowcharts, written answers, source code as well as the program output.
3) You should prepare yourself before hand for the Exercise by reading the material mentioned
under icon . Also go through the material given in ready reference icon .
4) If the self activity exercise or assessment work contains any blanks such as this ______, or
6
2) Fill in the blanks with different values for each student
3) Choose appropriate problems to be solved by student by ticking box
4) Make sure that students follow the instruction as given above
5) After a student completes a specific set, the instructor has to verify the outputs and sign in the
provided space after the activity.
6) Ensure that students use good programming practices.
7) You should evaluate each assignment carried out by a student on a scale of 5 as specified
above by ticking appropriate box.
8) The value should also be entered on assignment completion page of the respective Lab course
3. Acknowledgements
The authors wish to express their gratitude to Dr. Narendra Jadhav, Vice Chancellor, University of
Pune, for his vision and guidance in bringing out this lab book, a first of its kind. Dr. Pandit
Vidyasagar, Director, Board of colleges and university department has played a pivotal role in
taking this project to completion. We are indebted to Dr. V. B. Gaikwad, Dean Science Faculty,
who extended his wholehearted support to this endeavor. Prof. Arun Gangarde, Chairperson,
Board of studies in Computer Science deserves a special mention for his untiring efforts during
the entire process.
We appreciate the efforts taken by Prof. Chitra Nagarkar , member, Board of studies in Computer
Science during initial phases of the project. We would like to acknowledge the role played by the
University authorities and the members of the Board of Studies in Computer Science.
Special thanks to Mr. Achyut Godbole, noted IT personality and renowned author who took a lot
of interest in this project.
Our heartfelt thanks to Dr. Sanjay Kadam, CDAC and Ms. Kishori Khadilkar, Patni Computer
Systems Ltd., for painstakingly reviewing the entire book and giving valuable inputs. Last but not
the least, we thank all the faculty members, who have been involved in this project and shared
their expertise.
7
Assignment Completion Sheet
Lab Course II
Section I
Sr. Assignment Name Grade
No
1 Using basic DOS commands like date, time, dir, copy con , type,
ren etc.
2 Creating a directory structure in DOS and batch files.
3 Using Windows XP graphical user interface (GUI).
4 Using basic Linux commands
5 Using vi editor
6 Shell Programming (Writing simple shell scripts, use of conditional
structures).
7 Shell programming (Writing shell scripts using control structures )
8 Creating simple HTML pages (use of different tags for changing
fonts, foreground and background colors etc.)
9 HTML programming (use of lists, tables, frames, hyperlinks)
10 HTML programming ( Creation of forms, small case study to create
HTML pages using all the above learnt techniques).
Section II
11 To create simple tables , with only the primary key constraint ( as a
table level constraint & as a field level constraint) (include all data
types)
12 To create more than one table, with referential integrity constraint,
PK constraint.
13 To create one or more tables with Check ,unique and not null
constraint
8
Lab Course I
Sr. Assignment Name Grade
No
1 To demonstrate use of data types, simple operators (expressions)
2 To demonstrate decision making statements (if and if-else, nested
structures)
3 To demonstrate decision making statements (switch case)
4 To demonstrate use of simple loops
5 To demonstrate use of nested loops
6 To demonstrate menu driven programs and use of standard library
functions.
7 To demonstrate writing C programs in modular way ( use of user
defined functions)
8 To demonstrate recursive functions.
9 To demonstrate use of arrays (1-d arrays ) and functions
10 To demonstrate use of multidimensional array(2-d arrays ) and
functions
11 To demonstrate use of pointers
12 To demonstrate concept of strings(strings and pointers)
13 To demonstrate array of strings.
14 To demonstrate use of bitwise operators.
15 To demonstrate structures (using array and functions )
16 To demonstrate nested structures and Unions
17 To demonstrate command line arguments and pre-processor
directives.
18 To demonstrate file handling (text files)
19 To demonstrate file handling (binary files and random access to
files)
20 Problem solving using C
9
Lab Course II
Section I
10
Exercise 1 Start Date / /
Using basic DOS commands like date, time, dir, copy con , type, ren etc.
Operating system is an interface between the user and the computer hardware. MS-DOS
(Microsoft’s Disk Operating System) runs on any of the Intel 8088,80x86 or Pentium class CPU’s
on a Personal computer platform. The version of MS-DOS that runs on early IBM computers is
called PC-DOS.
DOS is a 16-bit, single tasking, single-user operating system. It operates in real mode , meaning
that only one program or process can run at a time. There is a 640 KB limit on memory that is
accessible to the applications. The applications, directly access and control the hardware like
printers bypassing the operating system. DOS has a simple text-based command line interface
and it comprises of three files – MSDOS.SYS, COMMAND.COM and IO.SYS.
An operating system allows you to store and access information on a computer which can be
letters, favourite music, family pictures, reports etc. Every piece of stored data accessed by the
computer is treated as a file and is assigned a unique name. DOS uses a “8.3” filename, which
can be up to eight characters long followed by a period and an extension of three characters. It
cannot contain characters such as this “ / \ [ ] : ; = , .
When the number of files stored on a disk attached to a computer increases, it need to be
organized. The disks with large capacity are split into one or more partitions or drives. Each
partition, drive or volume is given a name such as ‘C’ , ‘D’ etc. Files in a partition are organized
into directories which are organized similar to tree structure.
C:\
Myletter.txt
trial
office Acrobat
Accessories
abc.txtc
et
Calculator.exe
Notepad.exe Paint.exe
Every file has path starting from root through subdirectories reaching a file. Path of file paint.exe
is c:\Programs\Accessories\paint.exe
You can execute DOS command on Windows XP by getting the console with a DOS prompt by
executing command program or choosing command prompt from Programs- Accessories.
11
In Windows XP, Select the following path :
Start -> Programs -> Accessories -> Command Prompt
It will display command prompt as C:\> _ , by default. The DOS commands can be typed at this
prompt.
1. Internal Commands
12
COPY Used to copy or append files C:\> copy <source> <destination>
to other files. C:\> copy con a.txt
Copies the contents typed at the console to file
a.txt. Input has to be terminated by Ctrl+Z.
C:\> copy a.txt b.txt
C:\> copy a.txt + b.txt c.txt
Copies the appended file of a.txt and b.txt to c.txt
C:\> Copy c:\d2\d21\c.doc d:
Copies files c.doc to floppy in drive d by the
same name
DEL Used to delete a file C:\> Del filename
C:\> Del a.txt
TYPE Display the contents of the C:\> Type <filename>
file on the screen or it can be C:\> type a.txt
sent to the printer . C:\> type a.txt | more
C:\> type a.txt > prn
RENAME Changes name of an existing C:\> ren <old_filename><new_filename>
or REN file. C:\> ren a.txt b.txt
PATH Used to display the current PATH [[drive:] path ][;[drive:] path …]]
path or set a new search path C:\> Path
for the executable files. Displays the current search path as
PATH C:\DOS; C:\system32; D:\PROGRAMS
Any executable program will be first searched in
DOS, then system32 and then PROGRAMS
directory
External Commands
13
Type the following commands and explain what the command is used for and give the output of
the command
Sr. No Command Explanation Output
1 copy con my.txt
2 copy my.txt ab.txt
3 dir *.txt
4 ren *.txt *.bak
5 dir
6 attrib +h ab.bak
7 dir *.bak
8 ver
9 type my.bak
10 path
11 cls
12 help dir
13 dir /A:h
14 help attrib
15 del my.bak
Set A
Give the DOS commands to be used to perform following set of tasks
1.
2.
Sr. No Task Command
1 Create a file named a.txt containing the
college details
2 Change the name of the above file to
college.txt
3 Create a copy of the file by name
course.txt
4 Display the contents of the file course.txt
5 Change the file attribute to read only
3.
Sr. No Task Command
1 Display the files which have the extension
txt
2 Rename the extension from txt to doc
3 Remove all the files created starting with
14
the name 1
4 Chkdsk any of the drives with display and
correction options
5 Set a new search path
4.
Sr. No Task Command
1 Create a file named a.txt containing
names of five students
2 Change the name of the file to b.txt
3 Create a copy of the file by name copy.txt
4 Display the contents of the file copy.txt
5 Change the file attribute to hidden
6 Display the current path
Set B
1. By pressing the arrow keys, the commands those have been used can be used again. How is
it really being done?
2. Create a file, change it into Read only file. Create one more file with the same name. Are
both the files existing or any one is only existing? Why?
3. Display the file content pagewise if it goes more than the page.
4. Set the date to 02-30-09. Does the system accept the date? Why?
15
Exercise 2 Start Date / /
Directory system is used for organizing the files. The directory is a group of files stored together
and identified by a name. The directories are organized in a hierarchical structure i.e. a directory
can contain subdirectories which in turn can contain files and / or more directories.
A batch file is a simple text file with an extension .BAT. It contains a set of DOS commands when
the name of batch file is typed at the DOS prompt, all the DOS commands within the file are
executed one by one
We will study the dos commands for creating and maintaining directory structure
16
IF Checking conditions before If [NOT] string==string2 command
executing a command If [NOT] exist file command
If [Not] errorlevel number command.
SHIFT All parameters are shifted
one position to the left.
AUTOEXEC.BAT (automatic execution batch file) is a special batch file, found in the root directory
of the boot disk. This file will automatically run before control of the computer gets turned over to
the user.
@Echo OFF
Path C:\DOS;C:\;C:\BAT;C:\UTILITY;
Prompt $p$g
Set TEMP=C:\Temp
C:\Utility\NumLock -
CD\
CLS
This file sets the PATH, defines a prompt and a temporary directory, runs a utility program,
changes to the root directory and then clears the screen.
Type in the following set of commands to create a batch file named mydir.bat
Execute the batch file mydir.bat by typing mydir at the prompt. Use dir and cd command to view
the directory structure created
17
Set A
1. Create the following Directory Structure in the current directory containing directories and file
and also remove it. Write down the commands used for the exercise
2. Create the following Directory Structure in the current directory and also remove it. Write
down the commands used for the exercise.
Set B
18
2. Create the following directory structure by passing dummy parameter to batch file.
3. Create a BACKUP directory with two directories TXT and BAT. Copy all batch files with .bat
extension to BAT directory, all files with .txt extension to TXT directory. Delete all files with
.bat extension. Give appropriate message and pause before deleting the file.
1. Create a new directory with a new.txt file in it. Change the attrib to hidden. Now use the dir
command to view the contents of the file. What are the contents you see? Why? Can you use
a different command to get the actual directory contents?
19
Exercise 3 Start Date / /
Microsoft has been making OS software utilizing graphical user interfaces since around 1985.
Some of the earlier windows versions were Windows 3.1 (1990), Windows 95 (1995), Windows
98 (1998), Windows ME (2000), Windows 2000 (2000), and Windows XP (2001). Windows XP
comes in two bundles Windows XP Professional and Windows XP for home users. Windows 2000
and Windows XP are personal operating systems when used as stand alone machines but can be
considered network operating systems when connected to a network. An operating system is a
collection of programs, which enables the entire pc to work. Some of the tasks that are performed
by Windows are:
1. Assisting in starting and shutting down of a pc.
2. Controlling and handling the hardware, including RAM, I/O cards etc.
3. Providing a graphics user interface including various features.
4. Provides a platform for applications to execute like Word.
5. File Handling.
6. Provides an interface for various tools like Internet explorer.
Drives are devices used to store data. Most computers have at least two drives:
hard drive C:\ (Which is the main storage and a floppy drive or a CD drive
(which stores smaller volumes of data) The hard drive is typically designated as
C:\ drive and the floppy drive is typically designated as A:\ drive. You will also
have other drives typically labelled D:\ or F:\ or H:\ or G:\
Folders /
Directory
Folders are used to organize the data stored on your drives. A Directory is the
path given to a folder on a drive. For example a text file called Hello World is
located in the My Documents directory on the C:\ drive. It would therefore read
"C:\My Documents\Hello World.txt"
File File Extensions are the ending letters associated with a file and an application
Extensions that it can be manipulated in. This way Windows knows to tell which program to
open the file you want to manipulate. For example a text file has an extension
20
of .txt, so a text file created in Notepad called Hello World would look like -
Hello World.txt. You do not have to assign a file extension to a file that you
create. The program you use will automatically do this for you. All you need to
do is give it a filename. Some other common extensions are as follows:
An Icon is a graphic image. Icons help you to execute the application programs
quickly. Commands tell the computer what you want the computer to do. To
execute the application program by using an icon, double-click on the icon.
Desktop
After starting your computer, the desktop is the first thing that you see with
some background image displayed on the screen with icons for various
programs. The desktop is the area you work in.
Taskbar
The taskbar is usually located on the bottom of the desktop. The Start button,
active program buttons, and the system tray are located on the Taskbar
Start Menu
Start menu guides you how to start with the various application programs that
are available on your windows system.
21
We can choose the view of start menu by right clicking on the start
button properties start menu.
System
Tray The System Tray is usually located in the lower right hand corner of the
Windows Desktop. The system tray contains a display of the current computer
time, and the icons representing the programs activated when Windows first
starts up. These are the background running applications required for smooth
running of windows.
My
Computer
My Computer icon provides access to the different parts of your computer. You
can access the different drives (Hard Drive, Floppy Drive, and Network Drives)
inside My Computer.
Recycle
Bin
When you delete an object, just by pressing Del key, Windows XP sends it to
the Recycle Bin. You can restore objects that are located in the Recycle Bin or
you can permanently delete them by right clicking on the Recycle Bin and
select Empty Recycle Bin.
My
Documents
The My Documents folder is nothing more than a regular folder that resides on
your Windows Desktop. However, it offers an easy-to-reach location where you
can store and retrieve important data, and the icon is always available in
Windows explorer and on the desktop. You can double-click My Documents
icon, click the File menu, point to New and click Folder to create folders. This is
the default destination folder offered by windows system where the entire user
created documents gets stored.
Internet
Explorer
The Internet Explorer icon launches the Internet Explorer browser. The Internet
Explorer browser is what you will use to access the Internet and the World
Wide Web.
Window
22
Every application when executed opens a window.
Window
Title Bar
Title bar shows the name of the Application we are in.
Menu Bar
The menu bar contains the menus that will allow us access to all the
operations that can be done with a file or folder
Standard
Bar
Tool Bar
Windows Explorer
Windows Explorer is the basic shell or user interface or an indispensable tool in the operating
system, with the help of which we can organize and control the files and folders of the different
storage systems at our disposal such as the hard drive, disk drive, etc. Its properties and
characteristics are something we deal with every time we use the computer. The Windows
Explorer is also known as the File Manager. Through it we can delete, view, copy, or move files
and folders.
The fastest way to get to the explorer is by pressing key combination windows
key + e using the modern keyboards or by right clicking the start button and
selecting the explore menu option as shown above
The other would be click start -> programs -> accessories -> windows
explorer
23
Components
of the
explorer
The explorer consists of two sections. On the left side there is the directory
tree, which is the list of units and folders in the system. Only units and folders
appear and no files. On the right side there is another section, which will show
the contents of the folder that we have selected in the left section. Depending
on the type of view that we have activated, we will see different type of
information regarding the files. In detailed view, we see the name, size, type,
and date of last modification for each file. The windows explorer view can be
customized according to each user. There is a View menu option available,
with the help of which each user can select his/her own way of displaying files
and folders
1. Click on Start button. Select Search -> For Files And Folders. Search for the file
________________________ and write down the entire path of the file
2. Click on Start -> Run. Browse to the _______ application in _____ folder and execute the
application
3. Right click on the desktop and list down the menu items.
4. Right click the My documents folder and view its properties
5. Create folder for you in the My documents folder. Right click the folder and view its
properties and write down its path and size
6. Click on Start button. Click control panel and write any three parts
7. Right click on the desktop. Select New -> Shortcut and browse to create a new shortcut for
______ application.
8. Use All programs in start menu, point to accessories and write down the options available in
system tools (If you are in classic start menu change it to start menu before executing this
command).
9. Right click on the taskbar and list down different menu items.
10. Open the explorer as directed above and list down all the menu items on the menu bar.
11. Click on the view menu option and list out the different appearances of thumbnails, tiles,
icons, list, and details options.
12. Select the ___________ folder and write down the information given in the status bar.
(Note: If the status bar is not to be seen you would need to make it available by selecting View
option).
13. Double click the computer icon on the desktop. Check which window is opened. Is it similar
to the windows explorer? What is the difference between the two?
Set A
24
1. Use Notepad option available in accessories to create a file and save it in the folder created
by you
2. Use Paint option available in accessories to create an image and save it in the folder created
by you
3. Use Disk Defragmenter tool from system tools
4. Use control panel to change the screen saver .
5. Right click the task bar and select the Task Manager option. Name the applications that are
currently running.
6. Double click on the time located at the bottom right corner on the system tray. Set the time
zone to __________. How much is the time difference between ___________ and Indian time
zone?
7. What happens when you select the Run Desktop cleanup wizard by right clicking the
desktop and selecting the arrange icons by option?
Set B
1. Create a new word document in the selected folder through the File menu option.
2. By right clicking the newly created file list out the properties.
3. Right click the newly created file. Select the ________ option (e.g. cut, copy, send to etc.)
and perform the specified operation and observe the results.
4. Click MyComputer on the left hand side panel. Right click on any drive and select sharing
and security option. Select the sharing tab and do the ______________settings.
5. Share the folder created by you by right-clicking on the folder. Use control panel ->
administrative tools to see the shared folders. In which option of the administrative tools can you
see the shared folders.
6. Customize the entire explorer by selecting / deselecting various toolbars from view
toolbars.
25
Exercise 4 Start Date / /
26
• ksh or the Korn shell: A superset of the Bourne shell
All LINUX commands are case sensitive single words optionally having arguments. One of the
argument is options which starts with “–“ sign immediately followed by one or more characters
indicating option. The wild-cards or metacharacters “*” and “?” have similar meaning as in
DOS.The “*” character matches any number of characters while”?” matches a single character.
The backquote “ ` ” is another metacharacter. Shell executes the command enclosed in
backquote in its place. Any wild-card is escaped with a \ character to be treated as it is
Shell Variables
There are number of predefined shell variables called system or environment variables which are
set by the system when the system boots up. Some important system variables are
PATH It contains set of paths where the system searches for
an executable file
HOME It is the home or login directory where the user is placed
initially
PS1 It is the primary shell prompt which is usually $
PS2 It is the secondary shell prompt which is usually >
Linux files may or may not have extensions. A file can have any number of dots in its name. Linux
file names are case sensitive. The root directory represented by / is the topmost directory file
containing number of subdirectories which in turn contains subdirectories and files
Shell Commands
The following is the list of shell commands
Command Used for Example
date Displays both date and time $date
The command can be used by the Format specifiers can be used as
system administrator to change date arguments
and time. %m month in integer format
%h Name of the month
%d Day of the month
%y Last two digits of the year
%H hours
%M Minutes
%S Seconds
$date +%H
$date +”%h %m”
cal Displays the calendar $cal 8 2007
Displays the calendar for the month
august of year 2007
$cal aug
Displays the calendar for the month
august of current year
27
cat Displays the contents of the files used $cat
with the command Displays immediately what is typed
when you hit enter key
$ cat > abc.txt
Whatever number of lines typed till
you press ^D are placed in abc.txt file
$cat abc.txt
Displays contents of file abc.txt
ls Displays the contents of current $ls
directory. A single dot ( . ) stands for the lists all files in the current directory
current directory while a double dot( .. )
$ls –a
indicates the parent directory
Lists also the hidden files
$ls –l
Lists the permission information
along with other information such as
date of last modification, size in
blocks etc. The first column of the
output exhibits the file type and
permissions.
File type: -, d, b respectively for
ordinary, directory and block device
file.
Permissions are of the form r, w, x, -
i.e. read, write, execute and none
respectively.
There are three groups of rwx.
Owner, group and public.
mkdir Creates specified directory in the $mkdir bin
current directory, fails if a file or Creates bin directory
directory by that name is already
$mkdir dir1 dir2 dir3
present or user is not having
permissions to create a directory Creates three directories dir1, dir2
and dir3
cd Switches to specified directory, fails if $cd /
user is not having permissions to Switches to root directory
access the directory
$cd
Changes to HOME directory
rmdir Removes specified directory fails if the $rmdir dir1
directory is not empty Removes dir1 directory
$rmdir dir2 dir3
Removes dir2 and dir3 directories
cp Creates an exact copy of a file with a $cp abc.txt xyz.txt
different name Copies abc.txt into a new file named
xyz.txt
$cp abc.txt bin
Copies abc.txt into a new file with the
same name in bin directory
mv It renames a file or moves a group of $mv xyz.txt pqr
files to a different directory
rm Deletes specified file. It can be used $rm pqr
28
with wildcards * and ? as in DOS, to
delete all files of a specified type
pwd Displays the path of your present $pwd
working directory displays the directory in which you
are currently working
wc Counts words, lines and characters or $wc –c abc.txt
bytes Displays the number of bytes in the
file abc.txt
$wc –l abc.txt
Displays the number of lines in the
file abc.txt
$wc –w abc.txt
Displays the number of words in the
file abc.txt
$wc abc.txt
Displays the number of bytes, words
and lines in the file abc.txt
grep The syntax is $grep Agarwal names.txt
grep options pattern filename Displays lines in the names.txt where
It displays the lines in the file in which the string “Agarwal” is present
the pattern is found $grep –n Agarwal names.txt
Displays lines along with line
numbers in the names.txt where the
string “Agarwal” is present
29
Redirection and pipes
The most of the above commands take some input, do some processing and give the output or
give error message in case there is some error. For example the cat command is usually given as
$cat filename. Here cat command takes input from file named filename and gives output on the
console. If the file is not present then it gives appropriate error message. By default the cat
command writes the output or error message to the console. If we just type cat command without
any filename, it will wait for user to type characters that means, it by default is expecting input
also from console. The default files where a command reads its input, sends its output and error
messages are called standard input(stdin), standard output(stdout) and standard error(stderr)
respectively.
By default all the above three files are attached with the terminal on which the command is
executing. Therefore, every command, by default, takes its input from the keyboard and sends its
output and error messages to the display screen. Redirection is used to detach default file from
the command and attach some specific file. Pipes allow you to send output of one command as
input to the other command. The commands that are connected via a pipe are called filters
Output Redirection > It detaches the console from $cat > file1
the standard output of Takes its input from
command and attaches keyboard by default and
specific file writes the output to file1,
effectively whatever typed
at the keyboard goes into
tempfile
$cat file1 abc.txt > file2
The contents of file1 and
abc.txt will be
concatenated and send to
file2
$cat file1 > /dev/lp0
The contents of file file1
will be sent to printer
instead of console
Output Redirection >> In output redirection the file is $cat file1 > file1
without overwriting cleared before writing to it. The file1 contents will be
The >> is used so that output cleared
is appended and not $cat file2 >> file2
overwritten The file2 will have its
contents appended to it
Pipe | The pipe character | is used $ ls –l | grep “abc”
between two commands so Displays the line in the
that output of first command output of ls –l containing
is send as input to the second pattern abc
command
Execute all the commands given in the example column of all the tables above in the same order
and understand the usage of the commands
30
Set A
1 Using cat command, create a file named ‘names.txt’ containing at least ten names and
addresses of your friends ( firstname , surname, street name, cityname ). Type the following
commands and explain what the command is used for and give the output of the command
2 Using cat command create a file named college.txt containing at least ten names and location
of colleges ( collegename, place , pincode ). Type the following commands and explain what the
command is used for and give the output of the command
Set B
Give the commands to perform the following actions and give the output
1 List the last three lines of the file ______
2 Create a file named ______containing abc.txt appended to itself
3 Display the current month(string) and year
4 Display the home directory followed by path
5 Write the contents of directory to a file
6 Append at the end of a file no of lines and the name of the file
7 Create a file named Manualcp containing manual for cp command
31
Set C
Give the commands to perform the following actions and verify by executing the command
1 Display the number of lines containg pattern “___ “ in first five lines of the file _____
2 Display the calendar of current month
3 Store the number of users logged-in in a file _____
4 Create a file containing first three and last three lines of a file.
5 Create a file containing word count of each and every file in the current directory plus a total
at the end.
6 Create a single file containing the data from all .txt files in the current directory.
32
Exercise 5 Start Date / /
Using vi editor
Editor vi was developed by the University of California at Berkeley and is also supplied with the
Berkeley distribution of the UNIX system. We are dividing the discussion into three parts –
Introduction to vi, useful commands of vi and advanced and miscellaneous vi commands. We will
first look at the table exhibiting the summary of vi Commands and then we will see the detailing of
the vi commands.
33
string
*34 n Repeat last / or ? *44. :q Quit
*35 N Reverse of n *45. :q! Quit (override check)
Miscellaneous *46. :ed-cmd Run the ed command
ed-cmd
*36. u Undo previous *47. :num Go to line num
command
37. U Restore entire line 48. ZZ Same as :wq
*38. Yobject Save object in temp
buffer
39. Y Save line(s) in temp
buffer
*40. p Put saved buffer after
cursor
41. P Put saved buffer
before cursor
Entering into vi
You can run the vi command just as normal Unix/Linux command. As a result you will get the
screen, printing about the file name, number of lines and number of characters at the bottom of
your screen.
$ vi names ↵ where (↵) is an enter key throughout this documentation.
~
~
~
~
~
~
~
~
~
~
~
“names” [New File] 0,0-1 All
The cursor is shown as _ and is placed in the upper left corner when vi starts. A ~ in the first
column indicates the file doesn’t have enough lines to fill up the screen. The bottom line is the
message line.
The vi editor uses two types of mode to deal with the file operations: insert mode and command
mode.
The vi editor allows getting into insert mode by pressing a respective characters cause to enter
into insert mode. It also allows getting into command mode by pressing ESC key or “:” character
sequence. The ESC key is to come out from the current activity and “:” character behaves like a
prompt where you execute the commands of vi editor. We are discussing vi editor command in
the control command section and into other few sections.
N.B. vi editor follows two modes – insert mode and the command mode.
34
We are following the demo in the sequence shown below.
Command Format
Action taken
Getting more comfortable with the moving around the screen, we are now trying to add some text.
To add the text into the file through vi editor you need to enter into the insert mode. The insert
mode of the vi editor follows two scenario.
Using the “i” (Insert) command
Using the “a” (append) command
_ i John
~ Jim
~ John Pat
~ Jim Steve_
~ Pet ~
~ Steve ~
~ ~
“names” 0 lines 0 characters Insert text INSERT
After the ESC is pressed, the cursor moves back to the last character inserted, just as with the “a”
command.
35
John Joxxyyzzhn
Jim a Jim
Pat Pat
Steve xxyyzz Steve
~ ~
~ add xxyyzz ~
~ ~
“names” 4 lines 19 characters INSERT
When you are done adding text, you press the ESC key. When you press ESC key, the cursor
moves back to the last character you entered.
You can even put ↵ RETURNs (CR) in the added text, and new lines appear.
Joxxyyzzhn Joxxyyzzone
Jim a twohn
Pat Jim
Steve oneCR Pat
~ twoESC Steve
~ ~
~ ~
~ ~
embedded CR
The appending started between the z and hn of the first line, causing the hn to be carried to the
↵) was pressed.
next line when the CR i.e. (↵
1. Perform the following changes to your file. Specify the command and the resulting text as a
answer.
Action Command typed Result
Change Jim in line 3 to Jirem
Insert a new line “Tom and Jerry” after
line number 3.
Insert a new line at the end
Moving Around
This is very essential to know about how to move the cursor around the screen to make additions
or changes. The basic screen motion commands are h,j,k and l, situated next to each other on the
36
right side of the keyboard. The motions for h,j,k and l are left, down, up and right, respectively. H
= , j= ↓, k=↑, l=.
Joxxyyzzone Joxxyyzzone
twohn j twohn
Jirem Jirem
Tom and Jerry Tom and Jerry
Pat Pat
Steve Steve
~ ~
~ ~
Move down
Joxxyyzzone Joxxyyzzone
twohn j twohn
Jirem Jirem
Tom and Jerry Tom and Jerry
Pat Pat
Steve Steve
~ ~
~ ~
Move right
Joxxyyzzone Joxxyyzzone
twohn k twohn
Jirem Jirem
Tom and Jerry Tom and Jerry
Pat Pat
Steve Steve
~ ~
~ ~
Move up
Joxxyyzzone Joxxyyzzone
twohn h twohn
Jirem Jirem
Tom and Jerry Tom and Jerry
Pat Pat
Steve Steve
~ ~
~ ~
Move left
37
You can precede these keys with numbers, which allows you to move more than one column or
line at a time. Command is nj, nh, nk or nl. For example
3j – move 3 lines down.
3h – move 3 columns left.
3k – move 3 lines up.
3l – move 3 columns right.
If you try to move past the beginning or end of file, vi will “beep” at you.
Consider the file contents given below.
Joxxyyzzone
twohn
Jirem
Tom and Jerry
Pat
Steve
~
~
2. Perform the following operation with your file by specifying the command and the resulting
text as answer.
Action (from current cursor position) Command typed Result
Move __ lines down
Move __ columns right
Move __ columns left
Move __ lines up
• Deleting Text
Here we are focusing on how to delete a text. There are two commands that delete text in vi: x
and d.
To delete one character, you use the “x” command. “x” deletes the character at the end current
cursor position, moving the rest of the line left into the void created by the deleted character.
Joxxyyzzone oxxyyzzone
twohn x twohn
Jirem Jirem
Tom and Jerry Tom and Jerry
Pat Pat
Steve Steve
~ ~
~ ~
Delete j
The “x” command can be preceded by a number to indicate how many characters you want to
delete. You will get the “beep”, if you are trying to delete nonexistent characters.
oxxyyzzone xxyyzzone
twohn nx
twohn
Jirem Jirem
Tom and Jerry Tom and Jerry
Pat 2x
Pat
Steve Steve
~ ~
~ ~
Move down
38
Sometimes you want to delete the entire line. The “x” command will get rid of all the characters on
a line, but it won’t get rid of the line itself. To delete a line, you use the dd command, a special
case of a more general delete. It can be preceded by a number to indicate the number of lines to
delete.
xyyzzone twohn
twohn dd Jirem
Jirem Tom and Jerry
Tom and Jerry Pat
Pat dd Steve
Steve ~
~ ~
~
Delete xyyzzone
The “dd” command can be preceded by a number to indicate how many lines you want to delete.
Highlight the cursor at the beginning of Jirem.
twohn twohn
Jirem ndd Pat
Tom and Jerry Steve
Pat 2dd ~
Steve ~
~
~ Delete
Jirem
Tom and Jerry
3. Perform the following operation by specifying the command and the resulting text as answer.
Action (from current cursor position) Command typed Result
Delete 2 characters
rd
Delete 3 characters from 3 line
st
Delete 1 line
th
Delete 4 line
Miscellaneous Command
If we need to undo the activity, it is achieved by means of “u” command.
undo delete
39
Cut the line(s) from the desired cursor position and paste those lines to the desired cursor
position
twohn dd twohn
Pat Steve
Steve ~
~ ~
~
Cut line
Pat
The “p” character is used to paste the line(s) before the desired cursor position.
twohn p twohn
Steve Steve
~ p Pat~
~
Paste line
after
steve
Copy the line(s) from the desired cursor position and paste those lines to the desired cursor
position
twohn yy twohn
Steve Steve
Pat yy Pat
~ ~
~
Copy line
Pat
The “p” character is used to paste the line(s) before the desired cursor position.
twohn p twohn
Steve Steve
Pat p Pat
~ Pat
~ ~
Paste line
After steve
40
:num –command moves the cursor to the specified line number scrolling if necessary.
twohn twohn
Steve Steve
t t
t :3 t
~ ~
~ ~
~ ~
:3 ~
:set nu – command allows you to show the line numbers for the line(s) present in the screen
editor.
twohn 1 twohn
Steve 2 Steve
t 3 t
t 4 t
~ ~
~ ~
~ ~
: set nu ~
4. Perform the following operation by specifying the command and the resulting text as answer.
Action (from current cursor position) Command typed Result
Cut line 2, 3 and put those after twohn
Copy line 3 and put it after line 4.
Undo all the changes
Locate the content at line 2
• Control Commands
• Saving the file
The vi editor also changes a copy of the file that must be written before the file is actually
changed. There are several ways to write file in vi editor, but the easiest way is through the “ZZ”
command that automatically write the file and quit, putting you back on to the shell prompt.
twohn ZZ twohn
Steve Steve
t t
t t
~ ~
~ Write ~
~ “names” “names” 4 lines, 16 characters
“names” 4 lines, 16 and quit $ _
41
1. :w – command write the file without quitting vi editor.
twohn twohn
Steve Steve
:w
t t
t t
~ ~
~ ~
~ ~
Write
:w
with the “names” 4 lines, 19 characters
file
:wq – command write the file and put you back on to the shell prompt.
twohn :q twohn
Steve Steve
t :q t
t t
~ ~
~ quits ~
~ from file “names” 4 lines, 19 characters
:q $_
42
4. Perform the following operation by specifying the command and the resulting text as answer.
Action (from current cursor position) Command typed Result
Create the file called “test “ to test the other
commands containing text as shown below
Apply operations covered so far on the file
Police inspector
came by and asked Q “who is this
guy?”
Q replied, “I don’t know, but his
face rings a bell.”
~
~
~
String Searching
The vi editor can search for strings, by typing in a “/”followed by the string you want to search for
followed by a CR (↵). The vi editor then scans for the next occurrences of the strings.
5. Perform the following operation by specifying the command and the resulting text as answer.
Action (from current cursor position) Command typed Result
Search for keyword guy
Word Commands
The vi editor knows about objects called words that are simply letters and numbers separated by
blank, tabs or punctuation marks. The vi editor allows you to move from word to word, delete
them and change them with simple commands.
43
1. w command
Moves the cursor to the next word.
2. b command
Moves the cursor backward a word.
3. e command
Moves the cursor to the end of a word.
44
Dw command – command is use to delete a word.
Set A
1. Create a file by name _________ at least 25 lines long using vi editor’s input commands – “a”
and “i”. Also try the replace mode by examining the toggle feature of “i” character.
2. Create a file by name _________ at least 25 lines long using vi editor’s input commands – “a”
and “i”. Also try search command on the file.
Set B
1. Create a file name _____ containing five lines and execute the following set of commands of
vi editor and describe the result on the paper.
45
4 O
5 n
6 N
7 dw
2. Create a file name _____ containing five lines and execute the following set of commands of
vi editor and describe the result on the paper.
Sr. No Command
1 cc
2 D
3 C
4 s
5 S
6 rchr
7 R
46
Exercise 6 Start Date / /
The set of internal commands provided by shell can be combined into a language with its own
variables, operators, conditional statements and loops called shell programming language. It
helps in combining basic shell commands into a complex service commonly required by users.
The UNIX system administrator should be an accomplished shell programmer. Shell programs
run in interpretive mode ,i.e., one statement at a time.
Shell program is stored in a file usually with .sh extension.
The shell program can be executed in one of the following ways
a) using sh command along with the file name for example $ sh myshell.sh
In case the program accepts filename as command line argument then
$sh myshell.sh file1
b) Make the file executable by using chmod command and then typing the filename at $
prompt for example
$ chmod +x myshell.sh
$ myshell.sh
In case the program accepts two integers as command line argument then
$ myshell.sh 45 36
The command line arguments specified to a shell procedure are assigned to certain special
variables or positional parameters such as $0, $1 etc.. $0 stores the filename of the shell script,
while $1 is first argument, $2 is second argument and so on. $* stores, the entire list of
arguments, as a single string. $# stores the total number of arguments passed to the script. The
positional parameter $?, Stores the exit status of the last command. It has the value 0 if the
command succeeds, and a non-zero value if the command fails.
47
echo to display output to user. echo “ Give your name”
echo “Enter first number”
expr It is used to do arithmetic sum=`expr $a + $b`
operations as also convert string x=`expr $x + 1`
to integer.
Test Evaluates expression on its right x=5; y=7;
[ ] or evaluates expression within test $x –eq $y ; echo $?
square brackets
read choice
If [ $choice =”y” –o $choice =”Y” ]
then
exit
If - then fi For conditional branching If grep “$1” $2
echo “pattern found”
if - then - else - fi For Two-way conditional If [ $# -eq 1 ]
branching then
cat $1
else
echo “ wrong no of arguments”
fi
If - then - elif - Nested if statements If [ $# -eq 3 ] ; then
then - else - fi # semicolon separator is required
# as if and then are on same line
grep “$1” , $2 > $3
elif [ $# -eq 2 ]
grep “$1” $ 2
else
echo “ wrong no of arguments “
fi
case - esac Multiple branching read answer
case $answer in
[yY]*) exit ;; #matches Yes yes
[nN]*) echo No ;;
*) echo “Invalid response”
esac
Sample programs
Sr. Program statement Program code
No
1 An interactive program that #The program accepts the date
accepts month name and echo “enter the date”
checks with current date if the read dt
person is late a= `date +%d`
# a stores the day value of current date as string
a=`expr $a + 0`
# converting to integer
# note space before and after +
if [ $a -gt $dt ]
# note space before and after brackets
48
then
echo “You are late by $a -$dt days”
fi
2 A command line program that # program accepts two arguments
accepts only two arguments if test $# -ne 2 ; then
and outputs sum and product # semicolon separator is required as if and then
of the two # are on the same line
echo “wrong number of arguments”
else
tot=`expr $1 + $2`
# * is escaped to be treated as mult operator
# and not as a wild character
prod=`expr $1 \* $2`
echo The total is $tot
echo The product is $prod
fi
Type the examples given for different statements in files with .sh extension and execute them
1. Type the sample program 1, execute it for different date values and modify it to a program
that decides the file as late by accepting both month and date. Modify the program to one that
accepts value as command line arguments
2. Type the sample program 2, execute it for different values and modify it to a program that
prints quotient and divisor of command line arguments. Modify the program to one that accepts
values interactively from user.
3. Type the sample program 3, execute it for different values and modify it to a program that
checks for a regular file if it is readable or writable giving appropriate message.
Set A
1. Write a shell script to accept a file name, check if it is regular & show it’s contents. (use cat
command)
2. Write a shell script to accept a file name, check if it is regular & display number of words in a
file. (use wc command)
49
3. Write a shell script to accept a name, check if it is directory & display its contents. (use ls
command)
4. Write a shell script to accept a file name, and accept a pattern and display lines from the file
in which the pattern is present. (use grep command)
5. Write a shell script to accept a name, and create a copy of it named as this name-
(hypen)copy in the same directory . (use cp command)
6. Write a shell script to display “ Good Morning”, “ Good afternoon” , and “Good evening”
depending on the hour (use date command)
Set B
1. Write a shell script to accept argument string , and display present working directory if
argument string is “current” ,display parent directory if argument string is “parent” and display the
contents of root directory if argument string is “root” (use pwd, cd and ls command)
2. Write a shell script to accept an extension name such as txt and display the contents of all
files with this extension, if there exists a file with this extension or give appropriate message (use
cat with wild cards and ls)
3. Write a shell script to accept as argument an extension name such as .txt and move the
contents of all files with this extension to a directory by the same name (use mkdir and mv)
4. Write a shell script to accept a file name , and display file details if the file exists and a
suitable message if it does not. (use grep and ls)
Set C
1. Write a shell script which accepts a filename, displays menu with following options, accepts
user choice as number and takes appropriate actions
2. Write a shell script that displays menu with following options, accepts user choice as number
and takes appropriate actions
3. Write a shell script that displays menu with different DOS commands, accepts user choice
as letters of the command and executes appropriate linux command after accepting required
arguments as given below.
50
Number Menu option Linux command
1 Dir use ls
2 Copy Accept filenames and use cp command
3 Type Accept filename and use cat command
4 delete Accept filename and use rm command
5 date Use date
51
Exercise 7 Start Date / /
Some shell commands are specially useful when writing shell programs.
We will consider some of them
52
fields , -d is used for specifying delimiter $cut –c 1-10, 17-20 dirfile
$cut –d’ ‘ -f 1,6 dirfile
Type the examples given above for “while” , “until” and “for” and execute them in that order. Use
shell commands to verify the outcome.
Write the outcome when you execute the following set of commands at shell prompt
1 name=date
$name
`$name`
2 set `date`
shift
cal “$5”
3 set `wc abc.txt`
shift
echo the number of characters is $2
4 set `who`
shift
echo My terminal is $1
5 who > userlist
cut -d’ ‘ –f 1, 3 userlist
Set A
1. Write a shell script which prints file name followed by first line of each file in the current
directory.
2. Write a shell script which checks if any of the strings in the output of date command are
present in the dirfile
3. Write a shell script which accepts directory names till a valid directory name is given. It
should give appropriate message if directory is not present.
4. Write a shell script to print the information as to how many files and how many directories
are present in current directory.
Set B
1. Write a shell script to print the information of all files in current directory in the following
format
Name of the file -followed by name of the file
Directory - followed by yes or no
Date of last modification - followed by date of last modification
Size – followed by file size
53
2. Write a shell script that accepts name from the user and creates a directory by that name,
then creates a text file in that directory and stores in it, the data accepted from user(till ^z), and
displays the number of characters stored in the file. The program stops if directory name given is
null.
54
Exercise 8 Start Date / /
HTML
You will need a simple text editor to write html codes. For example you can use notepad in
windows an in Linux operating system. You will need a browser to view the html
code, you can use IE on windows and Mozilla on Linux operating system.
HTML tags are somewhat like commands in programming languages. Tags are not themselves
displayed, but tell the browser how to display the document’s contents.
Every HTML tag is made up of a tag name, sometimes followed by an optional list of attributes, all
of which appears between angle brackets < >. Nothing within the brackets will be displayed in the
browser. The tag name is generally an abbreviation of the tag’s function. Attributes are properties
that extend or refine the tag’s function. The name and attributes within a tag are not case
sensitive. Tag attributes, if any, belong after the tag name, each separated by one or more
spaces. Their order of appearance is not important. Most attributes take values, which follow an
equal sign (=) after the attribute’s
name. Values are limited to 1024 characters in length and may be case sensitive. Sometimes the
value needs to appear in quotation marks (double or single).
Most HTML tags are containers, meaning they have a beginning start tag and an end tag. An end
tag contains the same name as the start tag, but it is preceded by a slash (/). Few tags do not
have end tags.
Some HTML tags required to design simple web pages are given below
55
Tag Description Attributes Example
<!-- ... --> Allows one to insert <!— Starting my first
a line of browser- web page --!>
invisible comments
in the document
<HTML> <HTML> tag tells
</HTML> the browser that <HTML>
this is start of the Hello world!
HTML and </HTML>
</HTML> marks its
end.
56
type to an absolute value on a
scale from 1 to 7 (3 is the
default)
<BIG> </BIG> Sets the type one
font size larger
than the
surrounding text
<SMALL> Sets the type one
</SMALL> font size smaller
than the
surrounding text
<BLINK> Causes the
</BLINK> contained text to
flash on and off.
<SUB> </SUB> Formats enclosed a<SUB> <SMALL> o
text as subscript. </SUB> </SMALL>
<SUP> </SUP> Formats enclosed x<SUP> <SMALL> 2
text as superscript. </SUP> </SMALL>
<MARQUEE> Creates a scrolling- align=top|middle|bottom <MARQUEE align=top
</MARQUEE> text marquee area. Aligns the marquee with the behaviour =slide
top, middle, or bottom of the bgcolor=”#00FF00”
neighbouring text direction=right
line. height=20 hspace =5 >
behaviour=scroll|slide|alternate scrolling all the way
Specifies how the text should from one end to other
behave. Scroll is the default </MARQUEE>
setting and
means the text should start
completely off one side, scroll
all the way across
and completely off, then start
over again. Slide stops the
scroll when the text
touches the other margin.
Alternate means bounce back
and forth within
the marquee.
bgcolor="#rrggbb" or color
name
Sets background color of
marquee.
direction=left|right
Defines the direction in which
the text scrolls.
height=number
Defines the height in pixels of
the marquee area.
hspace=number
Holds n pixels space clear to
the left and right of the
marquee.
<IMG> loads an inline src= “ text” Provides the URL
image of the graphic file to be
displayed
alt="text" Provides alternate
text if the image cannot be
displayed.
height=number
Specifies the height of the
image in pixels.
57
width=number
Specifies the width of the
image in pixels.
An HTML document is divided into two major portions: the head and the body.The head contains
information about the document, such as its title and “meta” information describing the contents.
The body contains the actual contents of the document (the part that is displayed in the browser
window).
Create a background image called myimage.jpg by using any picture creating tool. Type the
above sample html program in the text editor and view it through the browser. Modify it to include
some blinking text.
Set A
1. Create an html page with 7 separate lines in different sizes. State size of each line in its text.
2. Create an html page with 7 separate lines in different colors. State color of each line in its
text.
3. Create an html page with all the different text styles (bold, italic and underlined) and its
combinations on separate lines. State style of each line in its text.
5. Create an html page with red background with a message “warning” in large size blinking.
Add scrolling text “read the message” below it.
58
1. Create an html page with following specifications
a. Title should be about myself
b. Color the background with pink color
c. Place your name at the top of the page in large text and centered
d. Add names of your family members each in a different size, color, style and typeface
e. Add scrolling text with a message of your choice
f . Add your image at the bottom
Lists : Lists are a great way to provide information in a structured and easy to read format.
There are two types of lists :
1] Numbered List (Ordered List)
An ordered list is used when sequence of list items is important.
2] Bulleted List (Unordered List)
An unordered list is a collection of related items that have no special order or sequence.
Tags used to create lists are given in the following table.
59
Tag Description Attributes Example
<LI> Specify the list item.
<OL> The <OL> tag formats Type = a/A/i/I/1 <body bgcolor= "pink">
</OL> the contents of an Sets the numbering style to a,A,i, <font face = "Arial” size=
ordered list with I,1 default 1 "6" color = "green">
numbers. The start = “A” <u>
numbering starts at 1. Specifies the number or letter List of Cities....
It is incremented by with which the list should start. </u>
one for each </font>
successive ordered list <ol type = "A" start = "A">
item tagged with <LI> <li> Mumbai
<li> Pune
<li> Nashik
<li> Nagpur
</ol>
</body>
<UL> <UL> tag defines the Type = disc/square/circle <body bgcolor= "sky blue"
</UL> unordered list of items Specifies the bullet type. text =”yellow”>
<font face = "Arial”
size="6" color= "orange">
<i><u><b>
List of Fruits
</i></u></b>
<ul type = "square">
<li> Apple
<li> Pinapple
<li> Mango
<li> Guava
</ul>
</body>
Tables : A table is a two dimensional matrix, consisting of rows and columns. HTML tables are
intended for displaying data in columns on a web page. Tables contains information such
as text, images, forms, hyperlinks etc.
Tags used to create table are given in the following table.
60
row of the
table for
heading
Tags used to add hyperlinks lists are given in the following table.
61
Frames : Using frames, one can divide the screen into multiple scrolling sections, each of which
can display a different web page into it. It allows multiple HTML documents to be seen
concurrently
1. Create an html program using the body given in the example for ordered list. Modify it to
change the color of the item text to ____ and reduce the size of text one smaller than the heading.
2. Create an html program using the body given in the example for unordered list. Modify it to
change the shape of the bullet to ____and also reduce the size of bulleted items one smaller than
the heading.
3.Type the sample HTML program using tables. Modify it to remove Rs and paise column and
specify price as 500.50
4.Type the sample HTML program using frames. Create the required html files with appropriate
messages. Modify it to change to a different frame structure.
Set A
1. Write the HTML code which generates the following output.
• Coffee
• Tea
Black Tea
62
Green Tea
1] Africa
2] China
• Milk
3. Divide the frame into different sections as shown below and add appropriate html files to
each frame.
Set B
1. Create an html page with appropriate frames containing Heading and other information. Add
a bulleted list of your favourite subjects. For each subject make a nested list that contains,
teacher name, the start and end time. Add your photograph and message in a separate frame
Add link to teacher or college web site wherever teacher name appears.
2. Create an html page with appropriate frames containing Heading and other information. Add
an ordered list of your educational qualifications. For each course make a nested list that
contains, university or board name, the year and the percentage scored. Add link to university site
where university name appears. Add your college photograph and message in a separate frame
63
Exercise 10 Start Date / /
Creation of forms, small case study to create HTML pages using all the above learnt techniques.
Forms : HTML provides better & more extensive support for collecting user inputs through
forms. A form can be placed anywhere inside the body of an HTML document.
You can have more than one form in the document.
Tags used to add input forms are given in the following table.
64
that checkbox or
radio button is
checked
align="(texttop/
absmiddle
/baseline /bottom,)"
<SELECT> Defines and <br>
</SELECT> displays a Age Between :
set of name=" (name to <select name = "age" size = 1>
optional list be passed to the </select>
items from script as part of <br>
which the name/value pair)"
user can rows="no. of rows"
select one cols="(no. of cols.)"
or more
items.
<OPTION> indicates a <select name = "age" size = 1>
possible selected=default <option selected> 21-30
item within a selection <option> 31-40
select value="data <option> 41-50
widget submitted if this <option> 51-60
option is selected" <option> 61-70
</select>
<TEXTAREA> name=name of <br>
</TEXTAREA> data field Objectives
multiline text size=#of items to :
entry widget display. multiple <textarea rows = 10 columns = 15>
allows multiple </textarea>
selections
Type the sample HTML code given above and view the contents through a browser.
Set A
Write the HTML code for generating the form as shown below
1.
65
2.
Vanilla
Pistachio
Choose your favourite ice cream flavour Chocalate
Mango
Santra Mantra
How would you like to have it?
3.
Browse…
What does the file contain?
Image Source code Binary code
Set B
1. Design an html form to take the information of a student registering for the course such as
the name, address , gender , course( to be selected from a list of courses) etc. One should
provide button to Submit as well as Reset the form contents.
2. Design an html form to take the information of a customer visiting a departmental store such
as name, contact phone no , preferred days of purchasing , favourite item ( to be selected from a
list of items), suggestions etc. One should provide button to Submit as well as Reset the form
contents.
3. Design an html form to take the information of a customer booking a travel plan such as
name, address, contact phone no , gender, preffered season , location type( to be selected from
a list) etc. One should provide button to Submit as well as Reset the form contents.
66
4. Design an html form to take the information of a article to be uploaded such as file path,
author name , type (technical, literary, general), subject topic ( to be selected from a list) etc.
One should provide button to Submit as well as Reset the form contents.
67
Lab Course I
Section II
68
Exercise 11 Start Date / /
To create simple tables , with only the primary key constraint ( as a table level constraint & as a
field level constraint) (include all data types)
A table is a database object that holds data. A table must have unique name, via which it can be
referred. A table is made up of columns. Each column in the table must be given a unique name
within that table. Each column will also have size a data-type and an optional constraint.
The data types permitted are
69
is called as column level ,……)
constraint
3. Create table emp (eno integer primary key, ename varchar[50] , salary float);
4. Create table books( id integer UNIQUE, title text NOT NULL, author_id integer,sub_id
integer,CONSTRAINT books_id_pkey PRIMARY KEY(id));
5. Create table sales_order(order_no char[10] PRIMARY KEY, order_date date, salesman_no
integer);
6. Create table client_master(client_no integer CONSTRAINT
p_client PRIMARY KEY, name varchar[50], addr text, bal_due
integer);
7. Create table inventory(inv_no integer PRIMARY KEY,in_stock
Boolean);
70
8. create table sales_order1(order_no char[10], product_no char[10], ,
qty_ordered integer,product_rate numeric(8,2),PRIMARY
KEY(order_no,product_no));
Set A
1.
Create a table with details as given below
Table Name PLAYER
Columns Column Name Column Data Type Constraints
1 player_id Integer Primary key
2 Name varchar (50)
3 Birth_date date
4 Birth_place varchar(100)
Table level constraint
2.
Create a table with details as given below
Table Name Student
Columns Column Name Column Data Type Constraints
1 Roll_no integer
2 Class varchar (20)
3 Weight numeric (6,2)
4 Height numeric (6,2)
Table level constraint Roll_no and class as primary key
3.
Create a table with details as given below
Table Name Project
Columns Column Name Column Data Type Constraints
1 project_id integer Primary key
2 Project_name varchar (20)
3 Project_ text
description
4 Status boolean
Table level constraint
4.
Create a table with details as given below
Table Name Donor
Columns Column Name Column Data Type Constraints
1 Donor_no integer Primary key
2 Donor_name varchar (50)
3 Blood_group Char(6)
4 Last_date date
Table level constraint
Set B
Create table for the information given below by choosing appropriate data types and also
specifying proper primary key constraint on fields which are underlined
1. Property ( property_id, property_desc , area, rate, agri_status )
2. Actor ( actor_id, Actor_name, birth_date )
71
3. Movie(movie-no, name, release-year )
4. Hospital(hno,hname,hcity)
Set C
Create table for the information given below by choosing appropriate data types and also
specifying proper primary key constraint on fields which are underlined
1. Table ___________ ( __________, ____________ , ______, _______,
Primary key : ____________________
72
Exercise 12 Start Date / /
To create more than one table, with referential integrity constraint, PK constraint.
The integrity constraints help us to enforce business rules on data in the database. Once an
integrity constraint is specified for a table or a set of tables, all data in the table always conforms
to the rule specified by the integrity constraint.
The following is the list of constraints that can be defined for enforcing the referential integrity
constraint.
Rules to Handle relationships , attributes , enhanced E-R concepts during table creation :
Name Description Handling Example Create
statement
One-to-one A member from The key Room & guest. Create table
73
an entity set is attribute from Room no is room( rno int
connected to anyone entity foreign key in primary key,
atmost one set goes to the guest desc char(30));
member from other entity set relation.guest Create table
the other entity (may be the has full guest(gno int,
set & vice-versa entity set that participation in name
has full relation. varchar(20), rno
participation in int references
relation) , as a room unique);
foreign key.
One-to-many, A member from The key Department & Create table
many-to-one the entity set on attribute of the employee. Here dept(dno int
the one side is entity set on one department is primary key,
connected to side is put as on the one side dname char(20);
one or more foreign key in & employee is Create table
members from the entity set on on the many emp(eno int
the other entity the many side. side. primary key,
set, but a name char(30),
member from dno int
the entity set on references dept);
the many side ,
is connected to
atmost one
member of the
entity set on one
side.
May-to-many A member from A new relation is Student & Create table
one entity set created that will subject . a student(sno int
connected to contain the key student can opt primary key,
one or more attributes of for many name
members of the both the subjects & a varchar(20);
other entity set participating subject has Create table
& vice-versa entity sets. many students subject(sbno int
opting for it. primary key,
name
varchar(20));
Create table st-
sub(sno int
references
student, sbno int
references
subject,
constraint pkey
primary
key(sno,sbno));
A multivalued an attribute A new relation is An employee Create table
attribute having multiple created , which having multiple emp(eno int
values for each will contain a contact primary key,
member of the place holder for numbers, like name char(30));
entity set the multivalued home phone, Create table
attribute and mobile number, emp-ph(eno int
the key office number references emp,
attributes of the etc. hence the phno int ,
entity set that phone-no constraint pkey
contains the attribute in primary
multivalued employee key(eno,phno));
attribute relation
becomes a
multivalued
attribute.
74
A multivalued, A composite A new relation is An employee Create table
composite attribute having created, which having multiple emp(eno int
attribute multiple values , will contain a addresses , primary key,
for each place holder for where each name char(30));
member of the each part of the address is made Create table
entity set composite up of a block no, emp-add(eno int
attribute and the street no, city, references emp,
key attributes of state. Hence the addno int, hno
the entity set address int, street
that contains the attribute char(20), city
composite becomes a char(20),
multivalued composite constraint pkey
attribute multivalued primary
attribute. key(eno,addno));
Generalization / The members of New relations A person ( Create table
specialization an entity set can for each parent entity person(ssno int
be grouped into subgroup , if the set) can be an primary key,
several subgroups have employee, a name char(30));
subgroups, its own student, a Create table
based on an attributes, other retired person. emp(ssno int
attribute/s than the parent Here employee references
vaue/s. attributes. The has its own set person, eno int,
Each subgroup parent entity of attributes like cname char(20),
becomes an set’s key is company, salary sal float, primary
entity set. added to each etc. a student key(ssno));
Depicts a subgroup. has its won set Create table
parent-child type If no specific of attributes like student(ssno int
of relationship. attributes for college/ school, references
each subgroup, course etc. a person, class
then only the retired person char(10), school
parent relation is has its own set varchar(50),
created. of attributes like primary
hobby, pension key(ssno));
etc. so we
create a person
relation , a
student relation,
an employee, a
retire person.
The student ,
employee,
retired person
entity sets will
have the key of
the person entity
set added to it.
You can type the following Create table Statements to create the tables satisfying referential
integrity constraints. On table creation type \d <table name> and write the output.
1. Consider two tables department & employee. One department can have one or more
employees, but an employee belongs to exactly one department ( 1-m relation). It’s pictorially
shown as follows :
75
To handle the above relation, while creating the tables, ‘deptno’ is a foreign key in the employee
table. The statement for creating the tables are as follows :
2. Consider the department table created above & another table called project. A project is
controlled by exactly one department , but a department can control one or more projects( a m-1
relation). It’s pictorially shown as follows :
Control
project by department
tt
To handle the above relationship, control-dno is a foreign key in project. The statement for
creating the project table is as follows :
Create table project(pno int primary key, pname char(10), control-dno int,
foreign key(control-dno) references department(dno))
3. Consider the project & employee relations created above. An employee can work in one or
more projects, and a project can have one or more employees working in it .( a m-m relation). It’s
shown pictorially as follows :
hrs
To handle the above relationship, we create a new table , works-on , as given below :
create table works(eno int references employee, pno int references project, hrs int, constraint
pkey primary key(eno,pno))
4. Consider the relations guest and room. A guest is allocated exactly one room, and a room
can contain exactly one guest in it. ( a 1-1 relation). It’s pictorially shown as follows :
To handle the above relation, we add room-no as foreign key to guest, since a guest cannot be
without being allocated to a room ( guest has full participation in relation). The statements for
creating these relations are as follows
Create table room(room-no integer primary key , description char(20, charge integer);
Create table guest(guest-no integer primary key, name varchar(30), room-no references room
unique);
76
Set A
Create tables for the information given below by giving appropriate integrity constraints as
specified.
1. Create the following tables :
Table Name Property
Columns Column Name Column Data Type Constraints
1 Pnumber Integer Primary key
2 description varchar (50) Not null
3 Area Char(10)
Relationship A one-many relationship between owner & property. Define reference keys
accordingly .
77
Set B
Create table for the information given below by choosing appropriate data types and integrity
constraints as specified.
1. Table _____________(______, __________, ________, ___________
_____________(______, __________, ________, ___________
Constraints: ____________, _____________________
Relationship _____________________________________________________
78
Exercise 13 Start Date / /
To create one or more tables with Check constraint , Unique constraint, Not null constraint
, in addition to the first two constraints (PK & FK)
1. create client master by using any one DDL statement given above. On table creation type \d
<table name> and write the output
79
Set A
1.
Create a table with details as given below
Table Name Machine
Columns Column Name Column Data Type Constraints
1 Machine_id integer Primary key
2 Machine_name varchar (50) NOT NULL, uppercase
3 Machine_type varchar(10) Type in ( ‘drilling’, ‘milling’,
‘lathe’, ‘turning’, ‘grinding’)
4 Machine_price float Greater than zero
5 Machine_cost float
Table level constraint Machine_cost less than Machine_price
2.
Create a table with details as given below
Table Name Employee
Columns Column Name Column Data Type Constraints
1 Employee_id integer Primary key
2 Employee_name varchar (50) NOT NULL, uppercase
3 Employee_desg varchar(10) Designation in ( ‘Manager’,
‘staff’, ‘worker’)
4 Employee_sal float Greater than zero
5 Employee_uid text Unique
Table level constraint Employee_uid not equal to Employee_id
Set B
1.
Create a table with details as given below
Table Name
Columns Column Name Column Data Type Constraints
1
2
3
4
5
Table level constraint
80
Exercise 14 Start Date / /
To drop a table from the database, to alter the schema of a table in the
Database.
Create the table given below . Assume appropriate data types for attributes.
Modify the table, as per the alter statements given below, type \d <table name>
and write the output.
Supplier_master( supplier_no, supplier_name,city,phone-no,amount)
81
4.alter table supplier_master modify (supplier_name varchar(50));
5. alter table supplier_master drop constraint city-check;
6. drop table supplier_master;
Set A
1. Remove employee table from your database. Create table employee( eno, ename, sal). Add
designation column in the employee table with values restricted to a set of values.
2. Remove student table from your database. Create table student( student_no, sname,
date_of_birth). Add new column into student relation named address as a text data type with NOT
NULL integrity constraint and a column phone of data type integer.
3. Consider the project relation created in the assignment 12. Add a constraint that the project
name should always start with the letter ‘R’
4.Consider the relation hospital created in assignment 12. Add a column hbudget of type int ,
with the constraint that budget of any hospital should always > 50000.
Set B
1. Remove ____________ table from your database. Create table _____( __________,
______, _________). Add ___________ _________________________ ____________
_____________________
82
Exercise 15 Start Date / /
83
Update The UPDATE UPDATE Update emp set sal = sal
command is used to tablename +0.5*sal;
change or modify
data values in a SET Update emp set sal = sal+1000
table. columnname = where eno =1;
To specify update of value where
several columns at condition;
the same time, we
simply specify them
as a comma-
separated list
Consider the tables created in assignments 11,12,13,14. type and execute the below statements
for these tables. Write the output of each statement & justify your answer
1. INSERT INTO sales_order(s_order_no,s_order_date,client_no)
VALUES (‘A2100’, now() ,’C40014’);
2. INSERT INTO client_master values(‘A2100’,’NAVEEN’,’Natraj apt’,’pune_nagar
road’,’pune’,40014);
3. insert into client_master values (‘A2100’,’NAVEEN’,NULL,’pune_nagar road’,’pune’,40014);
4. UPDATE emp SET netsal= net_sal_basic_sal*0.15;
5. UPDATE student
SET name=’SONALI’,address=’Jayraj apartment’
WHERE stud_id=104 ;
6. DELETE from emp;
7.DELETE from emp
WHERE net_sal <1000;
Set A
1. Create the following tables ( primary keys are underlined.).
Property(pno,description, area)
Owner(oname,address,phone)
An owner can have one or more properties, but a property belongs to exactly one owner . Create
the relations accordingly ,so that the relationship is handled properly and the relations are in
normalized form (3NF).
a) Insert two records into owner table.
b) insert 2 property records for each owner .
c) Update phone no of “Mr. Nene” to 9890278008
d) Delete all properties from “pune” owned by “ Mr. Joshi”
84
Create the Relations accordingly, so that the relationship is handled properly and the relations are
in normalized form (3NF).
a) Insert 5 records into department table
b) Insert 2 employee records for each department.
c) increase salary of “managers” by 15%;
d) delete all employees of deparment 30;
e) delete all employees who are working as a “clerk”
f) change location of department 20 to ‘KOLKATA’
Set B
1. Design a set of tables with the following constraints. Add any new attributes , as required by
the queries.
Table name :
Field name Data Type Constraints
Table name :
Field name Data Type Constraints
Relationship ___________________________________________
Write & execute insert/ update / delete statements for following business tasks
a)
b)
c)
d)
e)
f)
85
Set C
Create an appropriate set of tables in normalized form to keep some business information.
Populate the tables with information for the business process. State the updations that can be
done to the data in the table .Write and execute update / delete statements for the same. The
names of tables & fields should be self-explanatory ( i.e . their names should depict the kind of
data being stored. )
86
Exercise 16 Start Date / /
87
query to appear in a
sorted order.
Group by clause
used to form groups of
tuples , of the result . It
is used when using
aggregate functions.
Having clause
Used with group by
clause, to force a
condition on the groups
formed after applying
group by clause, &
selects only those groups
in the output that satisfy
the condition.
88
As part of the self activity in exercise you have created a table employee with attributes empno,
name, address, salary and deptno. You have also inserted atleast 10 records into the same.
To execute each query
type each query into the database prompt or
type queries in a file and cut and copy each query at the database prompt or
type queries in a file and type \i filename at SQL prompt. ( all queries in the file will get
executed one by one).
Execute following select queries & write the business task performed by each query.
1. Select * from emp;
2. Select empno, name from emp;
3. Select distinct deptno from emp;
4. Select * from emp where deptno = ___;
5. Select * from emp where address = ‘pune’ and sal > _____;
6. Select * from emp where address = ‘pune and salary between _____ and _____;
7. Select * from emp where name like ‘---%’
8. Select * from emp where name like ‘%and%’
9. Select * from emp where salary is null;
10. Select * from emp order by eno;
11. Select * from emp order by deptno, eno desc;
12. Select deptno as department, sum(salary) as total from emp group by deptno order by
deptno;
13. Select deptno as department , count(eno) as total_emp from emp group by deptno having
count(eno ) > _____ order by deptno;
14. select avg(salary) from emp;
15. select max(salary),deptno from emp group by deptno having max(sal) > __________;
16. select deptno, min(salary) from emp order by deptno;
17. update emp set salary = salary + 0.5*salary where deptno = (select deptno from department
where dname = ‘finance’);
18. update emp set deptno = (select deptno from department where dname = ‘finance’)
Where deptno = (select deptno from department where dname = ‘inventory’);
19. insert into emp_backup(eno,ename) values(select eno,ename from emp);
20. delete from emp where deptno = (select deptno from department where
dname=’production’);
Set A
Consider the relations Person (pnumber, pname, birthdate, income), Area( aname,area_type).
An area can have one or more person living in it , but a person belongs to exactly one area. The
attribute ‘area_type’ can have values as either urban or rural.
Create the Relations accordingly, so that the relationship is handled properly and the relations are
in normalized form (3NF).
Assume appropriate data types for all the attributes. Add any new attributes as required,
depending on the queries. Insert sufficient number of records in the relations / tables with
appropriate values as suggested by some of the queries.
Write select queries for following business tasks and execute them.
89
7. List the names of people with average income
8. List the sum of incomes of people living in ‘____’
9. List the names of the areas having people with maximum income (duplicate areas must be
omitted in the result)
10. Give the count of people in each area
11. List the details of people living in ‘____’ and having income greater than _____;
12. List the details pf people, sorted by person number
13. List the details of people, sorted by area, person name
14. List the minimum income of people.
15. Transfer all people living in ‘pune’ to ‘mumbai’.
16. delete information of all people staying in ‘urban’ area
Set B
1. Design a table with the following constraints. Add any new attributes , as required by the
queries.
Table name :
Field name Data Type Constraints
Insert sufficient number of records in the relations / tables with appropriate values as
suggested by some of the queries.
Write & execute select queries for following business tasks
a)
b)
c)
d)
e)
Set C
Create an appropriate table to keep some business information. Populate the table with
information for the business process. State the business tasks that you need to perform to extract
information. Write and execute queries for the same. The names of tables & fields should be self-
explanatory ( i.e. their names should depict the kind of data being stored. )
90
Exercise 17 Start Date / /
To understand & get a Hands-on on using set operations (union ,intersect and except) with select
statement.
The relations participating in the SQL operations union, intersect & except must be compatible i.e.
the following two conditions must hold :
a)The relation r and s must be of the same arity. That is , they must have the same number of
attributes.
91
th th
b) The domains of the i attribute of r and the i attribute of s must be the same , for all i.
Non-teaching ( empno int primary key, name varchar(20), address varchar(20), salary int,dno
references department)
Teaching(empno int primary key, name varchar(20), address varchar(20), salary int,dno
references department)
Department(dno int primary key,dname)
• insert at least 10 records into both the relations.
• type the following select queries & write the output and the business task performed by
each query
1. Select empno from non-teaching union select empno from teaching;
2. Select empno from non-teaching union all select empno from teaching;
3. Select name from non-teaching intersect select name from teaching;
4. Select name from non-teaching intersect all select name from teaching;
5. Select name from non-teaching except select name from teaching;
6. Select name from non-teaching except all select name from teaching;
Set A
Create the following relations, for an investment firm
emp( emp-id ,emp-name, address, bdate)
Investor( inv-name , inv-no, inv-date, inv-amt)
An employee may invest in one or more investments, hence he can be an investor.
But an investor need not be an employee of the firm.
Create the Relations accordingly, so that the relationship is handled properly and the relations are
in normalized form (3NF).
Assume appropriate data types for the attributes. Add any new attributes , as required by the
queries. Insert sufficient number of records in the relations / tables with appropriate values as
suggested by some of the queries.
Set B
1. Design following two tables with the following constraints . Add any new attributes, as
required by the queries.
Table name 1:
Field name Data Type Constraints
92
Table name 2:
Field name Data Type Constraints
Relationship ______________________________________________
Insert sufficient number of records in the relations / tables with appropriate values as
suggested by some of the queries.
Write & execute queries for following business tasks
a)
b)
c)
d)
e)
f)
Set C
Create two compatible tables having similar set of attributes, to keep some business information.
Populate the tables with information for the business process. State the business tasks that you
need to perform on these tables involving information from both the tables. Write and execute
queries for the same. The names of tables & fields should be self-explanatory ( i.e. their names
should depict the kind of data being stored. )
93
Exercise 18 Start Date / /
To understand & get a Hands-on on nested queries & subqueries, that involves joining of tables.
Set comparison the < some, > some, <= some, >= some, = some, <> some are the
constructs allowed for comparison. = some is same as the ‘in’
connectivity. <> some is not the same as the ‘not in’ connectivity.
Similarly sql also provides < all, >all, <=all, >= all, <> all
comparisons. <>all is same as the ‘not in’ construct.
Set cardinality The ‘exists’ construct returns the value true if the argument
subquery is nonempty. We can test for the non-existence of tuples
in a subquery by using the ‘not exists’ construct. The ‘not exists ‘
construct can also be used to simulate the set containment
operation (the super set ). We can write “relation A contains relation
B” as “not exists (B except A)”.
The complete Syntax of select statement containing connectivity or Comparison operators is as
follows
select <attribute-list> from <relation-list>
where <connectivity / comparison > { sub-query };
94
5. select ename from works w where salary > some (select salary from works where company-
name not in (select company-name from company where city = “____”));
6. select ename from employee e where city = ( select city from employee e1 , manages m
where m.ename = e.ename and m.manager-name = e1.ename);
7. select * from employee where ename in (select manager-name from manages )
8. select city count(*) from employee group by city having count(*) >= all (select count(*) from
employee group by city)
9. select ename from works w where salary <> all (select salary from works where ename <>
w.ename);
10. select company-name, sum(salary) from works w group by company-name having sum(sal)
>= all ( select sum(sal) from works group by company-name)
11. select ename from employee e where city in(‘_____’,’______’);
12. select ename from employee e where city = (select city from company c, works w where
w.ename = e.name and c.company-name = w.company-name);
Set A
Create the following relations :
Emp(eno,name,dno,salary)
Project(pno,pname,control-dno,budget)
Each employee can work on one or more projects, and a project can have many employees
working in it. The number of hours worked on each project , by an employee also needs to be
stored.
Create the Relations accordingly, so that the relationship is handled properly and the relations are
in normalized form (3NF).
Assume appropriate data types for the attributes. Add any new attributes , new relations as
required by the queries.
Insert sufficient number of records in the relations / tables with appropriate values as suggested
by some of the queries.
Write the queries for following business tasks & execute them.
1. list the names of departments that controls projects whose budget is greater than ___.
2. list the names of projects, controlled by department No __, whose budget is greater than
atleast one project controlled by department No __.
3. list the details of the projects with second maximum budget
4. list the details of the projects with third maximum budget.
5. list the names of employees, working on some projects that employee number __ is working.
6. list the names of employees who do not work on any project that employee number __ works
on
7. list the names of employees who do not work on any project controlled by ‘______’
department
8. list the names of projects along with the controlling department name, for those projects
which has atleast __ employees working on it.
9. list the names of employees who is worked for more than 10 hrs on atleast one project
controlled by ‘______’ dept.
10. list the names of employees , who are males , and earning the maximum salary in their
department.
11. list the names of employees who work in the same department as ‘_____’.
12. list the names of employees who do not live in _____ or _______.
Instructor should fill in the blanks with appropriate values.
95
Set B
1. Design a set of tables with the following constraints. Add any new attributes , as required by
the queries.
Table name :
Field name Data Type Constraints
Table name :
Field name Data Type Constraints
Table name :
Field name Data Type Constraints
Relationship _______________________________________________
Insert sufficient number of records in the relations / tables with appropriate values as
suggested by some of the queries.
Write & execute queries for following business tasks. ( business tasks should be using
set operations & should be similar to the ones given in set A )
a)
b)
c)
d)
Set C
Create an appropriate set of tables to keep some business information. Populate the tables with
information for the business process. State the business tasks that involve set of operations that
you need to perform to extract information. Write and execute queries for the same. The names of
tables & fields should be self-explanatory ( i.e. their names should depict the kind of data being
stored. )
96
Exercise 19 Start Date / /
To understand & get a Hands-on on nested queries & subqueries, that involves joining of tables,
to demonstrate set cardinality.
SQL includes a feature for testing whether a subquery has any tuples in its result, using the
following clauses :.
Name Description Syntax Example
Exists The ‘exists’ construct select <attribute- Select cname from
returns the value true if list> from <relation- borrower b where
the argument subquery list> exists( select * from
is nonempty where depositor where
<exists> { sub- dname = b.cname);
query} ;
Not exists We can test for the select <attribute- Select cname from
non-existence of tuples list> from <relation- borrower b where not
in a subquery by using list> exists( select * from
the ‘not exists’ where <not exists> depositor where
construct. { sub-query}; dname = b.cname);
The ‘not exists ‘
construct can also be
used to simulate the
set containment
operation (the super
set ).
We can write “relation
A contains relation B”
as “not exists (B except
A)”
Consider the table you have prepared as part of self activity of exercise 18, Type the following
queries , execute them and give the business task performed by each query
1. Select company-name from company c where not exists (select city from company where
company-name = “_______” except (select city from company where company-name =
c.company-name));
2. Select ename from employee e where exists (select manager-name from manages where
manager-name = e.ename group by manager-name having count(*) >3);
3. Select company-name from company c where not exists (select city from company where
company-name = c.company-name except (select city from company where company-name =
“__________”));
4. Select ename from employee e where exists (select city from employee where city = e.city
and ename <> e.ename group by city having count(*) > 5)
97
5. Select company-name from company c where not exists (select company-name from
company where city = c.city and company-name <> c.company-name)
Set A
Consider the table you have prepared as part of Assessment work set A of exercise 18, Type the
following queries, execute them and give the business task performed by each query
1. List the names of employees who work in all the projects that “____________” works on.
2. List the names of employees who work on only some projects that “______” works on
3. List the names of the departments that have atleast one project under them .( write using
‘exists ‘ clause)
4. List the names of employees who do not work on “sales” project (write using ‘not exists’)
clause
5. List the names of employees who work only on those projects that are controlled by their
department .
6. List the names of employees who do not work on any projects that are controlled by their
department
Set B
1. Design tables with the following constraints. Add any new attributes , as required by the
queries.
Table name :
Field name Data Type Constraints
Table name :
Field name Data Type Constraints
Relationship _____________________________________________
Insert sufficient number of records in the relations / tables with appropriate values as
suggested by some of the queries.
Write & execute queries for following business tasks. ( business tasks should be using
set cardinality operations & should be similar to the ones given in set A )
a)
b)
98
c)
d)
e)
f)
Set C
Create an appropriate set of tables to keep some business information. Populate the tables with
information for the business process. State the business tasks that involve set cardinality
operations that you need to perform to extract information. Write and execute queries for the
same. The names of tables & fields should be self-explanatory ( i.e. their names should depict the
kind of data being stored. )
99
Exercise 20 Start Date / /
Assignment related to small case studies ( Each case study will involve creating tables with
specified constraints, inserting records to it & writing queries for extracting records from these
tables)
The following constraints are to be defined for the vehicles, drivers, destination places :
a) the vehicle make should be after the year 2000.
b) only vehicles of maruti, Tata are used by the company
c) drivers should be above 20 years of age
d) drivers should be staying in “pune” city
e) the destination places should be within 500km radius from Pune.
Design the relational database for the above company , so that the following queries can be
answered :
1. List the names of drivers who have driven a car to “Mumbai”
2. List the name of customers who have booked a “SUV” to “satara”
3. List the names of customers who have booked cars to pune or Mumbai or Lonavla
4. List the details of cars that have never driven down to “Mumbai”
5. List the details of the place to which maximum number of customers have driven down.
6. List the details of the driver who have driven all the vehicles of the company.
100
7. List the names of the drivers who have driven atleast two cars to “Mumbai
8. List the names of drivers who have also driven some vehicles to “Mumbai”
9. List the details of customers who have booked more than two vehicles to “solapur”
10. List the names of customers who have booked maximum number of vehicles
Design the relational database for the above , so that the following queries can be answered:
1. List the names of agents living in ‘_________’
2. List the names of policy holders , who have bought policies from the agent ‘joshi’
3. List the names of policyholders, who have bought more than two policies from ‘joshi’
4. List the names of agents , who have sold policies to only customers who live in their own
City.
5. List the names of agents who have sold atleast two policies.
6. List the names of cities, which has the maximum number of agents.
7. List the names of customers who have bought the maximum number of policies.
8. List the details of all premiums , paid f
or the policy number _______________
9. Update all policy amount to _____ , for all policies bought by customers from _____ city.
10. Delete all policies , bought from ‘joshi’
11. _______________________________________________
12. _________________________________________________
13.___________________________________________________
14.___________________________________________________
15.___________________________________________________
Design the relational database for the above , so that the following queries can be answered:
1. List the names of movies in which _________ has acted.
2. List the names of actors who have acted in at least one movie, in which shahrukh has acted.
3. List the names of actors who have acted in every movie in which _________ has acted.
101
4. List the names of actors who have acted as a ‘villan’ in every movie, in which the actor has
acted
5. List the names of movies with the highest budget
6. List the names of movies with the second highest budget
7. List the names of actors who have acted in the maximum number of movies.
8._____________________________________________________________
9. ______________________________________________________________
10._______________________________________________________________
11. Update the address of producer ______ . set the city to _________
12. Delete information of all actors who have an address in pune.
13. _________________________________________
14.__________________________________________
15 List the names of movies , produced by more than one producer.
Design the relational database for the above , so that the following queries can be answered:
1. ____________________________________
2. List the names of musicians who have played guitar for the album ________
3. list the names of musicians who palsy at least one instrument same as the one “joshi” plays.
4. List the names of albums , in which “_________” has sung.
5._________________________________________________
6._________________________________________________
7. List the names of albums released in 1998
8. List the names of albums that have more than two instruments being played in it
9. Delete all information of singers who have not sung in any album
10. Delete all information of musicians , who have worked in the album “_________”
102
Every month the society would like to print a report of expenditure versus collection.
Design the relational database for the above , so that the following queries can be answered:
1. List the flats of 2bhk type.
2. List the 3bhk flats that are currently vacant.
3. List the functions held in clubhouse during the month of “_________”
4. List the names of owners , who have never conducted any functions in the clubhouse.
5. List the payment defaulters for the month of “april”
6. List the total expenditure for the month of _____________
7. List the month with the least expenditure.
8. Transfer the flat in the name of ___________ to ____________
9. __________________________________________________
10.List the names of owners , who own both a 2bhk and a _________
11. ________________________________________________________
12._________________________________________________________
NB : More small case studies can be designed by the instructors , so that there can be
maximum variation in work assigned to each student in a batch.
The case studies must cover almost all types of entities, attributes & relationships.
The queries on the case studies , must be similar to the ones done in assignments 15 to 19.
103
Lab Course I
104
Exercise 1 Start Date / /
2. Expression Examples
Expression C expression
Increment by a 3 a=a+3
Decrement b by 1 b = b-1 or b--
2
2 a + 5 b/2 2*a*a + 5*b/2
7/13(x-5) (float)7/13*(x-5)
5% of 56 (float)5/100*56
n is between 12 to 70 n>=12 && n<=70
πr h
2
Pi*r*r*h
n is not divisible by 7 n % 7 != 0
n is even n%2== 0
ch is an alphabet ch>=’A’ && ch<=’Z’ || ch>=’a’ && ch<=’z’
Note: The operators in the above expressions will be executed according to precedence and
associativity rules of operators.
3. Sample program- to calculate and print simple interest after accepting principal sum, number of
years and rate of interest.
105
Program development steps
1. Type the sample program given above. Execute it for the different values as given below and
fill the last column from the output given by the program.
Follow the following guidelines
a. At $ prompt type vi followed by filename. The filename should have .c as extension for
example
$vi pnr.c
b. Type the sample program given above using vi commands and save it
Compile the program using cc compiler available in Linux
$cc pnr.c
It will give errors if any or it will give back the $ prompt if there are no errors
A executable file a.out is created by the compiler in current directory. The program can be
executed by typing name of the file as follows giving the path.
$ ./a.out
Alternatively the executable file can be given name by using –o option while compiling as
follows
$cc pnr.c –o pnrexec
$./pnrexec
The executable file by specified name will be created. Note that you have to specify the path
of pnrexec as ./pnrexec , i. e., pnrexec in current (. Stands for current directory) directory
otherwise it looks for program by that name in the path specified for executable programs
106
2. If you have not typed the program correctly,i.e., if there are syntactical errors in the program,
compiler will pinpoint the errors committed and are called compile-time errors. C compiler
gives line no along with error messages when it detects grammatical or syntactical errors in
the program. These messages are not so straightforward and you may find it difficult to
identify the error. You may miss a semicolon at the end of a statement and the compiler
points out error in the next statement. You may miss just a closing ‘*/’ of a comment and it will
show errors in several statements following it.
Another type of error which is quite common is the run-time or execution error. You are able
to compile the program successfully but you get run-time messages or garbage output when
you execute the program.
Modify the above program to introduce the following changes, compile, write the error
messages along with line numbers ,remove the error execute and indicate the type of error
whether it was compile-time or execution time error.
int noofYears;
scanf(“%f”,&amount)
scanf(“%f”, amount);
scanf(“%d”, noOfYears);
Set A . Apply all the three program development steps for the following examples.
1. Accept dimensions of a cylinder and print the surface area and volume (Hint: surface area =
2πr + 2πrh, volume = πr h)
2 2
2. Accept temperatures in Fahrenheit (F) and print it in Celsius(C) and Kelvin (K) (Hint: C=5/9(F-
32), K = C + 273.15)
3. Accept initial velocity (u), acceleration (a) and time (t). Print the final velocity (v) and the
2
distance (s) travelled. (Hint: v = u + at, s = u + at )
4. Accept inner and outer radius of a ring and print the perimeter and area of the ring (Hint:
perimeter = 2 π (a+b) , area = π (a -b ) )
2 2
5. Accept two numbers and print arithmetic and harmonic mean of the two numbers (Hint: AM=
(a+b)/2 , HM = ab/(a+b) )
6. Accept three dimensions length (l), breadth(b) and height(h) of a cuboid and print surface
area and volume (Hint : surface area=2(lb+lh+bh ), volume = lbh )
7. Accept a character from the keyboard and display its previous and next character in order.
Ex. If the character entered is ‘d’, display “The previous character is c”, “The next character is e”.
8. Accept a character from the user and display its ASCII value.
Set B . Apply all the three program development steps for the following examples.
107
1. Accept the x and y coordinates of two points and compute the distance between the two
points.
2. Accept two integers from the user and interchange them. Display the interchanged numbers.
3. A cashier has currency notes of denomination 1, 5 and 10. Accept the amount to be
withdrawn from the user and print the total number of currency notes of each denomination the
cashier will have to give.
108
Exercise 2 Start Date / /
During problem solving, we come across situations when we have to choose one of the
alternative paths depending upon the result of some condition. Condition is an expression
evaluating to true or false. This is known as the Branching or decision-making statement. Several
forms of If and else constructs are used in C to support decision-making.
1) if statements
2) if – else
3) Nested if
Note: If there are more than one statement in the if or else part, they have to be enclosed in { }
braces
statement
New statement
2. if - else
statement if( n % 2 == 0)
printf(“Even”);
if (condition) True If False else
{ condition ? printf(“Odd”);
statement;
}
statement statement
else
{
statement;
}
New statement
109
3. Nested if
If ( a >= b)
if (condition) { if ( a >= c)
{ False True printf(“ %d is
if (condition) a>=b maximum”,a);
{ statement;} else
else b>= c True
printf(“ %d is
{ statement;} True a>=c maximum”,c);
False False
}
} c is b is c is a is else
max max max max
else {
{ if ( b >= c)
if (condition) printf(“ %d is
{ statement; } maximum”,b);
else else
{ statement; } printf(“ %d is
maximum”,c);
} }
Step 1: Writing the Step 2 : Draw the flowchart Step 3 : Writing Program
Algorithm
start
/* Program to check range */
1. Start
2. Accept the number #include <stdio.h>
3. Check if number is main( )
within range Read { /* variable declarations */
4. if true number int n;
print “Number is int llimit=50, ulimit = 100;
within range “ /* prompting and accepting input */
False
otherwise printf(“Enter the number”);
print “number is out If(n in range) scanf(“%d”,&n);
of range”. if(n>=llimit && n <= ulimit)
5. Stop True printf(“Number is within range”);
else
printf(“Number is out of range”);
Number is
within range
}
Number is out
of range
stop
110
1. Execute the following program for five different values and fill in the adjoining table
main() n output
{
int n;
printf(“Enter no.”);
scanf(“%d”,&n);
if(n%___==0)
printf(“divisible);
else
printf(“not divisible”);
}
2. Type the above sample program 4 and execute it for the following values.
n Output message
50
100
65
____
____
3. Using the sample code 3 above write the complete program to find the maximum of three
numbers and execute it for different set of values.
Set A: Apply all the three program development steps for the following examples.
1. Write a program to accept an integer and check if it is even or odd.
2. Write a program to accept three numbers and check whether the first is between the other
two numbers. Ex: Input 20 10 30. Output: 20 is between 10 and 30
3. Accept a character as input and check whether the character is a digit. (Check if it is in the
range ‘0’ to ‘9’ both inclusive)
4. Write a program to accept a number and check if it is divisible by 5 and 7.
5. Write a program, which accepts annual basic salary of an employee and calculates and
displays the Income tax as per the following rules.
Basic: < 1,50,000 Tax = 0
1,50,000 to 3,00,000 Tax = 20%
> 3,00,000 Tax = 30%
6. Accept a lowercase character from the user and check whether the character is a vowel or
consonant. (Hint: a,e,i,o,u are vowels)
111
Set B: Apply all the three program development steps for the following examples.
1. Write a program to check whether given character is a digit or a character in lowercase or
uppercase alphabet. (Hint ASCII value of digit is between 48 to 58 and Lowercase characters
have ASCII values in the range of 97 to122, uppercase is between 65 and 90)
2. Accept the time as hour, minute and seconds and check whether the time is valid. (Hint:
0<=hour<24, 0<=minute <60, 0<=second <60)
3. Accept any year as input through the keyboard. Write a program to check whether the year is
a leap year or not. (Hint leap year is divisible by 4 and not by 100 or divisible by 400)
4. Accept three sides of triangle as input, and print whether the triangle is valid or not. (Hint:
The triangle is valid if the sum of each of the two sides is greater than the third side).
5. Accept the x and y coordinate of a point and find the quadrant in which the point lies.
6. Write a program to calculate the roots of a quadratic equation. Consider all possible cases.
7. Accept the cost price and selling price from the keyboard. Find out if the seller has made a
profit or loss and display how much profit or loss has been made.
1. Write a program to accept marks for three subjects and find the total marks secured ,
average and also display the class obtained. (Class I – above __%, class II – ___% to ___%,
pass class – ___% to ___% and fail otherwise)
2. Write a program to accept quantity and rate for three items, compute the total sales amount,
Also compute and print the discount as follows: (amount > ____– 20% discount, amount between
___ to _____ -- 15% discount, amount between – ____ to ____ -- 8 % discount)
3. A library charges a fine for every book returned late. Accept the number of days the member
is late, compute and print the fine as follows:(less than five days Rs ___ fine, for 6 to 10 days Rs.
____ fine and above 10 days Rs. ___ fine )
112
Exercise 3 Start Date / /
The control statement that allows us to make a decision from the number of choices is called a
switch-case statement. It is a multi-way decision making statement.
False
Default Block
stop
113
2. The switch statement is used in writing menu driven programs where a menu displays several
options and the user gives the choice by typing a character or number. A Sample program to
display the selected option from a menu is given below.
1. Write the program that accepts a char–type variable called color and displays appropriate
message using the sample code 1 above. Execute the program for various character values and
fill in the following table. Modify the program to include all rainbow colours
114
Set A: Apply all the three program development steps for the following examples.
1. Accept a single digit from the user and display it in words. For example, if digit entered is 9,
display Nine.
2. Write a program, which accepts two integers and an operator as a character (+ - * /),
performs the corresponding operation and displays the result.
3. Accept two numbers in variables x and y from the user and perform the following operations
Options Actions
1. Equality Check if x is equal to y
2. Less Than Check if x is less than y
3. Quotient and Remainder Divide x by y and display the quotient and remainder
4. Range Accept a number and check if it lies between x and y
(both inclusive)
5. Swap Interchange x and y
Set B: Apply all the three program development steps for the following examples.
1. Accept radius from the user and write a program having menu with the following options and
corresponding actions
Options Actions
1. Area of Circle Compute area of circle and print
2. Circumference of Circle Compute Circumference of circle and print
3. Volume of Sphere Compute Volume of Sphere and print
2. Write a program having a menu with the following options and corresponding actions
Options Actions
1. Area of square Accept length ,Compute area of square and print
2. Area of Rectangle Accept length and breadth, Compute area of rectangle
and print
3. Area of triangle Accept base and height , Compute area of triangle and
print
115
Set C: Write a program to solve the following problems
1. Accept the three positive integers for date from the user (day, month and year) and check
whether the date is valid or invalid. Run your program for the following dates and fill the table.
(Hint: For valid date 1<=month<=12,1<= day <=no-of-days where no-of-days is 30 in case of
months 4, 6,9 and 11. 31 in case of months 1,3,5,7,8,10 and 12. In case of month 2 no-of-days is
28 or 29 depending on year is leap or not)
Date Output
12-10-1984
32-10-1920
10-13-1984
29-2-1984
29-2-2003
29-2-1900
__________
2. Write a program having menu that has three options - add, subtract or multiply two fractions.
The two fractions and the options are taken as input and the result is displayed as output. Each
fraction is read as two integers, numerator and denominator.
116
Exercise 4 Start Date / /
We need to perform certain actions repeatedly for a fixed number of times or till some condition
holds true. These repetitive operations are done using loop control statements. The types of loop
structures supported in C are
1. while statement
2. do-while statement
3. for statement
117
3. for statement /* display first 10 multiples
of 2 */
for(expr1; expr2; expr3) expr1 for( i=1; i <= 10; i++)
{ {
statement 1 printf (“2 X %d = %d\n”, i,
. False 2*i);
. Test }
} expr2
Note: Usually the for loop is used when the statements have to executed for a fixed number of
times. The while loop is used when the statements have to be executed as long as some
condition is true and the do-while loop is used when we want to execute statements atleast once
(example: menu driven programs)
Print value
of sum
stop
118
4. Sample program- To read characters till EOF (Ctrl+Z) and count the total number of characters
entered.
Print count
stop
1. Write a program that accepts a number and prints its first digit. Refer sample code 1 given
above. Execute the program for different values.
2. Write a program that accepts numbers continuously as long as the number is positive and
prints the sum of the numbers read. Refer sample code 2 given above. Execute the program for
different values.
3. Write a program to accept n and display its multiplication table. Refer to sample code 3 given
above.
4. Type the sample program to print sum of first n numbers and execute the program for
different values of n.
5. Write a program to accept characters till the user enters EOF and count number of times ‘a’
is entered. Refer to sample program 5 given above.
119
Set A . Apply all the three program development steps for the following examples.
1. Write a program to accept an integer n and display all even numbers upto n.
2. Accept two integers x and y and calculate the sum of all integers between x and y (both
inclusive)
n
3. Write a program to accept two integers x and n and compute x
4. Write a program to accept an integer and check if it is prime or not.
5. Write a program to accept an integer and count the number of digits in the number.
6. Write a program to accept an integer and reverse the number. Example: Input: 546, Output
645.
7. Write a program to accept a character, an integer n and display the next n characters.
Set B. Apply all the three program development steps for the following examples.
1. Write a program to display the first n Fibonacci numbers. (1 1 2 3 5 ……)
2. Write a program to accept real number x and integer n and calculate the sum of first n terms
of the series x+ 3x+5x+7x+…
3. Write a program to accept real number x and integer n and calculate the sum of first n terms
1 2 3
of the series + 2 + 3 + ……
x x x
4. Write a program to accept characters till the user enters EOF and count number of alphabets
and digits entered. Refer to sample program 5 given above.
5. Write a program, which accepts a number n and displays each digit in words. Example: 6702
Output = Six-Seven-Zero-Two. (Hint: Reverse the number and use a switch statement)
1. Write a program to accept characters from the user till the user enters * and count the
number of characters, words and lines entered by the user. (Hint: Use a flag to count words.
Consider delimiters like \n \t , ; . and space for counting words)
2. Write a program which accepts a number and checks if the number is a palindrome (Hint
number = reverse of number)
Example: number = 3472 Output: It is not a palindrome
number = 262, Output : It is a palindrome
3. A train leaves station A at 4.00 a.m and travels at 80kmph. After every 30 minutes, it reaches
a station where it halts for 10 minutes. It reaches its final destination B at 1.00 p.m. Display a
table showing its arrival and departure time at every intermediate station. Also calculate the total
distance between A and B.
120
4. A task takes 4 ½ hours to complete. Two workers, A and B start working on it and take turns
alternately. A works for 25 minutes at a time and is paid Rs 50, B works for 75 minutes at a time
and is paid Rs. 150. Display the total number of turns taken by A and B, calculate their total
amounts and also the total cost of the task.
121
Exercise 5 Start Date / /
In the previous exercise, you used while, do-while and for loops. You should read following topics
before starting this exercise
1. Different types of loop structures in C.
2. Syntax for these statements.
3. Usage of each loop structure
Nested loop means a loop that is contained within another loop. Nesting can be done upto any
levels. However the inner loop has to be completely enclosed in the outer loop. No overlapping of
loops is allowed.
2. Nested while loop / do while loop /* Program to calculate sum of digits till
sum is a single digit number */
while(condition1)
{ …………………… #include <stdio.h>
while(condition2) void main( )
{ …………………… {
} int n , sum;
……………………. printf(“Give any number ”);
} scanf(“%d”,&n);
do
do {
{ …………………… sum =0;
while(condition1) printf(“%d --->”,n);
{ ……………….. while ( n>0)
} { sum +=n%10;
122
………………. n= n/10;
} while (condition2); }
n=sum;
} while( n >9);
printf ( “ %d” , n);
}
Note: It is possible to nest any loop within another. For example, we can have a for loop inside a
while or do while or a while loop inside a for.
1. The Sample program 1 displays n lines of the following triangle. Type the program and
execute it for different values of n.
1
1 2
1 2 3
1 2 3 4
2. Modify the sample program 1 to display n lines of the Floyd’s triangle as follows (here n=4).
1
2 3
4 5 6
7 8 9 10
3. The sample program 2 computes the sum of digits of a number and the process is repeated
till the number reduces to a single digit number. Type the program and execute it for different
values of n and give the output
123
Signature of the instructor Date / /
1. Write a program to display all Armstrong numbers between 1 and 500. (An Armstrong
number is a number such that the sum of cube of digits = number itself Ex. 153 = 1*1*1 + 5*5*5
+ 3*3*3
2. Accept characters till the user enters EOF and count the number of lines entered. Also
display the length of the longest line. (Hint: A line ends when the character is \n)
3. Display all perfect numbers below 500. [A perfect number is a number, such that the sum of
its factors is equal to the number itself]. Example: 6 (1 + 2 + 3), 28 (1+2+4+7+14)
1. A company has four branches, one in each zone: North, South, East and West. For each of
these branches, it collects sales information once every quarter (four months) and calculates the
average sales for each zone. Write a program that accepts sales details for each quarter in the
four branches and calculate the average sales of each branch.
2 5
2. A polynomial in one variable is of the form a0 + a1x + a2x + …. For example, 6 - 9x + 2x .
Write a program to calculate the value of a polynomial. Accept the number of terms n , the value
of x, and n+1coefficients.
3. The temperature of a city varies according to seasons. There are four seasons – spring,
summer, Monsoon and winter. The temperature ranges are: Spring (15-25 degrees), Summer
(25-40 degrees), Monsoon (20-35 degrees), Winter (5-20 degrees). Accept weekly temperatures
(12 weeks per season) for each season, check if they are in the correct range and calculate the
average temperature for each season.
124
Exercise 6 Start Date / /
ctype.h : contains function prototypes for performing various operations on characters. Some
commonly used functions are listed below.
math.h : This contains function prototypes for performing various mathematical operations on
numeric data. Some commonly used functions are listed below.
Note: If you want to use any of the above functions you must include the library for example
#include <ctype.h>
#include <math.h>
In case of math library , it needs to be linked to your program. You have to compile the program
as follows
$ cc filename -lm
125
A program that does multiple tasks, provides a menu from which user can choose the appropriate
task to be performed. The menu should appear again when the task is completed so that the user
can choose another task. This process continues till the user decides to quit. A menu driven
program can be written using a combination of do-while loop containing a switch statement. One
of the options provided in a menu driven program is to exit the program.
1. Write a menu driven program to perform the following operations on a character type variable.
i. Check if it is an alphabet
ii. Check if it is a digit.
iii. Check if it is lowercase.
iv. Check if it is uppercase.
v. Convert it to uppercase.
vi. Convert it to lowercase.
Refer to the sample code given above and use standard functions from ctype.h
1. Write a program, which accepts a character from the user and checks if it is an alphabet, digit
or punctuation symbol. If it is an alphabet, check if it is uppercase or lowercase and then change
the case.
126
2. Write a menu driven program to perform the following operations till the user selects Exit.
Accept appropriate data for each option. Use standard library functions from math.h
x
i. Sine ii. Cosine iii. log iv. e v. Square Root vi. Exit
3. Accept two complex numbers from the user (real part, imaginary part). Write a menu driven
program to perform the following operations till the user selects Exit.
i. ADD ii. SUBTRACT iii. MULTIPLY iv. EXIT
1. Accept x and y coordinates of two points and write a menu driven program to perform the
following operations till the user selects Exit.
i. Distance between points.
ii. Slope of line between the points.
iii. Check whether they lie in the same quadrant.
iv. EXIT
(Hint: Use formula m = (y2-y1)/(x2-x1) to calculate slope of line.)
2. Write a simple menu driven program for a shop, which sells the following items:
The user selects items using a menu. For every item selected, ask the quantity. If the quantity of
any item is more than 10, give a discount of _____%. When the user selects Exit, display the
total amount.
Item Price
1. Write a program to calculate the total price for a picnic lunch that a user is purchasing for her
group of friends. She is first asked to enter a budget for the lunch. She has the option of buying
apples, cake, and bread. Set the price per kg of apples, price per cake, and price per loaf of bread
in constant variables. Use a menu to ask the user what item and how much of each item she
would like to purchase. Keep calculating the total of the items purchased. After purchase of an
item, display the remaining amount. Exit the menu if the total has exceeded the budget. In
addition, provide an option that allows the user to exit the purchasing loop at any time.
127
Exercise 7 Start Date / /
You have already used standard library functions. C allows to write and use user defined
functions. Every program has a function named main. In main you can call some functions which
in turn can call other functions.
The following table gives the syntax required to write and use functions
Sr. Actions involving Syntax Example
No functions
1. Function declaration returntype function(type arg1, void display();
type arg2 … ); int sum(int x, int y);
1. Sample code
The program given below calculates the area of a circle using a function and uses this function to
calculate the area of a cylinder using another function.
#include <stdio.h>
void main()
{
float areacircle (float r);
float areacylinder(float r, int h);
float area, r;
printf(“\n Enter Radius: “);
scanf(“%f”,&r);
area=areacircle(r);
printf(“\n Area of circle =%6.2f”, area);
128
scanf(“%d”,&h);
area=areacylinder(r,h);
printf(“\n Area of cylinder =%6.2f”, area);
}
2. Sample code
The function iswhitespace returns 1 if its character parameter is a space, tab or newline
character. The program accepts characters till the user enters EOF and counts the number of
white spaces.
#include <stdio.h>
void main()
{
int iswhitespace (char ch);
char ch;
int count=0;
1. Type the program given in sample code 1 above and execute the program. Comment
function declarations and note down the type of error and the error messages received. Add
another function to calculate the volume of sphere and display it.
2. Type the program given in sample code 2 above and execute the program. Comment
function declaration and note down the type of error and the error messages received. Modify the
function such that it returns 1 if the character is a vowel. Also count the total number of vowels
entered.
129
Set A . Write C programs for the following problems
1. Write a function isEven, which accepts an integer as parameter and returns 1 if the number is
even, and 0 otherwise. Use this function in main to accept n numbers and ckeck if they are even
or odd.
2. Write a function, which accepts a character and integer n as parameter and displays the next
n characters.
3. Write a function, which accepts a character and integer n as parameter and displays the next
n characters.
ii. sin(x)
y
Define separate functions to calculate x and n! and use them in each function.
130
Exercise 8 Start Date / /
To demonstrate Recursion.
You should read the following topics before starting this exercise
1. Recursive definition
2. Declaring and defining a function
3. How to call a function
4. How to pass parameters to a function
Recursion is a process by which a function calls itself either directly or indirectly. The points to be
remembered while writing recursive functions
i. Each time the function is called recursively it must be closer to the solution.
ii. There must be some terminating condition, which will stop recursion.
iii. Usually the function contains an if –else branching statement where one branch makes
recursive call while other branch has non-recursive terminating condition
Expressions having recursive definitions can be easily converted into recursive functions
2. The recursive definition long int nCr( int n, int r) #include <stdio.h>
for nCr ( no of { if(n==r || r==0) /* function code*/
combinations of r objects /* terminating condition */ main()
out of n objects) is as return(1); {
follows else int n, r;
nCn = 1 return ( nCr(n-1,r) + printf(“\n enter the total
nC0 = 1 nCr(n, r-1)); number of objects:”);
nCr = n-1Cr + nCr-1 /* recursive call */ scanf(“%d”,&n);
} printf(“\n enter the number
of objects to be selected”);
scanf(“%d”,&r);
printf(“\n The value
%dC%d is %ld”,n, r,
nCr(n,r));
}
131
1. Write the sample program 1 given above and execute the program. Modify the program to
define a global integer variable count and increment it in factorial function. Add a printf statement
in main function for variable count. Execute the program for different values and fill in the
following table.
2. Write the sample program 2 given above and execute the program for different values of n
and r. Modify the program to define a global integer variable count and increment it in nCr
function. Add a print statement in main function for variable count. Execute the program for
different values and fill in the following table
1. Write a recursive C function to calculate the sum of digits of a number. Use this function in
main to accept a number and print sum of its digits.
2. Write a recursive C function to calculate the GCD of two numbers. Use this function in main.
The GCD is calculated as :
gcd(a,b) = a if b = 0
= gcd (b, a mod b) otherwise
3. Write a recursive function for the following recursive definition. Use this function in main to
display the first 10 numbers of the following series
an = 3 if n = 1 or 2
= 2* an-1 + 3*an-2 if n > 2
y
4. Write a recursive C function to calculate x . (Do not use standard library function)
132
Set B . Write C programs for the following problems
1. Write a recursive function to calculate the nth Fibonacci number. Use this function in main to
display the first n Fibonacci numbers. The recursive definition of nth Fibonacci number is as
follows:
fib(n) = 1 if n = 1 or 2
= fib(n-2) + fib(n-1) if n>2
2. Write a recursive function to calculate the sum of digits of a number till you get a single digit
number. Example: 961 -> 16 -> 5. (Note: Do not use a loop)
3. Write a recursive C function to print the digits of a number in reverse order. Use this function
in main to accept a number and print the digits in reverse order separated by tab.
Example 3456
6 5 4 3
(Hint: Recursiveprint(n) = print n if n is single digit number
= print n % 10 + tab + Recursiveprint( n/10)
1. The “Towers of Hanoi” problem: The objective is to move a set of disks arranged in
increasing sizes from top to bottom from the source pole to a destination pole such that they are
in the same order as before using only one intermediate pole subject to the condition that
• Only one disk can be moved at a time
• A bigger disk cannot be placed on a smaller disk.
Write a recursive function which displays all the steps to move n disks from A to C.
1
disks 2
3
4
5
133
Exercise 9 Start Date / /
You should read the following topics before starting this exercise
1. What are arrays and how to declare an array?
2. How to enter data in to array and access the elements of an array.
3. How to initialize an array and how to check the bounds of an array?
4. How to pass an array to a function
An array is a collection of data items of the same data type referred to by a common name. Each
element of the array is accessed by an index or subscript. Hence, it is also called a subscripted
variable.
Arrays and function We can pass an array to a function /* Passing the whole array*/
using two methods. void modify(int a[5])
1. Pass the array element by {
element int i;
2. Pass the entire array to the for(i=0; i<5 ; i++)
function a[i] = i;
}
134
Sample program to find the largest element of an array
#include<stdio.h>
int main()
{
int arr[20]; int n;
void accept(int a[20], int n);
void display(int a[20], int n);
int maximum(int a[20], int n);
1. Write a program to accept n numbers in an array and display the largest and smallest
number. Using these values, calculate the range of elements in the array. Refer to the sample
code given above and make appropriate modifications.
2. Write a program to accept n numbers in an array and calculate the average. Refer to the
sample code given above and make appropriate modifications.
135
Set A. Write programs to solve the following problems
1. Write a program to accept n numbers in the range of 1 to 25 and count the frequency of
occurrence of each number.
2. Write a function for Linear Search, which accepts an array of n elements and a key as
parameters and returns the position of key in the array and -1 if the key is not found. Accept n
numbers from the user, store them in an array. Accept the key to be searched and search it using
this function. Display appropriate messages.
3. Write a function, which accepts an integer array and an integer as parameters and counts
the occurrences of the number in the array.
4. Write a program to accept n numbers and store all prime numbers in an array called prime.
Display this array.
1. Write a program to accept n numbers from the user and store them in an array such that the
elements are in the sorted order. Display the array. Write separate functions to accept and display
the array. (Hint: Insert every number in its correct position in the array)
2. Write a function to sort an array of n integers using Bubble sort method. Accept n numbers
from the user, store them in an array and sort them using this function. Display the sorted array.
3. Write a program to accept a decimal number and convert it to binary, octal and hexadecimal.
Write separate functions.
4. Write a program to find the union and intersection of the two sets of integers (store it in two
arrays).
136
Set C. Write programs to solve the following problems
1. Write a program to merge two sorted arrays into a third array such that the third array is also
in the sorted order.
a1 10 25 90
a2 9 16 22 26 10
0
a3 9 10 16 22 25 26 90 10 0
2. Write a program to accept characters from the user till the user enters EOF and calculate the
frequency count of every alphabet. Display the alphabets and their count.
Input: THIS IS A SAMPLE INPUT
Output: Character Count
T 2
H 1
I 3
…….
3. Write a recursive function for Binary Search, which accepts an array of n elements and a key
as parameters and returns the position of key in the array and -1 if the key is not found. Accept n
numbers from the user, store them in an array and sort the array. Accept the key to be searched
and search it using this function. Display appropriate messages
137
Exercise 10 Start Date / /
You should read the following topics before starting this exercise
1. How to declare and initialize two-dimensional array
2. Accessing elements
3. Usage of two dimensional arrays
138
Sample program to accept, display and print the sum of elements of each row of a matrix.
#include<stdio.h>
int main()
{
int mat[10][10], m, n;
void display(int a[10][10], int m, int n);
void accept(int a[10][10], int m, int n);
void sumofrows(int a[10][10], int m, int n);
1. Write a program to accept, display and print the sum of elements of each row and sum of
elements of each column of a matrix. Refer to sample code given above.
139
Set A . Write C programs for the following problems.
1. Write a program to accept a matrix A of size mXn and store its transpose in matrix B. Display
matrix B. Write separate functions.
2. Write a program to add and multiply two matrices. Write separate functions to accept,
display, add and multiply the matrices. Perform necessary checks before adding and multiplying
the matrices.
1. Write a menu driven program to perform the following operations on a square matrix. Write
separate functions for each option.
i) Check if the matrix is symmetric.
ii) Display the trace of the matrix (sum of diagonal elements).
iii) Check if the matrix is an upper triangular matrix.
2. Write a menu driven program to perform the following operations on a square matrix. Write
separate functions for each option.
i) Check if the matrix is a lower triangular matrix.
ii) Check if it is an identity matrix.
3. Write a program to accept an mXn matrix and display an m+1 X n+1 matrix such that the
th th
m+1 row contains the sum of all elements of corresponding row and the n+1 column contains
the sum of elements of the corresponding column.
Example:
A B
1 2 3 1 2 3 6
4 5 6 4 5 6 15
7 8 9 7 8 9 24
12 15 18 45
1
1 1
1 2 1
1 1 3 3
1
4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
140
2. A magic square of order n is an arrangement of n² numbers, in a square, such that the n
numbers in all rows, all columns, and both diagonals sum to the same constant. A normal magic
square contains the integers from 1 to n². The magic constant of a magic square depends on n
3
and is M(n) = (n +n)/2. For n=3,4,5, the constants are 15, 34, 65 resp. Write a program to
generate and display a magic square of order n.
141
Exercise 11 Start Date / /
You should read the following topics before starting this exercise
1. What is a pointer?
2. How to declare and initialize pointers.
3. ‘*’ and ‘&’ operators.
5. Pointer to a pointer.
6. Relationship between array and pointer.
7. Pointer to array and Array of pointers.
8. Dynamic memory allocation (malloc, calloc, realloc, free).
142
q = *p ;
To allocate memory The functions used are : malloc, int * p,*p1;
dynamically calloc, realloc p = (int *) malloc(10 *
ptr = ( cast-type * ) malloc ( sizeof(int));
byte-size) ; p1 = (int *) calloc(10,
Allocates a block of contiguous sizeof(int));
bytes. If the space in heap is p1=realloc(p1,20*sizeof(int));
not sufficient to satisfy request,
allocation fails, returns NULL.
ptr1 = ( cast-type * ) calloc (
byte-size);
Similar to malloc, but initializes
the memory block allocated to
0.
ptr = realloc ( ptr, new size );
To increase / decrease memory
size.
1. Sample program
/* Program to swap two numbers*/
main()
{
int a = 10, b = 20;
void swap1( int x, int y);
void swap2( int *ptr1, int *ptr2);
143
2. Sample program
/* Program to allocate memory for n integers dynamically*/
#include <stdlib.h>
void main()
{
int *p, n,i;
printf(“How many elements :”);
scanf(“%d”,&n);
p = (int *)malloc(n*sizeof(int));
/* Accepting data */
for(i=0; i<n;i++)
scanf(”%d”,p+i);
/* Displaying data */
for(i=0; i<n;i++)
printf(”%d\t”,*(p+i));
}
1. Type the sample program 1 given above, execute it and write the output.
2. Sample program 2 allocates memory dynamically for n integers and accepts and displays the
values. Type the sample program 2 given above, execute it. Modify the program to allocate
memory such that the allocated memory is initialized to 0.
1. Write a function which takes hours, minutes and seconds as parameters and an integer s
and increments the time by s seconds. Accept time and seconds in main and Display the new
time in main using the above function.
2. Write a program to display the elements of an array containing n integers in the reverse
order using a pointer to the array.
3. Write a program to allocate memory dynamically for n integers such that the memory is
initialized to 0. Accept the data from the user and find the range of the data elements.
2. Write a function which accepts a number and three flags as parameters. If the number is
even, set the first flag to 1. If the number is prime, set the second flag to 1. If the number is
divisible by 3 or 7, set the third flag to 1. In main, accept an integer and use this function to check
if it is even, prime and divisible by 3 or 7. (Hint : pass the addresses of flags to the function)
144
Set C. Write programs to solve the following problems
1. Accept the number of rows (m) and columns (n) for a matrix and dynamically allocate
memory for the matrix. Accept and display the matrix using pointers. Hint: Use an array of
pointers.
n integers
m pointers
2. There are 5 students numbered 1 to 5. Each student appears for different number of
subjects in an exam. Accept the number of subjects for each student and then accept the marks
for each subject. For each student, calculate the percentage and display. (Hint: Use array of 5
pointers and use dynamic memory allocation)
145
Exercise 12 Start Date / /
To demonstrate strings in C.
You should read the following topics before starting this exercise
1. String literals
2. Declaration and definition of string variables
3. The NULL character
4. Accepting and displaying strings
5. String handling functions
Accepting Strings scanf and gets can be used char name[20], address[50];
to accept strings printf(“\n Enter your name :);
scanf(“%s”, name);
printf(“\n Enter your address :);
gets(address);
Displaying Strings printf and puts can be used to printf(“\n The name is %s:”,
display strings. name);
printf(“\n The address is :”);
puts(address);
146
Returns the concatenated
string.
f. strrev – Reverses a string
and returns the reversed
string.
g. strupr – Converts a string
to uppercase.
h. strlwr - Converts a string
to lowercase
Sample program :
The following program demonstrates how to pass two strings to a user defined function and copy
one string to other using pointers
void string_copy (char *t,char *s)
{
while (*s !=’\0’) /* while source string does not end */
{ *t=*s;
s++;
t++;
}
*t =’\0’; /* terminate target string */
}
void main()
{
char str1[20], str2[20];
printf(“Enter a string :”);
gets(str1);
string_copy(str2, str1);
printf(“The copied string is :”);
puts(str2);
}
1. Write a program to accept two strings str1 and str2. Compare them. If they are equal, display
their length. If str1 < str2, concatenate str1 and the reversed str2 into str3. If str1 > str2, convert
str1 to uppercase and str2 to lowercase and display. Refer sample code for string functions
above.
2. Type the sample program above and execute it. Modify the program to copy the characters
after reversing the case. (Hint: First check the case of the character and then reverse it)
1. Write a menu driven program to perform the following operations on strings using standard
library functions:
Length Copy Concatenation Compare
Reverse Uppercase Lowercase Check case
2. Write a program that will accept a string and character to search. The program will
call a function, which will search for the occurrence position of the character in the
147
string and return its position. Function should return –1 if the character is not found in
the string.
3. A palindrome is a string that reads the same-forward and reverse. Example: “madam” is a
Palindrome. Write a function which accepts a string and returns 1 if the string is a palindrome and
0 otherwise. Use this function in main.
4. For the following standard functions, write corresponding user defined functions and write a
menu driven program to use them. strcat, strcmp, strrev, strupr
5. Write a program which accepts a sentence from the user and alters it as follows:
Every space is replaced by *, case of all alphabets is reversed, digits are replaced by ?
1. Write a menu driven program which performs the following operations on strings. Write a
separate function for each option. Use pointers
i. Check if one string is a substring of another.
ii. Count number of occurrences of a character in the string.
iii. Replace all occurrences of a character by another.
3. Write a function which displays a string in the reverse order. (Use recursion)
1. Write a program that accepts a sentence and returns the sentence with all the extra
spaces trimmed off. (In a sentence, words need to be separated by only one space; if
any two words are separated by more than one space, remove extra spaces)
2. Write a program that accepts a string and displays it in the shape of a kite. Example: “abcd”
will be displayed as :
aa
abab
abcabc
abcdabcd
abcabc
abab
aa
3. Write a program that accepts a string and generates all its permutations. For example: ABC,
ACB, BAC, BCA, CAB, CBA
148
t * *
h *
i * * * *
s * * * *
a * *
n * *
g * *
l *
e *
r *
149
Exercise 13 Start Date / /
You should read the following topics before starting this exercise
1. How to declare and initialize strings.
2. String handling functions
3. How to create and access an array of strings.
4. Dynamic memory allocation
An array of strings is a two dimensional array of characters. It can be treated as a 1-D array such
that each array element is a string.
Actions Involving Explanation Example
array of strings
Declaring String array char char cities[4][10]
array[size1][size2];
Initializing String array char cities[4][10] = { “Pune”, “Mumbai”,
“Delhi”, “Chennai”};
Sample program-
The following program illustrates how to accept ‘n’ names , store them in an array of strings and
search for a specific name.
/* Program to search for name from array */
#include <stdio.h>
void main( )
{
char list[10][20]; /*list is an array of 10 strings */
char name[20];
int i,n;
printf(“\n How many names ?:”);
scanf(“%d”, &n);
for (i=0;i<n; i++)
{
printf(“\n Enter name %d,”i);
scanf(“%s”, list[i]);
}
printf(“\n The names in the list are : \n”);
for (i=0; i<n; i++)
printf(”%s”, list[i]);
printf(“\n Enter the name to be searched “);
scanf(“%s”, name);
for (i=0; i<n; i++)
if(strcmp(list[i],name)==0)
{
printf(“Match found at position %d”, i);
break;
}
if(i==n)
printf(“Name is not found in the list”);
}
150
1. Type the above sample program and execute the same for different inputs.
1. Write a program that accepts n words and outputs them in dictionary order.
2. Write a program that accepts n strings and displays the longest string.
3. Write a program that accepts a sentence and splits the sentence into words. Sort each word
and reconstruct the sentence.
Input – this is a string Output – hist is a ginrst
1. Create a mini dictionary of your own. Each entry in the dictionary contains three parts (word,
its meaning, similar word). The entries are stored in the sorted order of words. Write a menu
driven program, which performs the following operations.
i. Add a new word (Insert new word and its details in the correct position)
ii. Dictionary look-up
iii. Find similar word
iv. Delete word
v. Display All words starting with a specific alphabet (along with their meaning).
151
Exercise 14 Start Date / /
You should read the following topics before starting this exercise
1. Bitwise operators and their usage ( &, |, ^, ~, <<, >>)
Sample code: The following function accepts an integer argument and displays it in binary
format. It uses shift operator and AND masking.
1. Write a program to accept n integers and display them in binary. Use the function given
above.
152
Set A . Write C programs for the following problems.
1. Write a program to accept 2 integers and perform bitwise AND, OR, XOR and Complement.
Display the inputs and results in binary format. Use the function in the above exercise.
2. Write a program to swap two variables without using a temporary variable. (Hint: Use XOR)
3. Write a program which accepts two integers x and y and performs x<<y and x>>y. Display
the result in binary.
1. Write functions to calculate the size of an integer, character, long and short integer using
bitwise operators. Store their declaration in file “myfunctions.h” and their definitions in file
“myfunctions.c”. Include these files in your program and use these functions to display the size of
each.
2. Write a program to perform the following operations on an unsigned integer using bitwise
operators and display the result in hexadecimal format.
i. Swap the ____ and ____ nibble ( 4 bits)
ii. Remove the lower order nibbles from the number.
For example: Input: A3F1 Output 00A3
iii. Reverse the nibbles
For example: Input: A3F1 Output 1F3A
1. Write a program to add, subtract, multiply and divide two integers using bitwise operators.
2. Packing and Unpacking Data: A date consists of three parts : day, month, year. To store this
information, we would require 3 integers. However, day and month can take only limited values.
Hence, we can store all three in a single integer variable by packing bits together. If we are using
the dd-mm-yy format, the date will be stored in memory as an unsigned integer (16 bits) in the
following format. Year (Bits 15-9), Month (bits 8 – 5), Day (Bits 4 - 0).
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
y y y y y y y m m m m d d d d d
hour Month day
Accept day, month and year from the user and pack them into a single unsigned int. Unpack and
display them in the binary format. (Hint: for packing, use: 512 * year + 32 * month + day )
The output should be:
Enter the date, month and year –dd mm yy :
31 12 89
Packed date = 1011001110011111
Day = 31
0000000000011111
153
Month = 12
0000000000001100
Year = 89
0000000001011001
3. Packing and Unpacking Data: Time consists of three parts : hours, minutes, seconds. To
store this information, we would require 3 integers. However, all these three variable take only
limited values. Hence, we can store all three in a single integer variable by packing bits together.
Time being 0 to 23 hours, it will require maximum 5 bits, minutes being 0 to 59 will require 6 bits.
The two together take up 11 bits. The remaining 5 bits cannot store seconds which are also in the
range 0 to 59 hence we store double seconds which are in the range 0 to 29
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
h h h h h m m m m m m ds ds ds ds ds
hour Minutes Double seconds
Accept hour, minute and double seconds from the user and pack them into a single unsigned int.
Unpack and display them in the binary format.
The output should be:
Enter the hour, minutes and double seconds –hh mm ss :
07 12 20
Packed date = 0011100110010100
Hour = 07
0000000000000111
Minutes = 12
0000000000001100
Double seconds = 20
0000000000010100
154
Exercise 15 Start Date / /
Structures in C
You should read the following topics before starting this exercise
1. Concept of structure
2. Declaring a structure
3. Accessing structure members
4. Array of structures
5. Pointer to a structure.
6. Passing structures to functions
A structure is a composition of variables possibly of different data types, grouped together under a
single name. Each variable within the structure is called a ‘member’.
155
Sample Code:
#include<stdio.h>
struct student
{ char name[20];
int rollno;
int marks[3];
float perc;
};
void main( )
{
int i, sum j;
struct student s[10];
printf(“\n Enter the details of the 10 students \n”);
for (i=0;i<10;i++)
{
printf(“\n Enter the name and roll number \n”);
scanf(“%s%d”,s[i].name, &s[i].rollno);
printf(“\n Enter marks for three subjects:”);
sum = 0 ;
for { j=0;j<3;j++)
{
scanf(“%d”,&s[i].marks[j]);
sum = sum + s[i].marks[j];
}
s[i].perc = (float)sum/3;
}
/* Display details of students */
printf(“\n\n Name \t Roll no\t Percentage”);
printf(“\n================================\n”);
for(i=0;i<10;i++)
{
printf(“\n%s\t%d\t%f”,s[i].name,s[i].rollno,s[i].perc);
}
}
1. The program in Sample code 1 demonstrates an array of structures of the type student. Type
the above program and run it. Modify the program to display the details of the student having the
highest percentage.
156
2. Create a structure employee (id, name, salary). Accept details of n employees and write a
menu driven program to perform the following operations. Write separate functions for the
different options.
i) Search by name
ii) Search by id
iii) Display all
iv) Display all employees having salary > _____
v) Display employee having maximum salary
Instructor should fill in the blanks with appropriate values.
2. Create a structure Fraction (numerator, denominator). Accept details of n fractions and write
a menu driven program to perform the following operations. Write separate functions for the
different options. Use dynamic memory allocation. Note: While accepting fractions, store the
fractions in the reduced form.
i) Display the largest fraction
ii) Display the smallest fraction
iii) Sort fractions
iv) Display all
2. The government of a state wants to collect census information for each city and store the
following information : city name, population of the city, literacy percentage. After collecting data
for all cities in the state, the government wants to view the data according to :
i. Literacy level
ii. Population
iii. Details of a specific city.
Write a C program using structures and dynamic memory allocation.
157
Exercise 16 Start Date / /
You should read the following topics before starting this exercise
1. Creating and accessing structures
2. Array of structures
3. Dynamic memory allocation
4. Structure within a structure
5. Creating and accessing unions
Nested structures: The individual members of a structure can be other structures as well. This is
called nesting of structures.
158
};
Unions A union is a variable that union u
contains multiple members of {
possibly different data types char a;
grouped together under a single int b;
name. However, only one of };
the members can be used at a
time. They occupy the same
memory area.
Sample Code 1:
Example: The following structure is for a library book with the following details : id, title, publisher,
code ( 1 – Text book, 2 – Magazine, 3 – Reference book). If the code is 1, store no-of-copies. If
code = 2, store the issue month name. If code = 3, store edition number. Also store the cost.
struct library_book
{
int id;
char title[80],publisher[20] ;
int code;
union u
{
int no_of_copies;
char month[10];
int edition;
}info;
int cost;
};
void main( )
{
struct library_book book1;
printf(“\n Enter the details of the book \n”);
159
printf(“\n Title = %s”, book1.title);
printf(“\n Publisher = %s”, book1.publisher);
switch(book1.code)
{
case 1: printf(“Copies = %d:”, book1.info.no_of_copies);
break;
case 2: printf(“Issue month name = %s”,book1.info.month);
break;
case 3: printf(“Edition number =%d:”,book1.info.edition);
break;
}
printf(“\n Cost = %d”, book1.cost);
}
Sample Code 2:
A linked list is a collection of data elements which are linked to one another by using pointers i.e.
the every node stores the address of the next node. The advantage of using a linked list over an
array is that it is easy to insert and delete elements from the list.
To create a linked list, we have to use a self referential structure (See table above). Each element
of the list is called a node.
info next info next info next info next
list NULL
#include <stdio.h>
struct node
{
int info;
struct node *next;
};
struct node *list = NULL; /* list is a pointer to the linked list */
void createlist()
{
struct node *temp, *p;
int i;
for(i=1;i<=5;i++)
{
p=(struct node *)malloc(sizeof(struct node)); /* create a node */
p->info = i;
p->next=NULL;
if(list == NULL)
list=temp=p; /* list points to the first node */
else
{
temp->next=p; /* link new node to the last */
temp=p;
}
}
void displaylist()
{
struct node *temp;
160
for(temp=list; temp!=NULL; temp=temp->next) /* use a temporary pointer */
printf(%d \t”, temp->info);
}
void main( )
{
createlist();
displaylist();
}
1. The sample code 1 given above demonstrates how we can create a variable of the above
structure and accept and display details of 1 book. Type the program and execute it. Modify the
program to accept and display details of n books.
2. The sample code 2 given above demonstrates how we can create a linked list and traverse
the list. Type the program and execute it. Modify the displaylist function to display only the even
numbers from the list.
1. Modify the sample program 1 above to accept details for n books and write a menu driven
program for the following:
2. Modify the sample program 1 to accept details for n books and write a menu driven program
for the following:
3. Modify the sample program 1 to accept details for n books and write a menu driven program
for the following:
161
Set B. Write programs to solve the following problems
2. Write a program to create a linked list of n nodes and accept data from the user for each
node. Display the list. Accept a number from the user and search for the element in the list.
1. A shop sells electronic items. Each item has an id, company name, code (1-TV, 2-Mobile
phones, 3-Camera) and cost. The following additional details are stored for each item.
• TV - size, type ( CRT-1 / LCD- 2 / Plasma-3)
• Mobile Phone - type ( GSM – 1 / CDMA – 2) , model number.
• Camera – resolution, model number.
The shop wants to maintain a list of all items and perform the following operations for each of the
item types:
i) Display all
ii) Search for specific item
iii) Sort according to cost
2. Write a program to create a linked list of n nodes and accept data from the user for each
node. Write a menu driven program to perform the following operations:
i) Display the list
ii) Search for specific number
iii) Display the element after ____
iv) Find the maximum / minimum
162
Exercise 17 Start Date / /
You should read the following topics before starting this exercise
1. Passing arguments from the command line to main
2. Accessing command line arguments
3. File inclusion, macro substitution and conditional compilation directives.
4. Argumented and Nested macros
163
Sample Code 1
void main()
{
int m; char c;
printf(“Enter an integer corresponding to the month”);
scanf(“%d”,&m);
if(NEGATIVE(m))
printf(“Enter a positive number”);
else
if(INRANGE(m))
printf(“You Entered a valid month”);
1. Write a program to display all command line arguments passed to main in the reverse order.
Hint: See table above.
2. Sample code 1 above demonstrates the use of argumented and nested macros. Type the
program and execute it.
1. Write a program to accept three integers as command line arguments and find the minimum,
maximum and average of the three. Display error message if invalid number of arguments are
entered.
2. Write a program which accepts a string and two characters as command line arguments and
replace all occurrences of the first character by the second.
164
3. Define a macro EQUALINT which compares two parameters x and y and gives 1 if equal
and 0 otherwise. Use this macro to accept pairs of integers from the user. Calculate the sum of
digits of both and continue till the user enters a pair whose sum of digits is not equal.
4. Define a macro EQUALSTR which compares two strings x and y and gives 1 if equal and 0
otherwise. Use this macro to accept two strings from the user and check if they are equal.
1. Write a program to accept two strings as command line arguments and display the union
and intersection of the strings. If the user enters invalid number of arguments, display appropriate
message.
2. Write a program which accepts a string and an integer (0 or 1) as command line arguments.
If the integer entered is 0, sort the string alphabetically in the ascending order and if it is 1, sort it
in the descending order. If the user enters invalid number of arguments, display appropriate
message. (Hint – use atoi)
Include this file in your program. Write a menu driven program to use macros SQR, CUBE,
GREATER2 and GREATER3. Your program should run the first two macros if the macro called
FLAG has been defined. If it is not defined, execute the other two macros. Run the program twice
– with FLAG defined and with FLAG not defined.
165
Exercise 18 Start Date / /
You should read the following topics before starting this exercise
1. Concept of streams
2. Declaring a file pointer
3. Opening and closing a file
4. Reading and Writing to a text file
5. Command line arguments
Sample Code 1
The following program reads the contents of file named a.txt and displays its contents on the
screen with the case of each character reversed.
/* Program revrese case of characters in a file */
#include <stdio.h>
#include <ctype.h>
void main()
{
FILE * fp;
fp = fopen(“a.txt”, “r”);
if(fp==NULL)
{
printf(“File opening error”);
166
exit(0);
}
while( !feof(fp))
{
ch = fgetc(fp);
if(isupper(ch))
putchar(tolower(ch));
else
if(islower(ch))
putchar(toupper(ch));
else
putchar(ch);
}
fclose(fp);
}
Sample Code 2
The following program displays the size of a file. The filename is passed as command line
argument.
#include <stdio.h>
void main(int argc, char *argv[])
{
FILE * fp;
long int size;
fp = fopen(argv[1], “r”);
if(fp==NULL)
{
printf(“File opening error”);
exit(0);
}
fseek(fp, 0, SEEK_END); /* move pointer to end of file */
size = ftell(fp);
printf(“The file size = %ld bytes”, size);
fclose(fp);
}
Sample Code 3
The following program writes data (name, roll number) to a file named student.txt , reads the
written data and displays it on screen.
#include <stdio.h>
void main()
{
FILE * fp;
char str[20]; int num;
fp = fopen(“student.txt”, “w+”);
if(fp==NULL)
{
printf(“File opening error”);
exit(0);
}
fprintf(fp,“%s\t%d\n”, “ABC”, 1000);
fprintf(fp,“%s\t%d\n”, “DEF”, 2000);
fprintf(fp,“%s\t%d\n”, “XYZ”, 3000);
167
rewind(fp);
while( !feof(fp))
{
fscanf(fp,“%s%d”, str, &num);
printf(“%s\t%d\n”, str, num);
}
fclose(fp);
}
1. Create a file named a.txt using the vi editor. Type the sample program 1 given above and
execute the program. Modify the program to accept a character from the user and count the total
number of times character occurs in the file.
2. Type the sample program 2 above and execute it. Modify the program to display the last n
characters from the file.
3. Type the sample program 3 above and execute it. Modify the program to accept details of n
students and write them to the file. Read the file and display the contents in an appropriate
manner.
1. Write a program to accept two filenames as command line arguments. Copy the contents of
the first file to the second such that the case of all alphabets is reversed.
2. Write a program to accept a filename as command line argument and count the number of
words, lines and characters in the file.
3. Write a program to accept details of n students (roll number, name, percentage) and write it
to a file named “student.txt”. Accept roll number from the user and search the student in the file.
Also display the student details having the highest percentage.
1. A file named numbers.txt has a set of integers. Write a C program to read this file and
convert the integers into words and write the integer and the words in another file named
numwords.txt.
Example:
numbers.txt numwords.txt
11 Eleven
261 Two hundred Sixty One
9 Nine
2. Write a program which accepts a filename and an integer as command line arguments and
encrypts the file using the key. (Use any encryption algorithm)
168
Signature of the instructor Date / /
1. A text file contains lines of text. Write a program which removes all extra spaces from the
file.
2. Write a menu driven program for a simple text editor to perform the following operations on a
file, which contains lines of text.
i. Display the file
ii. Copy m lines from position n to p
iii. Delete m lines from position p
iv. Modify the nth line
v. Add n lines
3. Write a program which reads the contents of a C program and replaces all macros occurring
in the program with its value. Assume only simple substitution macros (ex: #define FALSE 0 ).
169
Exercise 19 Start Date / /
You should read the following topics before starting this exercise
1. Concept of streams
2. Declaring a file pointer
3. Opening and closing files
4. File opening modes
5. Random access to files
6. Command line arguments
In binary files, information is written in the form of binary . All data is written and read with no
interpretation and separation i.e. there are no special characters to mark end of line and end of
file.
I/O operations on binary files
Sample Code
/* Program to demonstrate binary file */
struct employee
{ char name[20];
float sal;
};
main( )
{
FILE *fp;
struct employee e;
int i;
if((fp=fopen (“employee.in”,“wb”))==NULL)
{ printf(“Error opening file”);
exit( );
}
for(i=0;i<5;i++)
{
printf(”\n Enter the name and salary”);
scanf(“%s%f”,e.name,&e.sal);
fwrite(&e,sizeof(e),1,fp);
}
170
fclose(fp);
1. Type program given above, writes data of 5 employees to a binary file and then reads the file.
Modify the program to search an employee by name.
1. Create a structure student (roll number, name, percentage) Write a menu driven program to
perform the following operations on a binary file- “student.dat”. Write separate functions for the
different options.
1. Add a student (Note: Students should be assigned roll numbers consecutively)
2. Search Student
a. according to name
b. according to roll number
3. Display all students
2. Create a structure student (roll number, name, percentage) Write a menu driven program to
perform the following operations on a binary file- “student.dat”. Write separate functions for the
different options.
171
Signature of the instructor Date / /
1. Create two binary files such that they contain roll numbers, names and percentages. The
percentages are in ascending orders. Merge these two into the third file such that the third file still
remains sorted on percentage. Accept the three filenames as command line arguments.
1. Create a binary file which contains details of student projects namely roll number, project
name, project guide. The first line of the file contains an integer indicating the total number of
students. When the program starts, read all these details into an array and perform the following
menu driven operations. When the user selects Exit from the menu, store these details back into
the file.
1. Add 2. Delete 3. Search 2. Modify 3. Display all 4. Exit
172
Exercise 20 Start Date / /
Display a calendar for a particular year. If month-number is supplied, only that month is displayed.
Write a program that will multiply two (2) N digit positive integers, where N may be
arbitrarily large. Your program should output the product(s).
Input format: One N digit positive integer per line in input and output files.
Sample Input:
65656432310964579864321356898765432243578987876654
94454
Sample Output:
6201512657499848426504609444515990137135009720901476916
A company has just finished construction of their new pentagon shaped office building. However
identifying the location of a room is a problem.
Room numbers will be between 100 and 99999 inclusive. The ones digit (rightmost) tells which
side of the pentagon the room is on. The next one after that, the tens digit, gives the hall number
in which the room is (see table). The digits after that give which floor the room is on.
0,1 Hall 1
2,3 Hall 2
4,5 Hall 3
6,7 Hall 4
8,9 Hall 5
The least significant digit (right-most) tells whether the room is on the courtyard or outside edge of
the hall. If it is even, the room faces the courtyard, if it is odd, it faces the outside.
Input Format: The input will consist a list of room numbers not longer than 5 digits. The input
ends with -1.
Output Format: You will print the Room, Floor, Hall, and Side that each room number
represents.
173
Room r is on Floor f in Hall h facing {courtyard|outside}
Example Input:
111
1322
455
512
-1
Example Output:
Room 111 is on Floor 1 in Hall 1 facing outside
Room 1322 is on Floor 13 in Hall 2 facing courtyard
Room 455 is on Floor 4 in Hall 3 facing outside
Room 512 is on Floor 5 in Hall 1 facing courtyard
An anagram is a pair of words or sentences that contain the same number of the same letters.
Examples include Dormitory whose anagram is Dirty Room. You will write a program to
recognize whether a pair of words or sentences are anagrams.
Input: The input accept two strings and check whether they are anagrams.
Output: If a pair of strings tested are anagrams of each other, print “An Anagram,” otherwise
print, “Not An Anagram.”
Example Input 1:
dormitory
dirtyroom
Output:
An Anagram
Example Input 2:
eleven plus two
twelve plus one
Output:
An Anagram
Example Input 3:
thisisntananagram
andthatissuchashame
Output:
Not An Anagram
You have determined that the enemy is using the following mechanism to encode secret words.
You believe that the first letters of each word in enemy messages form secret words. Only the
first letters of consecutive words are used to form the secret words. Further, a sentence may
contain other words before and/or after the actual words that make up the secret word.
Messages always contain a single space between words.
174
Write a program that takes a secret word and a message as input and determines if the message
contains the secret word. The program should not be case-sensitive and should ignore
punctuation.
Input Format: The first line of input consists of the secret word. The second line contains the
sentence to check.
Output Format: The output will be “Secret word found” if the secret word is found in the
sentence, otherwise, output “Secret word not found.”
Input:
year
the yellow elephant ate raw bananas
Output:
Secret word found
Input:
you
you will often fail unless you try harder
Output:
Secret word not found
You are provided with a credit card number with the length varying from 13 digits to 16 digits.
Each digit of the credit card is weighted by either 2 or 1. The credit card number must be zero-
filled on the left to create a sixteen digit number, and then the pattern starts with 2, alternating
with a 1. If the number multiplied by the weight results in a 2-digit number, each digit is added to
the sum. The final sum with the check digit should be a multiple of 10.
Example:
5 4 9 9 0 0 1 1 0 0 1 2 0 0 3 4
2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1
1+0 +4 +1+8 +9 +0 +0 +2 +1 +0 +0 +2 +2 +0 +0 +6 +4 =40
40 mod 10 = 0. If the last digit did not result in a number divisible by 10, the credit card
number is invalid.
Input Format: The user will provide you with a credit card number without spaces.
Output Format: The program will return "Valid" or "Invalid" depending on the success or failure of
the check digit.
Input:
5499001100120034
Output:
Valid
Input:
5499001100120036
Output:
Invalid
175
current date (day, month, year) and the number of issue days as input and generate the due date
as output.
Write a C program which reads the contents of a file containing a C program and removes all
comments from the program.
Write a C program which reads the contents of a text file and generates a histogram of
frequencies of all alphabets in the file. Use * to draw the histogram bars.
“Cryptarithmetic” puzzles are puzzles in which one gets problems like these
hello
+ there
-------
world
and is asked to assign digits to each letter so that the resulting addition is correct. Each digit from
0 to 9 must be used at most once, and the leading digits may not be 0. In the above cases, for
example, we can get the solutions
56442
+ 15606
-------
72048
Write a program to find a solution to cryptarithmetic problems for which the input consists of
triples of strings each containing up to 128 lower-case letters and the output is in the form given in
the sample below.
For the input Produce the output
hello there world hello 56442
+ there + 15606
------- -------
world 72048
Write a program which compresses a text file such that consecutive occurrences of specific
character are replaced by the character followed by a digit indicating the number of times the
character occurs. Replace only if the character occurs 3 or more times consecutively. For
example, if the input text is “aath1111yy66666kkk baabbbbdg”, the output should be
“aath14yy65k3 4baab4dg”. Write a decompression program which reads a compressed file and
generates the original text.
This problem is to place 4 queens on a 4X4 chessboard such that no two queens can attack. i.e.
No two queens are on the same row, same column or diagonal. Write a program to generate all
possible valid placements. One possible solution is shown below.
176
Q
Q
Q
Q
The output is a set of column numbers { c1, c2, c3, c4} such that cj is the column number in which
Queen j is placed (in row j). For the above example, the output is {2,4,1,3}. Extend your program
for n queens.
177
Appendix A
Here are the steps to configure the NFS server in this scenario:
1. Edit the /etc/exports file to allow NFS mounts of the /home directory with read/write access.
/home *(rw,sync)
2. Let NFS read the /etc/exports file for the new entry, and make /home available to the network
with the exportfs command.
[root@bigboy tmp]# exportfs -a
3. Make sure the required nfs, nfslock, and portmap daemons are both running and configured to
start after the next reboot.
[root@bigboy tmp]# chkconfig nfslock on
[root@bigboy tmp]# chkconfig nfs on
[root@bigboy tmp]# chkconfig portmap on
[root@bigboy tmp]# service portmap start
[root@bigboy tmp]# service nfslock start
[root@bigboy tmp]# service nfs start
After configuring the NFS server, we have to configure its clients, This will be covered next.
You also need to configure the NFS clients to mount their /home directories on the NFS server.
1. Make sure the required netfs, nfslock, and portmap daemons are running and configured to
start after the next reboot.
[root@smallfry tmp]# chkconfig nfslock on
[root@smallfry tmp]# chkconfig netfs on
[root@smallfry tmp]# chkconfig portmap on
[root@smallfry tmp]# service portmap start
[root@smallfry tmp]# service netfs start
[root@smallfry tmp]# service nfslock start
2. Keep a copy of the old /home directory, and create a new directory /home on which you'll
mount the NFS server's directory.
[root@smallfry tmp]# mv /home /home.save
[root@smallfry tmp]# mkdir /home
3. Make sure you can mount bigboy's /home directory on the new /home directory you just
created. Unmount it once everything looks correct.
[root@smallfry tmp]# mount 192.168.1.100:/home /home/
[root@smallfry tmp]# ls /home
[root@smallfry tmp]# umount /home
4. Start configuring autofs automounting. Edit your /etc/auto.master file to refer to file
/etc/auto.home for mounting information whenever the /home directory is accessed. After five
minutes, autofs unmounts the directory.
#/etc/auto.master
/home /etc/auto.home --timeout 600
5. Edit file /etc/auto.home to do the NFS mount whenever the /home directory is accessed. If the
line is too long to view on your screen, you can add a \ character at the end to continue on the
next line.
#/etc/auto.home
* -fstype=nfs,soft,intr,rsize=8192,wsize=8192,nosuid,tcp \
192.168.1.100:/home:&
6. Start autofs and make sure it starts after the next reboot with the chkconfig command.
[root@smallfry tmp]# chkconfig autofs on
[root@smallfry tmp]# service autofs restart
178
You need to add the NIS domain you wish to use in the /etc/sysconfig/network file. For the school,
call the domain NISNETWORK.
#/etc/sysconfig/network
NISDOMAIN="NISNETWORK"
2. Edit Your /etc/yp.conf File
NIS servers also have to be NIS clients themselves, so you'll have to edit the NIS client
configuration file /etc/yp.conf to list the domain's NIS server as being the server itself or localhost.
# /etc/yp.conf - ypbind configuration file
ypserver 127.0.0.1
Start the necessary NIS daemons in the /etc/init.d directory and use the chkconfig command to
ensure they start after the next reboot.
[root@bigboy tmp]# service portmap start
[root@bigboy tmp]# service yppasswdd start
[root@bigboy tmp]# service ypserv start
[root@bigboy tmp]# chkconfig portmap on
[root@bigboy tmp]# chkconfig yppasswdd on
[root@bigboy tmp]# chkconfig ypserv on
Now that you have decided on the name of the NIS domain, you'll have to use the ypinit
command to create the associated authentication files for the domain. You will be prompted for
the name of the NIS server, which in this case is bigboy.
With this procedure, all nonprivileged accounts are automatically accessible via NIS.
[root@bigboy tmp]# /usr/lib/yp/ypinit -m
At this point, we have to construct a list of the hosts which will run NIS
servers. bigboy is in the list of NIS server hosts. Please continue to add
the names for the other hosts, one per line. When you are done with the
list, type a <control D>.
next host to add: domainname
next host to add:
The current list of NIS servers looks like this:
domainname
You can now start the ypbind and the ypxfrd daemons because the NIS domain files have been
created.
[root@bigboy tmp]# service ypbind start
Listening for an NIS domain server.
[root@bigboy tmp]# service ypxfrd start
[root@bigboy tmp]# chkconfig ypbind on
[root@bigboy tmp]# chkconfig ypxfrd on
Now that the NIS server is configured, it's time to configure the NIS clients. There are a number of
related configuration files that you need to edit to get it to work. Take a look at the procedure.
1. Run authconfig
The authconfig or the authconfig-tui program automatically configures your NIS files after
prompting you for the IP address and domain of the NIS server.
[root@smallfry tmp]# authconfig-tui
179
Once finished, it should create an /etc/yp.conf file that defines, amongst other things, the IP
address of the NIS server for a particular domain. It also edits the /etc/sysconfig/network file to
define the NIS domain to which the NIS client belongs.
2. Start The NIS Client Related Daemons
Start the ypbind NIS client, and portmap daemons in the /etc/init.d directory and use the chkconfig
command to ensure they start after the next reboot. Remember to use the rpcinfo command to
ensure they are running correctly.
[root@smallfry tmp]# service portmap start
[root@smallfry tmp]# service ypbind start
2. Configuration Files
In pg_hba.conf file we have to define
* max_connection allowed
* port
postgresql.conf -This file contents Client Authentication Configuration. In this file we have to
define Database name and database owner
180
References
181