Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Foc Lab Manual

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 77

JERUSALEM COLLEGE OF ENGINEERING CHENNAI-100 DEPARTMENT OF COMPUTER APPLICATIONS

LABORATORY MANUAL COMPUTER PRACTICE LABORATORY-II B.E II-SEMESTER 2010-2011

I N D E X S. N O
1 2 3 4 5

N A M E O F T H E EX P E R I M E N T
Study Of Unix Operating System. Study Of Basic Unix Commands. Study Of Vi Editors. Calculating The Gross Salary Of an Employee. Finding The Area Of A Circle. To Implement The Concept Of Two-Way Branching Using If Statement. To Implement The Concept Of Multi-Way Branching Using If- Elif Statement. To Implement The Concept Of Multi-Way Branching Using Case Statement. To Write A Program To Print N Natural Numbers. To Write A Program To Print First N Number Of Fibonacci Series. To Write A Program To Print The Multiplication Table Using Until Loop. To Write A Program To Print The Sum Using For Loop. To Write A Program To Calculate The Factorial Of a Given Number. Program For The Illustration Of Pointer Expressions. Program For Dynamic Memory Allocation, Reallocation And Deletion Program To Create File, To Store Information In The File And To Show The Information In The File By Using File Handling Functions.

7 8 9 10 11 12 13 14 15

16

S T U D Y O F U N I X O PE R A T I N G SYS T EM
W H AT I S U N I X? UNIX is an operating system which was develope d first in the 1960s and has under constant development ever since by op eratingsystem we mean the suite of programs which make the computerw ork. It is a stable, multi-user, multi-tasking operating system forser vers, desktops and laptops. UNIX operating system also have graphical u ser interface (GUI)similar to Microsoft windows operati ng system which provides an e as y to use e n v ir o n m en t . Ho w ev e r k n o w le d g e o f u n i x i s r e quired for operations which are not covered by graphical program or for whenthere is nowindows interface available . TYPES OF UN IX

There are many different versions of unix, although t h e y s h a r e t h e c o m m o n s i m i l a r i t i e s .T h e m o s t p o p u l a r v a r i e ties of unixare Sun Solaris, GNU/Linux and Macos X. T H E U N I X O P E R A T I N G S Y S T EM

The Unix Operating system is made up of three parts

1. The Kernel

2. The Shell

3. The Programs

THE KERNEL

The Kernel of Unix is the hub of the operating syste m. Itallocates time and memory to programs and handles thefile storeand communication in response to system calls. A s an illustration of the way that the shell and the kernel work t og e t h e r , s u p p o s e a u s e r t y p e s r m m y f i l e . T h e s h e l l s earches the filestore for the filecontaining the program rmand then requests th e kernel,through system calls to rm myfile finished running, the shell the n returnsthe unix prompt % to the user, indicating execute the program rmon myfile. When the process that it is waiting for future commands.

THE SHEL L

The shell acts as an interface between the user an d thekernel. When user login, the login program checks the u sername andpassword, and then starts another program ca lled the shell. Theshell is a command line interpreter (CLI ). It interprets the commandsthe user types in an arranges for them to be carried out. Thecommands are themselves programs. When they terminate, the shellgives the user ano ther prompt (% on our system). By typing part ofthe name o f a command, filename and directory and pressing the[tab ] key, the shell will complete the rest of them automaticall y. Ifshell finds more than one name beginning with those letters youhave typed, it will beep, prompting to type a few more letters bef orepressing the tab key again.

The shell keeps the list of the commands you have typed in, if youneed to repeat a command, use the cursor key to scroll up and downthe list or type history for a list of previous c ommands. Differentusers may use different shells. Initial ly, your system administratorwill supply a default shell, w h i c h c a n b e o v e r r id d e n o r c h a n g e d .

Themostcommonlyavailableshells are:

o o

Bourne shell (sh)C shell (csh) Korn shell (ksh)

o TCShell(tcsh)
o

Bourne Again Shell(bash)

T he Bo ur n e sh e l l i s o n e o f t h e o l d e s t s h e l l s a n d i s t h e m o s t e fficient for background work.However it provides few facili ties forinteractive users.

T he C s h e l l p r o v i d e s s o p h i s t i c a t e d i n t e r a c t i v e c a p a b i l i t i e s l ackingin the Bourne shell.Features of this shell include a commandhistory buffer, command aliases and file name

c o m p l e t i o n .T h e C s h e l l h a s a s y n t a x w h i c h r o g r a m m i n g l a n g u a g e.

resemblestheCp

The C shell is the default shell for interactive work on many UNIXsystems. It will be covered in this document, althoug h most of thebasic commands given here are relatively standard across all themain shell s.

T he Ko r n s h e l l w a s w r i t t e n b y D a v i d K o r n f r o m A T & T a n d i n it heattempted to merge the preferred features of both the B ourne and Cshellsaswellasaddingsomeadditionalfeatures. Unfortunately the Korn shell was not available for free, as otherUNIX shells were, so many users and companies di d not chose touse of it.

T he Ba s h s h e l l w a s b a s e d o n t h e B o u r n e s h e l l ( B o u r n e a g a i n s h ell) and as with Korn it attempted to combine the best featur es ofthe other shells which were available at the time. This s hell howeverwas available for free.Bash was initially adopted for LINUX although several varieties of

LINUX now exist e.g. RedHat, SuSE and Debian-GNU.

FILES AND PROCESS Everything in unix is either a file or a process. A proce ssisan

executingprogram identifiedbyauniquePID ntifier).

(ProcessIde

A file is collection of datas. They are created by us ers using texteditors, running, compilers etc.

All files are grouped together in the directory structure. The filesystem is arranged in a hierarchical structure, like i nverted tree. Thetop of the hierarchy is traditionally called root .

FEATURES OF U NIX

1.Multitasking

Multitasking is the capability of the operating syst e m t o p e r f o r m v a r i o u s t a s k s s i m u l t a n e o u s l y ie a s i n g l e u s e r c a n r u n m u l t i p l e p r o g r a m s( t a s k s ) c o n c u r r e n t l y .

2.Multi-user Capability

Multi-user capability of UNIX allows several users t o use thesame computer to perform their tasks. Several term inals (keyboardsand monitors) are connected to a single p owerful computer (Unixserver) and each user can work with their terminals.

3 .S e c u r i t y

Unix allows sharing of data. Every user must have a lo g i n n a m e an d a p a s s w o r d .S o a c c e s s i n g a n o t h e r u s e r s d a t a i s i m p o s s i b l e w i t h

o u t p e r m i s s i o n ie invalid users cannot access data.

4. Portability

UNIX is portable because it is written in a high level la nguage.So, UNIX can be run on different computers.

5. Communication

UNIX supports the fallowing communications

o Between the different terminals connected to the UNIX

server .

o B e t w e e n t h e u s e r s o f o n e c o m p u t e rt o t h e u s e r s o f another computer located elsewhere in the networ k.

6. Programming facility

UNIX is highly programmable, the UNIX shell prog ramminglanguage has all necessary ingredients like condit ional and controlstructure (Loops) and variables, that establish it as a programmingla nguage in its own right.

ADVANTAGES OF UNIX

UNIX is a very stable operating system.

UNIX supports the Multi-User feature.

UNIX is a Multitasking operating system.

UNIX can be loaded to any type of computer hardware.

UNIX is optimized for program development.

UNIX has rich set of small commands and utilities t hat dospecific tasks.

UNIX has a powerful unified file system, everything i n a file; data, program and all physical dev ices.

UNIX has the ability to string commands and utilities togetherin unlimited ways to accomplish more complic ated tasks.

U N I X a l l o w s o n l y a u t h o r i z e du s e r s t o m o d i f y f i l e s a n d directories.

UNIX allows only System Administrators to make cha nges in System Configuration files.

EX NO: 2

STUDY OF BASIC UNIX COMMANDS

GENERAL COMMANDS

NO 1 2

COMMAND Date Cal

SYNTAX Date cal MM YYYY

VARIANCE/OPTIONS

DESCRIPTION Displays the current date and time Displays the calendar of the current month Displays the calendar of the whole year specified Displays the calendar of the specified month and year Displays the manual pages of the command name specified. Displays information about people who are presently logged in Displays information about oneself Displays information about the specified user

Cal cal YYYY cal MM YYYY

3 4

Man Who

man command name Who

5 6

who am i Finger

who am i finger user -

FILE MANAGEMENT COMMANDS NO 7 COMMAND Cat SYNTAX cat > filename VARIANCE/ OPTIONS cat > filename DESCRIPTION Creates a file with the specified name Displays the specified file in the console Copies the specified files to filez Appends contents to the specified file removes the specified file Moves the file to the destination Renames the file with the new name Renaming can be done while moving within the same directory or different directory Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. More is a filter for paging through text one screenful at a time for lengthy files.

cat filename

cat file1 file2filen > filez cat >> filename

8 9

Rm Mv

rm filename mv filename destination

mv filename destination mv filename newname

10

Cp

cp source destination

11

More

more file

14 12 15

File Page Wc page file

file filename

wc filename

Displays the type of the Same as more except that specified file more requires spacebar to Print the page be pressed for every number of lines, words, whereas page requires characters and return key to be pressed bytes in the file.

16 13 17

Head Ls Tail Ls

head n filename -l shows about permission, owner, size tail n filename etc -a shows all files including hidden files

Display the first n lines from the file Display the last n lines from the file

18

Sort

sort filename the -R displays contents of subdirectories

-r sort in reverse order

-f sort ignoring case -r reverses the order of files displayed -n sort numerically ls ~ List the contents of your home directory -b ignore leading ls / List the contents of blanks

Sorts the lines in the text files and displays them in the console

19

Grep

your root directory grep pattern -F for fixed filename grep . -E ls ../ List the contents for extended grep of the parent directory. ls */ List the -c print the count contents of all sub of matching lines directories. -i ignore case for ls -d */ Only list the matching directories in the -h prefix each current directory. matching line with line number

Grep searches the named input FILEs for lines containing a match to the given PATTERN.

20

Chmod

chmod filename users + permissions file/directory

+ for adding permission - for removing permission u stands for owner g stands for group o stands for others

chmod changes the permissions of each given file according to the mode specified

DIRECTORY MANAGEMENT COMMANDS

NO 21 22 23

COMMAND Mkdir Rmdir Mv

SYNTAX Mkdir dirname Rmdir dirname mv dirname destination

VARIANCE/OPTIONS

DESCRIPTION Creates a directory with the specified name. Deletes the specified directory if not empty Move the directory and all its contents to the destination. If a name is specified in the destination, the directory will be renamed. Shows the current directory

24 25

Pwd Cd

Pwd cd cd ~ cd .. cd -

Moves to the home directory Moves to the parent directory Moves to the previous directory

EX:NO:3

VI EDITOR

What is VI?

The default editor that comes with the UNIX operating system is called vi (visual editor). [Alternate editors for UNIX environments include Pico and emacs, a product of GNU.] The UNIX vi editor is a full screen editor and has two modes of operation:

1. Command mode commands which cause action to be taken on the file, and 2. Insert mode in which entered text is inserted into the file.

In the command mode, every character typed is a command that does something to the text file being edited; a character typed in the command mode may even cause the vi editor to enter the insert mode.

In the insert mode, every character typed is added to the text in the file; pressing the <Esc> (Escape) key turns off the Insert mode.

The most basic and useful commands are marked with an asterisk (* or star) in the tables below. NOTE: Both UNIX and vi are case-sensitive. Be sure not to use a capital letter in place of a lowercase letter; the results will not be what you expect.

To Get Into and Out Of VI

To Start vi

To use vi on a file, type in vi filename. If the file named filename exists, then the first page (or screen) of the file will be displayed; if the file does not exist, then an empty file and screen are created into which you may enter text. edit filename starting at line 1 * vi filename
vi -r filename

Recover filename that was being edited when system crashed

To Exit vi

Usually the new or modified file is saved when you leave vi. However, it is also possible to quit vi without saving the file. Note: The cursor moves to bottom of screen whenever a colon (:) is typed. This type of command is completed by hitting the <Return> (or <Enter>) key. * :x<Return> quit vi, writing out modified file to file named in original invocation
:wq<Return> :q<Return>

quit vi, writing out modified file to file named in original invocation quit (or exit) vi

* :q!<Return> quit vi even though latest changes have not been saved for this vi call

Moving the Cursor

Unlike many of the PC and MacIntosh editors, the mouse does not move the cursor within the vi editor screen (or window). You must use the key commands listed below. On some UNIX platforms, the arrow keys may be used as well; however, since vi was designed with the Qwerty keyboard (containing no arrow keys) in mind, the arrow keys sometimes produce strange effects in vi and should be avoided. If you go back and forth between a PC environment and a UNIX environment, you may find that this dissimilarity in methods for cursor movement is the most frustrating difference between the two. In the table below, the symbol ^ before a letter means that the <Ctrl> key should be held down while the letter key is pressed.

j or <Return> * [or down-arrow] move cursor down one line

* k [or up-arrow] h or <Backspace> * [or left-arrow] l or <Space> * [or right-arrow] * 0 (zero) *$ w b :0<Return> or 1G :n<Return> or nG :$<Return> or G

move cursor up one line

move cursor left one character

move cursor right one character move cursor to start of current line (the one with the cursor) move cursor to end of current line move cursor to beginning of next word move cursor back to beginning of preceding word move cursor to first line in file move cursor to line n move cursor to last line in file

Screen Manipulation

The following commands allow the vi editor screen (or window) to move up or down several lines and to be refreshed. ^f move forward one screen ^b move backward one screen ^d move down (forward) one half screen ^u move up (back) one half screen ^l redraws the screen redraws the screen, removing deleted ^r lines

Adding, Changing, and Deleting Text

Unlike PC editors, you cannot replace or delete text by highlighting it with the mouse. Instead use the commands in the following tables. Perhaps the most important command is the one that allows you to back up and undo your last action. Unfortunately, this command acts like a toggle, undoing and redoing your most recent action. You cannot go back more than one step.

* u

UNDO WHATEVER YOU JUST DID; a simple toggle

The main purpose of an editor is to create, add, or modify text for a file.

Inserting or Adding Text

The following commands allow you to insert and add text. Each of these commands puts the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate the entry of text and to put the vi editor back into command mode. i insert text before cursor, until <Esc> hit *
I

insert text at beginning of current line, until <Esc> hit append text after cursor, until <Esc> hit append text to end of current line, until <Esc> hit open and put text in a new line below current line, until <Esc> hit open and put text in a new line above current line, until <Esc> hit

a A

* *

o O

Deleting Text

The following commands allow you to delete text. *x Nx dw dNw delete single character under cursor delete N characters, starting with character under cursor delete the single word beginning with character under cursor delete N words beginning with character under cursor; e.g., d5w deletes 5 words delete the remainder of the line, starting with current cursor position delete entire current line delete N lines, beginning with the current line; e.g., 5dd deletes 5 lines

* dd Ndd or dNd

Cutting and Pasting Text The following commands allow you to copy and paste text. yy Nyy or P copy (yank, cut) the current line into the buffer copy (yank, cut) the next N lines, including the current line, into the buffer put (paste) the line(s) in the buffer into the text after the current line

Other Commands

Searching Text

A common occurrence in text editing is to replace one word or phase by another. To locate instances of particular sets of characters (or strings), use the following commands. /string search forward for occurrence of string in text
?string n N

search backward for occurrence of string in text Move to next occurrence of search string Move to next occurrence of search string in opposite direction

Determining Line Numbers

Being able to determine the line number of the current line or the total number of lines in the file being edited is sometimes useful. :.= Returns line number of current line at bottom of screen
:=

Returns the total number of lines at bottom of screen provides the current line number, along with the total number of lines, in the file at the bottom of the screen

^g

Saving and Reading FilesThese commands permit you to input and output files other than the named file with which you are currently working.

read file named filename and insert after current line :r filename<Return> :w<Return> :w newfile<Return> :12,35w smallfile<Return> (the line with cursor) write current contents to file named in original vi call write current contents to a new file named newfile write the contents of the lines numbered 12 through 35 to a new file named smallfile write current contents over a pre-existing file named :w! prevfile<Return> prevfile

Ex .No: 4 CALCULATING THE GROSS SALARY OF AN EMPLOYEE

AIM:

To write a simple script to calculate the gross salary of an employee.

ALGORITHM:

STEP 1 : Start

STEP 2 : Get the basic salary from the user

STEP 3 : Calculate the Da , Hra, and gross with the needed formulas namely da=`expr $b \* 10 / 100` hra=`expr $b \* 20 / 100`

gross=`expr $b + $da + $hra`

STEP 4 : Print the gross salary by use of echo command

STEP 5 : Stop

PROGRAM

echo Calculating the gross salary of an employee

echo Enter the Basic salary

read b

da=`expr $b \* 10 / 100` hra=`expr $b \* 20 / 100` gross=`expr $b + $da + $hra` echo Gross Salary=$gross`

OUTPUT

Calculating the gross salary of an employee

Enter the Basic salary

10000

Gross Salary= 13000

Result: Thus the program to find gross salary of an employee is created and executed successfully.

Ex .No: 5

FINDING THE AREA OF A CIRCLE

AIM:

To write a simple script to find the area of a circle.

ALGORITHM:

STEP 1 : Start

STEP 2 : Get the radius from the user

STEP 3 : Read the radius.

STEP 4 : Calculate the area by using the formula 3.142857 \* $radius \* $radius | bc

STEP 5 : Stop

PROGRAM

echo FINDING THE AREA OF THE CIRCLE

echo "Enter the radius of the circle" read radius echo "The Area of the circle is"

echo 3.142857 \* $radius \* $radius | bc

OUTPUT

FINDING THE AREA OF THE CIRCLE

Enter radius of the circle

The Area of the circle is 78.571425

Result:

Thus the program to find radius of circle was created and executed successfully.

Ex .No:6

TWO-WAY BRANCHING

AIM:

To implement the concept of two-way branching using if statement.

ALGORITHM:

STEP1 :Start

STEP2 :Declare the variables and its access

STEP3 :If a is greater than b then print A is Big, else

STEP4 :Print B is Big

STEP5 :Stop

Program

echo Concept of two-way branching using if statement

echo Finding the Biggest of two numbers

echo Enter the two Numbers

read a b

if [ $a gt $b ]

then else fi echo A is Big

echo B is Big

OUTPUT

Concept of two-way branching using if statement Finding the Biggest of two numbers

Enter the two Numbers

12 45

B is Big

Result:

Thus the program to find biggest of given two numbers by using if statement was created and executed successfully.

Ex .No: 7

MULTI-WAY BRANCHING USING IF-ELIF STATEMENT

AIM:

To implement the concept of multi-way branching using if-elif statement.

ALGORITHM:

STEP 1 : Start

STEP 2 : Declare the variables and its access

STEP 3 : If a is greater than b and a is greater than c, then print A is Big, else

STEP 4 : If b is greater than c then print B is Big, else

STEP 5 : Print C is Big

STEP6 : Stop

Program

echo Concept of multi-way branching using if-elif statement echo Finding the Biggest of three numbers echo Enter the three Numbers echo a read a echo b= read b echo c= read c if [ $a gt $b ] then if [ $a gt $c ] then echo A is Big else echo C is Big fi elif [ $b gt $c ] then echo B is Big else echo C is Big fi

OUTPUT

Concept of multi-way branching using if-elif statement Finding the Biggest of three numbers Enter the three Numbers a=14 b=23 c=10 B is Big

Result:

Thus the program to find highest number among given three numbers by using if-elif statement was developed and executed successfully.

Ex .No: 8

MULTI-WAY BRANCHING USING CASE STATEMENT

AIM:

To implement the concept of multi-way branching using case statement.

ALGORITHM:

STEP 1 : Start

STEP 2 : Initialize the number of choices

STEP 3 : If the choice is present corresponding result will be displayed otherwise

STEP 4 : The statement of the default will be displayed

STEP 5 : Stop

Program

echo Concept of multi-way branching using case statement

clear

echo 1. To know Your current Directory

echo 2.Todays Date echo 3.List of Users echo Enter your choice read choice case $choice in

1) pwd;;

2) 2)date;;

3) who;;

*) echo Only give inputs from 1 to 3

esac

OUTPUT Concept of multi-way branching using case statement 1. To know Your current Directory 2.Todays Date 3.List of Users Enter your choice 2 wed march 18 08:25:20 IST 2009

Result: Thus the program for multiway branching by using case statement was created and executed successfully.

Ex .No: 9

PROGRAM TO PRINT N NATURAL NUMBERS

AIM:

To write a program to print n Natural numbers

ALGORITHM:

STEP 1 : Start

STEP 2 : Get a number from the user to print n Natural numbers

STEP 3 : Read the number

STEP 4 : Start the while loop and write the statements of the loop within do and done

STEP 5 : Echo the value of i and increment the value of i

STEP 6 : End the loop

STEP 7 : Stop

PROGRAM

echo print n natural numbers

echo Enter a number to get N natural numbers

read n

echo The first $n natural numbers are

i=1

while [ $i le $n ]

do

echo $i

i=`expr $i + 1` done

OUTPUT print n natural numbers

Enter a number to get N natural numbers

The first 5 natural numbers are

1 2 3 4 5

Result:

Thus the program to print n natural numbers was created by using while loop

and executed successfully.

Ex .No: 10

PROGRAM TO PRINT FIRST N FIBONACCI SERIES.

AIM:

To write a program to print first N Fibonacci Series.

ALGORITHM:

STEP 1 : Start

STEP 2 : Get the number of terms of Fibonacci Series the user needs. STEP 3 : Read the number

STEP 4 : Initialize f1=-1,f2=1 and i=1

STEP 5 :Start the while loop and write the statements of the loop within do and done

STEP 6 : calculate the value of the Fibonacci Series with the needed formulas

STEP 7 : End the loop

STEP 8 : Stop

PROGRAM

echo Enter the number of terms read n f1=1 f2=1 i=1 echo The Fibonacci series upto $n terms is while [ $i -le $n ] do

f3=`expr $f1 + $f2`

echo $f3 f1=$f2 f2=$f3 i=`expr $i + 1`

done

OUTPUT Enter the number of terms 10 The Fibonacci series upto 10 terms is 0 1 1 2

3 5 8 13 21 34

Result: Thus the program to display Fibonacci series up to given terms was created by using while loop and executed successfully.

Ex .No: 11 PRINT THE MULTIPLICATION TABLE USING UNTIL LOOP

AIM:

To write a program to print the multiplication table using until loop.

ALGORITHM:

STEP 1 : Start

STEP 2 : Get the number from the user to print its multiplication table.

STEP 3 : Read the number

STEP 4 :Start the until loop

STEP 5 : write the necessity statements within do and done

STEP 6 : End the loop

STEP 7 : print the multiplication table .

STEP 8 :Stop

PROGRAM

echo Enter a number

read n i=1 echo The multiplication table of $n is

until [ $i gt 10 ]

do

pro=`expr $i \* $n` echo $n x $i=$pro i=`expr $i + 1`

done

OUTPUT

Enter a number 5 The multiplication table of 5 is 5 x 1=5 5 x 2=10 5 x 3=15 5 x 4=20 5 x 5=25 5 x 6=30 5 x 7=35 5 x 8=40 5 x 9=45 5 x 10=50

Result: Thus the program for multiplication table was developed and executed successfully by until loop.

Ex .No: 12

PROGRAM TO PRINT THE SUM USING FOR LOOP.

AIM:

To write a program to print the sum using for loop.

ALGORITHM:

STEP 1 : Start

STEP 2 : Initialize the variable i.e sum=0

STEP 3 : Start the for loop

STEP 4 : calculate the sum by using the formula sum=`expr $sum + $i` for all the elements in the for loop list STEP 5 : End the loop.

STEP 6 : Print the value of the sum

STEP 7 : Stop

Program

echo Program implementing For Loop

sum=0 for i in 1 2 3 4 10 do

sum=`expr $sum + $i` done

echo The sum is $sum

OUTPUT

Program implementing For Loop

The sum is 20

Result:

Thus the program to find the sum of the numbers by using for loop was developed and executed successfully.

Ex .No: 13

PROGRAM TO CALCULATE THE FACTORIAL

AIM:

To write a program to calculate the factorial.

ALGORITHM:

STEP 1 : Start

STEP 2 : Get the number from the user

STEP 3 : Read the number

STEP 4 :Initialize the variable i.e f=1

STEP 5 : Start the for loop STEP 6 : calculate the factorial STEP 7 : End the loop. STEP 8 : print the factorial of the given number. STEP 9 : Stop

Program

echo "Factorial Program" echo "Enter the number" read a f=1

for (( i = 1; i <= ${a}; i++ ))

do

f=`expr $f \* $i` done

echo "The factorial of $a is $f"

OUTPUT

Factorial Program

Enter the number 5

The factorial of 5 is 120

Result:

Thus the program to find factorial of given number was created and executed successfully by using for loop.

EX NO: 14 PROGRAM FOR THE ILLUSTARTION OF POINTER EXPRESSIONS

AIM: To develop the program for the illustration of pointers expressions.

ALGORITHM:

1.

Open the UNIX operating system.

2. Edit the command vi filename in the home directory or in the directory created by user. VI stands for visual, a full screen editor, indicates most powerful editor. File name indicates program name 3. Now enter required header files and open main ( )

function.

4. data type.

Inside main ( ) function declare required variables, pointers of integer

5. Give the value for the variables at compile or runtime. After given values, assign the address of variables to the pointers. 6. pointers. 7. Show the value of the variables and its stored address by Evaluate more than one expression by pointers and show the result.

8. To save the program, press Escape button in the keyboard and enter :wq command. 9. 10. 11. To compile the program edit the command cc filename.c If no compile time error, to run the program edit the command ./a. out. If no run time error, output of the program is displayed.

Program

#include<stdio.h> main( ) { int a,b,*p1,*p2; printf(" ENTER THE VALUE FOR A,B : "); scanf("%d%d",&a,&b); p1=&a; p2=&b; printf(" \n %d is stored in the address %u ",*p1,p1); printf(" \n %d is stored in the address %u ",*p2,p2); printf(" \n (*p1+*p2)*(a -*p2) = %d", (*p1+*p2)*(a-*p2)); printf(" \n (*p1+*p2)/(*p1-b) = %d",(*p1+*p2)/(*p1-b)); printf(" \n *p1*p2/a+b = %d",*p1*p2/a+b); printf("\n"); }

OUTPUT

Enter the value for a,b: 12

12 is stored in the address 3218466676

8 is stored in the address 3218466672 (*p1+*p2)*(a-*p2) = 80 (*p1+*p2)/(*p1-b) = 5 *p1**p2/a+b = 16

RESULT:

Thus the program for the illustration of pointer expressions is developed, executed successfully

EX NO: 15 PROGRAM FOR DYNAMIC MEMORY ALLOCATION AND REALLOCATION

AIM:

To develop the program for dynamic memory allocation to store information and the reallocating dynamically the same memory to store more information .

ALGORITHM:

1. Open the UNIX operating system. 2. Edit the command vi filename in the home directory or in the directory created by user. VI stands for visual, a full screen editor, indicates most powerful editor. File name indicates program name. 3. Now enter required header files and open main ( ) function. 4. Inside main ( ) function declare required variables, pointers and allocate a block of memory dynamically by using malloc ( ) function. 5. Check whether dynamically a block of memory allocated or not. 6. If allocated, store the information and display the information. 7. Reallocate the same memory to store more information than before by using realloc ( ) function. 8. Check whether reallocation of same memory dynamically done

or not. 9. If allocated, store the new information and display it. 10. If no longer needed the stored information, release by using free ( ) function. 11. To save the progra m, press Escape button in the keyboa rd and enter : wq comma nd. 12. T o c o m p i l e t h e p r o g r a m

edit the command cc filename.c 13. If no compile time error, to run the program edit the command ./a. out.

14. If no run time error, output of the program is displayed .

Program

#include<stdio.h> #include<stdlib.h> #include<string.h> main( ) { char *buffer; buffer=(char *)malloc(10*sizeof(char)); if(buffer==0) { printf(" Dynamically memory not allocated . . . \n"); exit(1); } else printf(" Dynamically memory allocated . . . \n"); strcpy(buffer,"Chennai"); printf(" Buffer contains : %s \n",buffer); buffer=realloc(buffer,50); if(buffer==0) { printf(" Reallocation failed . . . \n"); exit(1); } printf(" Buffer size modified . . .\n"); printf(" Buffer still contains: %s \n",buffer); strcpy(buffer,"Chennai is the capital of the Tamilnadu state "); printf(" Buffer now contains: %s \n",buffer); printf(" Releasing dynamically allocated memory . . . . ");

free(buffer); }

. I OUTPUT

Dynamically Memory Allocated

Buffer contains : chennai Buffer size modified . . . Buffer still contains: chennai Buffer now contains: chennai is the capital of Tamilnadu state Releasing dynamically allocated memory . . .

RESULT:

Thus the program for dynamically memory allocation, reallocation and releasing the allocated memory dynamically is developed and executed successfully.

EX NO: 16 Program to create file, to store information in the file and to show the information in the file by using file handling functions.

AIM: To develop the program to create file, to store information in the file and to show the information in the file by using file handling functions.

ALGORITHM: 1. Open the UNIX operating system. 2. Edit the command vi filename in the home directory or in the directory created by user. VI stands for visual, a full screen editor, indicates most powerful editor. File name indicates program name. 3. Now enter required header files and open main ( ) function. 4. Inside main ( ) function declare required variables, file pointer. Open the file with write mode and assign to the file pointer. 5. Enter number of students information to store. 6. Through for( ) loop, read the one by one student information by using stdin keyword, represents the keyboard and write to the given file by file pointer. 7. Close the file using fclose ( ) function with file pointer as argument. 8. Again open the file with read mode and assign to the file pointer. 9. Again through same for( ) loop, read one by one student information from the file by file pointer and write to the screen by using stdout keyword, represents screen. 10. For reading use fscanf ( ) function and for writing fprintf ( ) function.

11. Close the file using fclose ( ) function with file pointer as argument. 12. To save the program, press Escape button in the keyboard and enter :wq command. 13. To compile the program edit the command cc filename.c 14. If no compile time error, to run the program edit the command ./a. out.

15. If no run time error, output of the program is displayed.

Program

#include<stdio.h> main( ) { FILE *fp; char studname[15]; int n, i,em,tm,mm,sm.scm,total; float avg; fp=fopen("studentdetails","w"); printf(" ENTER NUMBER OF STUDENTS : scanf("%d",&n); printf("ENTER STUDENT NAMES AND FOLLOWING SUBJECT MARKS . \n \n"); printf("ENGLISH TAMIL MATHS SCIENCE SOCIALSCIENCE \n \n"); ");

for(i=1;i<=n;i++) { printf(" %d: STUDENT DETAILS \n ",i); fscanf(stdin,"%s%d%d%d%d%d",studname,&em,&tm,&mm,&sm,&scm); fprintf(fp,"%s%d%d%d%d%d",studname,em,tm,mm,sm,scm); printf("\n"); } fclose(fp); fp=fopen("studentdetails","r"); printf(" STUDENT DETAILS STORED IN THE FILE . . . \n \n"); for(i=1;i<=n;i++) { fscanf(fp,"%s%d%d%d%d%d",studname,&em,&tm,&mm,&sm,&scm); total=em+tm+mm+sm+scm; avg=total/5;

fprintf(stdout,"%s\n%d\n%d\n%d\n%d\n%d\n%d\n %f",studname,em,tm,mm,sm,scm,total,avg); printf("\n"); } fclose(fp); }

OUTPUT

ENTER NUMBER OF STUDENTS: 2

ENTER STUDENT NAMES AND FOLLOWING SUBJECT MARKS . .

ENGLISH TAMIL MATHS SCIENCE SOCIALSCIENCE

1:

STUDENT DETAILS

Gnanasekar.P 48 78 90 76 56

2:

STUDENT DETAILS

Visu.L 70 89 76 65 54

STUDENT DETAILS STORED IN THE FILE

...

Gnanasekar.P 48 78 90 76 56 348 69.6

Visu.L 70 89 76 65 54 354 70.8

RESULT:

Thus the program for file handling by using file handling functions is

developed and executed successfully.

You might also like