addition of two · web view15 factorial of a number. 16 reverse of a number. 17 sum of digits...

120
Department of Electronics & Communication Engineering Computer Practice Laboratory-II Record Name: …………………………………….………. Year: ………… Degree & Branch: ……………………………..... Semester: ….. University Register No. Class Roll No. Certified that this is a Bonafide Record of the work done by the student of the …………………………..………… laboratory during the year 2013 to 2014. Signature of the Signature of the Lab in-charge HOD Submitted to the Anna University practical examination held on ……………. at Chettinad College of Engineering & Technology.

Upload: lebao

Post on 15-Mar-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Department of Electronics & Communication Engineering

Computer Practice Laboratory-II Record

Name: …………………………………….………. Year: …………

Degree & Branch: ……………………………..... Semester: …..

University Register No.

Class Roll No.

Certified that this is a Bonafide Record of the work done by the student of the …………………………..………… laboratory during the year 2013 to 2014.

Signature of the Signature of theLab in-charge HOD

Submitted to the Anna University practical examination held on ……………. at Chettinad College of Engineering & Technology.

Internal Examiner External Examiner

Ex. No Date Name of the Experiment Page No Marks Awarded

Faculty Sign

1 Study of Unix OS.

2 Basic Unix Commands.

3Study of vi editor and Basic

Shell Commands.

Shell Programming

4Sum and average of 4 integers.

5a) Simple interest.

b) Compound interest.

6 Swapping of two numbers.

7 Computing the power of x.

8Check whether given year is

leap year or not.

9Check whether the number is

even or odd.

10Check whether the number is

positive or negative.

Ex. No Date Name of the Experiment Page No Marks Awarded

Faculty Sign

Table of Contents

11Find the quotient and remainder

of two numbers.

12Check whether a number is

divisible by 5.

13Check the given number is

prime or not.

14GCD of two numbers.

15Factorial of a number.

16 Reverse of a number.

17Sum of digits of a given

number.

18 Greatest among three numbers.

19 First N even numbers.

20 First N odd numbers.

21 Factorial of first N numbers.

22 First N prime numbers.

C PROGRAMS

Ex.No Date Name of the Experiment Page Marks Faculty

NoAwarde

dSign

23Performing Matrix Addition, Multiplication, Transpose.

24 Greatest of N numbers using arrays.

25Sort N numbers using pointers

and functions.

26Print array elements in reverse

order.

27Converting lower case

characters to upper case equivalents.

28Copy the contents of one file

into another.

29Print the number of vowels in

given paragraph.

Ex.No Name of the experimentPage No

Marks Awarde

d

Faculty Sign

30 Computing the roots of a

quadratic equation.

31Sort N names alphabetically using pointers and functions.

Performance 25

Record 15

Viva voce 10

Total 50

Ex.No: 1 STUDY OF UNIX OSDate:

INTRODUCTION

An operating system is software that acts as an interface between the user and the

computer hardware. It is considered as the brain of the computer. It controls and co-ordinates the

internal activities of the computer and provides user interface.

The computer system is built with the following general components

i) Hardware

ii) Application Software

iii) Operating System

(i)Hardware: This includes the physical components such as CPU, Keyboard, Hard disk

and Printer.

(ii) Application Software: These are the programs that are used to accomplish specific

tasks.

(iii)Operating System: It is the component or the set of programs to manage and control the

hardware as well as co-ordinate the applications. Each system must have at least

have the hardware and the OS.

Functions of an Operating System

Command interpretation: The CPU can’t understand the commands keyed in by a user.

It is the function of the OS to make it understand.

Peripheral Interfaces: The OS also has to take care of the devices attached to the

system. The OS oversees communication between these devices and the CPU.

Memory management: The OS handles the extremely important job of allocating

memory for various processes running on the system.

Process management: This is required if several programs must run concurrently. CPU

time would then have to be rationed out by the OS to ensure that no programs get more

than its fair share of the processor time.

Services of an OS:

1. Process Management

2. File Management

3. I/O Management

4. Scheduling

5. Security Management

UNIX OPERARTING SYSTEM:

In the mid-1960s, AT &T Bell Laboratories developed a new OS called Multics. Multics

was intended to supply large scale computing services as a utility; much like electrical power. In

1969 Ken Thompson, Dennis Ritchie and others developed and simulated an initial design for a

file system that later evolved into the UNIX file system. The whole UNIX was rewritten in „C‟ language in 1973.Today, UNIX is a giant OS and is much powerful than most of its counter parts.

UNIX operating System is like a layer between the hardware and the applications that run

on the computer .It has functions that run on the computer. It has functions that manage the

executing applications.

UNIX system is an OS, which includes the traditional system components. UNIX

system includes a set of libraries and a set of applications.

KERNEL is the heart of UNIX OS that manages the hardware and the executing

process. The UNIX system views each device as a file called a device file. It implements

security controls to protect the safety and privacy of information. The Unix System allocates

resources including use of the CPU and mediates accesses to the hardware.

Application portability is the ability of a single application to be executed on various

types of computer hardware without being modified. This is one of the important advantages of

UNIX.

FEATURES OF UNIX:

1. Multitasking

Multitasking is the capability of the OS to perform various tasks simultaneously. i.e. A single

user can run multiple programs concurrently.

2. Multiuser Capability

Multiuser capability allows several users to use the same computer to perform their tasks.

Several terminals are connected to a single powerful computer and each user can work with

their terminals.

3. Security

Unix allows sharing of data. Every user must have a Login name and a password. So, accessing

another user’s data is impossible without permission.

4. Portability

Unix is a portable because it is written in high level languages so it can run on different

computers.

5. Communication

Unix supports communication between different terminals connected to the Unix server and

also between the users of one computer to the users of another computer located elsewhere

in the network.

6. Programming Facility

UNIX is highly programmable; the UNIX shell programming language has the

conditional statements and control structures and variables.

UNIX ARCHITECTURE

The functioning of Unix OS is handled in 3 ways. The closest layer is the hardware,

which provides the services to the OS. The Unix OS referred to Unix as the kernel, is the heart

of the Unix. The other layer is the shell, which acts as the mediator that translates the

commands given by the application programs.

Kernel

It is the core of the OS. It controls all the tasks and carries out all the functions of an

OS such as memory and file management etc., and it keep track of the programs that are

executing. It also handles the information exchange between the terminals such as tape drives

and printers etc.,

Functions of Kernel

1. Allocating and deallocating memory to each and every process.

2. Receiving instructions from the shell and carrying them out.

3. Managing files that held on various storage devices.

4. Scheduling, Coordinating and assigning various input/output devices simultaneously.

5. Enforcing security measures.

6. Providing Network services.

7. Providing Utility services.

8. Coordinating each and every process with signal handling.

9. Providing administrative functions or utilities.

Shell

It is the command interpreter of the OS. The commands given from the user are

moved to the shell. The shell analyses and interprets these commands into the machine

understandable form. The commands can be either typed in through the command line or

contained in a file called shell script. Hence, Shell acts as an interface between the user

and the kernel.

UNIX has a variety of shells, they are:

(i) Bourne Shell: It is developed by Steve Bourne and it is the most popular shell and widely

used. This shell comes bundled with almost every UNIX system.

(ii) Korn shell: It is developed by David G.Korn. This is superset of Bourne shell and it has

more capabilities.

(iii) C Shell: It is developed by Bil Joy. It is similar to C Programming language.

Features of Shell

1. All communications between user and Kernel takes place through the shell.

2. It allows the tasks to run on background.

3. It also enables us to construct scripts like a programming language.

4. A group of files can be executed using a single command.

Starting a UNIX session – Logging In

A user of UNIX based system works as a user terminal. After the boot procedure is

completed, that is the operating system is loaded in memory, the following message appears at

each user terminal:

Logging

Each user has an identification called the user name is the login name which has to be

entered when the login: message appears. The user is then asked to enter the password. UNIX

keeps track of all the UNIX user names and the information about identity in a special file. If the

login name entered does not match with any of the user names it displays the login message

again. This ensures that, only authorized people use the system. When a valid user name is

entered at the terminal the dollar symbol is displayed on the screen this is the UNIX prompt.

Ending a UNIX session –Logging Out

Once a user has logged into the system the users’ works session continues until the user

instructs the shell to terminate the session. This is done by pressing the ctrl and d keys together or

typing exit at the dollar prompt. Then the systems display the login: Prompt on the screen.

Ex.No: 2 BASIC UNIX COMMANDSDate:

1. cat command

This command is used to create a file in unix.

Syntax:

$ cat >filename

This command is also used for displaying contents in a file.

Syntax:

$ cat filename

2. ls command

It displays the list of files in the current working directory.

Syntax:

$ ls

3. rm command

This command is used to remove an existing file .

Syntax:

$ rm filename

4. wc commad

This command is used to count the number of lines characters & words in a file.

Syntax:

$ wc filename

5. pwd command

This command is used to know the current working directory.

Syntax:

$ pwd

6. date command

This command is used to display the current date ,year ,month ,day &time.

Syntax:

$ date

7. echo command

This command is used to print the message on the display .

Syntax:

$ echo text

8. cal command

This command is used to display the specified month or year calendar.

Syntax:

$ cal month

9. who command

This command is used to display the date & terminal type of all the users who are

currently logged into a system

Syntax:

$ who

10. who am I command

This command is used to display the logging details of the user who worked in

that terminal.

Syntax:

$ who am i

11. bc command

This command is used to perform mathematical calculations.

Syntax:

$ bc operation

12. tputclear command

This command is used to clear the screen & place the $ prompt at the top most of

the screen.

Syntax:

$ tput clear

13. tty command

This command is used to display the device type of the terminal.

Syntax:

$ tty

14. mkdir command

This command is used to create a new directory.

Syntax:

$ mkdir filename

15. man command

If we get stuck on something, and cannot find an expert to help, we can print

any manual page on our terminal with the command ’man’ command-name.

Syntax:

$ man who

16. head and tail command

The head command is used to display the initial part of a text file. This can be

thought of aa a complement command to the tail command. which displays the last

part of a text file. By default head command displays first 10 lines of a file and tail

command the last lines. $ head [-count] filename.

Syntax:

$ head -4 friends

jude

jacob

raju

prem

will display the first four lines of a file called friends.

$ tail [+|- number] filename

Syntax:

$ tail +5 friend

will display from the 5th line from the beginning of the file.

$ tail -5 friend

will display from the 5th line from the end of the file.

17. cd command

It is used to change the current directory to the other directory specified.

Syntax:

$ cd jac

18. rmdir command

It is used to remove the directory. It requires the directory to be empty.

Syntax:

$ rmdir directoryname

19. cp command

It is used to create duplicate copies of ordinary files.

Syntax:

$ cp source destination

20. ln – link command

It is used to establish an additional filename for the same ordinary file.

Syntax:

$ ln ordinary_filename additional_filename

Ex:

$ ln red rose

Advantage of this command is that several users can have access to a common data

file.Any modification in the additional file or ordinary file reflects in both of them.

21. mv command

It is used to rename and move ordinary and directory files. To do this we need

both execute and write permissions.

Syntax:

$mv source destination

Ex:

Renaming, $ mv aaa bbb

To move the contents of the file old to the new, the syntax is: Ex: $ mv old

new

22. To concatenate several files and display:

The above cat command will concatenate the two files (file1.txt and file2.txt)

and it will display the output in the screen.

Syntax:

cat file1.txt file2.txt

Some times the output may not fit the monitor screen. In such situation you

can print those files in a new file or display the file using less

command.

Syntax:

cat file1.txt file2.txt | less

To concatenate several files and to transfer the output to another file.

cat file1.txt file2.txt > file3.txt

In the above example the output is redirected to new file file3.txt. The cat

command will create new file file3.txt and store the concatenated output into

file3.txt.

23. To view the files page by page

More command is used to view one page of a file at a time.

Syntax:

cat filename | more

Or

Less command is also used to view the file page by page.

Syntax:

cat filename | less

24. To list files and directories, recursively on a single line

ls -R gives a recursive listing, including the contents of all subdirectories and

their subdirectories and so on.

25.To append more than one file

To append data into the same file use append operator >> to write into the file,

else the file will be overwritten (i.e., all of its contents will be erased).

Syntax:

cat >> file1.txt

26.To change the password

The passwd command changes the password for the user.

Syntax:

passwd tech

27. To view the commands which was executed

History command is used to view the commands which were executed.

Syntax :

History

28. List all filenames which has dot at the end

Syntax:

find ./ -type f -name '*[.].*'

29. List all filenames which has an extension

Syntax:

find ./ -type f -name '*.*'

30. Display all files, sub directories and files in subdirectories including their

sizes

Syntax:

du –sk * | sort -n

31. Store the output of date command in a file called date. out

Syntax:

date >> date.out

32. To display the file attributes

Syntax:

stat filename

33. Change the mode of the file, where the changed file should possess all the

permission

Syntax:

chmod 777

34. List all files in current directory whose second character is a digit

Syntax:

find ./ -type f -name ' ?[0-9]*'

35. Sort the files in alphabetical order

Syntax:

sort filename

36. Change the file to read only mode

Syntax:

chmod 0444

Ex.No:3 STUDY OF VI EDITOR AND BASIC SHELL

COMMANDSDate:

An editor is program that allows to see a portion of a file on the

screen and to modify characters and lines by simply typing at the cursor

position. There are number of editors that may be included with the UNIX

system, including ED, EX, VI and EMACS.

The vi Editor

VI - vi stands for visual.

VI is a full screen editor and is widely acknowledged as one of the most

powerful editors available .It is a full screen editor that allows the user to

view and edit the entire document at the same time.

The VI editor was written in the University of California at

Berkeley by Bill Joy, who is one of the co-founder of Sun

Microsystems.

Features of VI Editor

1. It is very easy to learn and has more powerful and exciting features.

2. It works in great speed.

3. VI is case sensitive.

4. VI has powerful undo features than most other word processors, but

it has no formatting features.

Modes of VI Editor

VI editor works in three modes of operations specified below:

Command Mode: In this mode, all the keys pressed by the user are

interpreted to be editor commands. No text is displayed on the screen, even

if corresponding key is pressed on keyboard.

Insert Mode: This mode permits to insert new text, editing and replacement

of existing text. Once VI editor is in the insert mode, letters typed in the

keyboard are echoed on the screen.

The ex or escape colon ( : ) Mode: This mode allow us to give commands

at the command line. The bottom line of the VI editor is called the command

line.vi uses the command line to display messages and commands.

Starting with VI editor

Syntax: vi filename

Moving the cursor

The cursor movement commands are:

Command Action

H or backspace Left one character

l or spacebar Right one character

K or - Up one line

J or + Down one line

I Moves forward a word

#b Moves back a word

#e Moves to the last character in the word

F[character] Moves right to the specified character in a

line

T[character] Moves right and places it one character

before the specified

character

0 or ^ Moves to the beginning of the file

#$ Moves to the end of the file

L Moves to the last line of the file

G Moves to the specified line number

Editing the file

Open the file using $ vi filename

To add text at the end of the file, position the cursor at the last

character of the file.

Switch from command mode to text input mode by pressing „a‟.

Here „a‟ stands for append.

Inserting text in the middle of the file is possible by pressing

„i‟. The editor accepts and inserts the typed character until Esc

key is pressed.

Deleting Text

For deleting a character, move the cursor to the character, press „x‟.

The character

will disappear.

Command Purpose

X Deletes one character

Nx Deletes n number of characters

#x Deletes on character at the cursor position

#X Deletes on the character before the cursor position

D$ or d Deletes a line from the cursor position to the end of

the line

D0 Deletes from the cursor position to the starting of the

line

#dd Deletes the current line where the cursor is positioned

#dw Deletes the word from the cursor position to the end

of the word

Starting vi

Command Description

vi file start at line 1 of file

vi +n file start at line n of file

vi + file start at last line of file

Saving files and quitting vi

Command Description

:w save (write out) the file being edited

:w file save as file

:w! file save as an existing file

:q quit vi

:wq save the file and quit vi

:x save the file if it has changed and quit vi

:q! quit vi without saving changes

Moving the cursor

Keys pressed Effect

h left one character

l or <Space> right one character

k up one line

j or <Enter> down one line

b left one word

w right one word

( start of sentence

) end of sentence

1G top of file

nG line n

G G end of file

<Ctrl>W first character of insertion

<Ctrl>U up ½ screen

<Ctrl>D down ½ screen

<Ctrl>B up one screen

<Ctrl>F down one screen

Inserting text

Keys pressed Text inserted

a after the cursor

A after last character on the line

i before the cursor

I before first character on the line

o open line below current line

O open line above current line

Searching for text

Search Finds

/and next occurrence of ``and'', for example, ``and'',

``stand'',``grand''

?and previous occurrence of ``and''

/^The next line that starts with ``The'', for example,

``The'',``Then'',

``There''

/end$ next line that ends with ``end''

/[bB]ox next occurrence of ``box'' or ``Box''

SHELL PROGRAMMING

The format for the various conditional statements and looping

statements and the relational operators used for those conditions are given

below.

if condition

if

c

o

n

di

ti

o

n

th

e

n

execute commands

fi

if – else condition

if

c

o

n

di

ti

o

n

th

e

n

execute commands

else

execute commands

fi

if – elif condition – multi way branching

if condition then

execute commands elif

condition

then

execute commands

else

execute commands

fi

Relational Operators

Operator Meaning

-eq Equal to

-ne Not equal to

-gt Greater than

-ge Greater than or equal to

-lt Less than

-le Less than or equal to

Case condition

case expression in

pattern1) execute commands ;;

pattern2) execute commands ;;

pattern3) execute commands ;;

……………..

esac while

looping

WHILE

While expression Do

execute commands

done

UNTIL

while’s complement

until [ condition ]

FOR looping

for variable in list

do

execute commands

done

SHELL PROGRAMMING

Ex.No:4 SUM AND AVERAGE OF 4 INTEGERS

Date:

Aim:

To write a shell program for finding the sum and average of 4 integers.

Algorithm:

1. Start the program.2. Read the four variables a, b, c, d.3. Calculate sum of a, b, c, d and store output in variable ‘sum’.4. Calculate average by sum/4.5. Print the sum and average of four numbers.6. Stop the program.

SUM AND AVERAGE OF 4 INTEGERS

echo “Enter four integers”read aread bread cread dsum=`expr $a + $b + $c + $d`avg=`expr $sum / 4`echo “Sum=$sum”echo “Average=$avg”

OUTPUT:

Enter four integers10203040Sum=100Average=25

Performance 25

Record 15

Viva voce 10

Total 50

Result: Thus shell program for finding sum and average of 4 integers has been executed successfully.

Ex.No: 5 SIMPLE INTEREST AND COMPOUND INTERESTDate:

Aim:

To write a shell program for computing simple interest and compound interest.

Algorithm:

1. Start the program.2. Read the variables p, n, r.3. Calculate the simple interest by using the formula pnr/100.4. Calculate the compound interest.5. Print the simple interest and compound interest.6. Stop the program.

SIMPLE INTEREST AND COMPOUND INTEREST

echo "Enter the Principal Amount"

read p

echo "Enter the Rate of Interest"

read r

echo "Enter the Number of Years"

read n

si=`expr $p \* $r \* $n`

si=`expr $si / 100`

echo "The Simple Interest is: Rs $si"

co=`expr 100 + $r`

co=`expr $co / 100`

i=2

ci=1

while [ $i -le $n ]

do

ci=`expr $ci \* $co`

i=`expr $i + 1`

done

ci=`expr $ci \* $p`

echo "The Compound Interest is: Rs $ci"

OUTPUT:

Enter the Principal Amount: 5000

Enter the Rate of Interest: 10

Enter the Number of Years: 1

The Simple Interest is: Rs 500

The Compound Interest is: Rs 5000

Result: Thus shell program for finding simple interest and compound interest has been executed successfully.

Performance 25

Record 15

Viva voce 10

Total 50

Ex.No:6 SWAPPING OF TWO NUMBERS

Date:

Aim:

To write a shell program for swapping of two numbers.

Algorithm:

1. Start the program.2. Read the variables a, b.3. Interchange the values of a and b using another temporary variable c as follows: c=a a=b b=c4. Print a and b.5. Stop the program.

SWAPPING OF TWO NUMBERS

echo “swapping using temporary variable”echo “enter a”read aecho “enter b”read bc=$aa=$bb=$cecho “after swapping”echo “$a”echo “$b”

OUTPUT:

Enter a10Enter b20After swapping2010

Performance 25

Record 15

Viva voce 10

Total 50

Result: Thus shell program for swapping two numbers has been executed successfully.

Ex.No: 7 COMPUTE THE POWER OF X

Date:

Aim:

To write a shell program for computing the power of x.

Algorithm:

1. Start the program.2. Read the number as n.3. Read the power as p.4. Compute power of a number by pr=pr*n.5. Print power.6. Stop the program.

COMPUTE THE POWER OF X

echo “enter a number”read necho “enter power”read pi=1pr=1while [ $i -le $p ]dopr=`expr $pr \* $n`i=`expr $i + 1`doneecho “result is:”echo “$pr”

OUTPUT:

Enter number5Enter power2Result is:25

Performance 25

Record 15

Viva voce 10

Total 50

Result: Thus shell program for computing the power of x has been executed successfully.

Ex.No:8 LEAP YEAR OR NOT

Date:

Aim:

To write a shell program for checking whether year is leap year or not.

Algorithm:

1. Start the program.2. Read the year.3. Check whether year%4, year%100, year%400 is zero.4. If zero then print year is leap year.5. Else print year is not leap year.6. Stop the program.

LEAP YEAR OR NOT

echo "Finding Leap Year"

echo "enter any year"

read y

a=`expr $y % 4`

b=`expr $y % 100`

c=`expr $y % 400`

if [ $a -eq 0 -a $b -ne 0 -o $c -eq 0 ]

then

echo "$y is a leap year "

else

echo "$y is not a leap year "

fi

OUTPUT:

Enter a year:2000Year is leap year

Result: Thus shell program for checking whether year is leap year or not has been executed successfully.

Ex.No: 9 GIVEN NUMBER IS ODD OR EVEN

Date:

Aim:

To write a shell program for checking whether given number is odd or even.

Algorithm:

1. Start the program.2. Read the number as num.3. Check whether num%2 is zero.4. If zero then print number is even.5. Else print number is odd.6. Stop the program.

Performance 25

Record 15

Viva voce 10

Total 50

GIVEN NUMBER IS ODD OR EVEN

echo “enter a number”read az=`expr $a % 2`if [ $z -eq 0 ]thenecho “$a is even”elseecho “$a is odd”fi

OUTPUT:

Enter a number5

5 is Odd

Result: Thus shell program for checking whether given number is odd or even has been executed successfully.

Ex.No:10 GIVEN NUMBER IS POSITIVE OR NEGATIVE

Date:

Aim:

To write a shell program for checking whether given number is positive or negative.

Algorithm:

1. Start the program.2. Read the number as num.3. If num<0 then print number is negative.4. Else if num>0 then print number is positive.5. Else print number is zero.6. Stop the program.

Performance 25

Record 15

Viva voce 10

Total 50

GIVEN NUMBER IS POSTIVE OR NEGATIVE

echo “enter a number”read nif [ $n -gt 0 ]thenecho “$n is positive”elif [ $n -lt 0 ]thenecho “$n is negative”elseecho “zero”fi

OUTPUT:

Enter a number

2

2 is Positive

Result: Thus shell program for checking whether the given number is positive or negative has been executed successfully.

Ex.No: 11 QUOTIENT AND REMAINDER OF TWO NUMBERS

Date:

Aim:

To write a shell program for finding the quotient and remainder of two numbers.

Algorithm:

1. Start the program.2. Read the number as n.3. Read the divisor as d.4. Calculate quotient as n/d.5. Calculate remainder as n%d.6. Print quotient and remainder.7. Stop the program.

Performance 25

Record 15

Viva voce 10

Total 50

QUOTIENT AND REMAINDER OF TWO NUMBERS

echo “enter a number”read necho “enter divisor”read dq=`expr $n / $d`r=`expr $n % $d`echo “quotient is:$q”echo “remainder is:$r”

OUTPUT:

Enter a number77

Enter divisor5

Quotient is: 15

Remainder is: 2

Result: Thus shell program for finding the quotient and remainder of two numbers has been executed successfully.

Ex.No: 12 NUMBER IS DIVISIBLE BY 5Date:

Aim:

To write a shell program for finding whether a number is divisible by 5

Algorithm:

1. Start the program.2. Read the number as num.3. If num%5 is zero then print number is divisible by 5.4. Else print number is not divisible by 5.5. Stop the program.

Performance 25

Record 15

Viva voce 10

Total 50

NUMBER IS DIVISIBLE BY 5

echo “enter a number”read na=`expr $n % 5`if [ $a -eq 0 ]thenecho “$n is divisible by 5”elseecho “$n is not divisible by 5”fi

OUTPUT:

Enter a number 75

75 is divisible by 5

Result: Thus shell program for finding whether a number is divisible by 5 or not has been executed successfully.

Ex.No: 13 NUMBER IS PRIME OR NOTDate:

Aim:

To write a shell program for checking whether the given number is prime or not.

Algorithm:

1. Start the program.2. Read the number as n.3. Initialize i=2.4. If i<n then compute a=n%0.5. If a=0 then print number is not a prime number.6. Else print number is a prime number.7. Stop the program.

Performance 25

Record 15

Viva voce 10

Total 50

NUMBER IS PRIME OR NOT

echo “enter a number”read ni=2while [ $i -lt $n ]doa=`expr $n % $i`if [ $a -eq 0 ]thenecho “$n is not a prime number “echo “since it is divisible by $i”exitfii=`expr $i + 1`doneecho “$n is a prime number”

OUTPUT:

Enter a number:33

33 is not a prime number

Since it is divisible by 3

Result: Thus shell program for checking whether the given number is prime number or not has been executed successfully.

Ex.No: 14 GCD OF TWO NUMBERS

Date:

Aim:

To write a shell program for finding the GCD of two numbers.

Algorithm:

1. Start the program.2. Read the two numbers a, b.3. Take another variable m and assign the value of a to m.4. If b<m then m=b.5. Compute x=a%m and y=b%m.6. If x=0 and y=0 then print GCD of two numbers a and b is m.7. Stop the program.

Performance 25

Record 15

Viva voce 10

Total 50

GCD OF TWO NUMBERS

echo “enter first number”read aecho "enter second number"read bm=$aif [ $b -lt $m ]thenm=$bfiwhile [ $m -ne 0 ]dox=`expr $a % $m`y=`expr $b % $m`if [ $x -eq 0 -a $y -eq 0 ]thenecho "gcd of $a and $b is: $m"breakfim=`expr $m - 1`done

OUTPUT:

Enter first number:54

Enter second number:24

Gcd of 54 and 24 is 6.

Result: Thus shell program for finding GCD of two numbers has been executed successfully.

Ex.No: 15 FACTORIAL OF A NUMBER

Date:

Aim:

To write a shell program for finding the factorial of the given number.

Algorithm:

1. Start the program.2. Read the number as n.3. For every iteration until n<1 compute f=f*n.4. Print the factorial of the given number as f.5. Stop the program.

Performance 25

Record 15

Viva voce 10

Total 50

FACTORIAL OF A NUMBER

echo “enter a positive number”read nf=1until [ $n -lt 1 ]dof=`expr $f \* $n`n=`expr $n - 1`doneecho “factorial of $n is $f”

OUTPUT:

Enter positive number

4

Factorial of 4 is24

Result: Thus shell program for finding factorial of the given number has been executed successfully.

Ex.No:16 REVERSE OF A NUMBERDate:

Aim:

To write a shell program for finding the reverse of a given number.

Algorithm:

1. Start the program.2. Read the number as n.3. For every iteration n> 0 compute rem=n%10 n=n/10 s=s*10 s=s+rem

Performance 25

Record 15

Viva voce 10

Total 50

4. Print the reverse of the given number as s.5. Stop the program.

REVERSE OF A NUMBER

echo “enter number”read ns=0while [ $n -gt 0 ]dorem=`expr $n % 10`n=`expr $n / 10`s=`expr $s \* 10`s=`expr $s + $rem`doneecho “Reverse is : $s”

OUTPUT:

Enter a number: 123

Reverse of 123 is:

321

Result: Thus shell program for finding reverse of a given number has been executed successfully.

Ex.No: 17 SUM OF DIGITS OF A GIVEN NUMBER

Date:

Aim:

To write a shell program for finding the sum of digits of a given number.

Algorithm:

1. Start the program.2. Read the number as n.3. Initialise sum=0

Performance 25

Record 15

Viva voce 10

Total 50

4. For every iteration n> 0 compute rem=n%10 n=n/10 sum=sum+rem5. Print the sum of digits of the given number as sum.6. Stop the program.

SUM OF DIGITS OF A GIVEN NUMBER

echo “enter the number”read nsum=0while [ $n -gt 0 ]dorem=`expr $n % 10`n=`expr $n / 10`sum=`expr $sum + $rem`doneecho “sum of digits of $n is:$sum”

OUTPUT:

Enter a number: 1234

Sum of digits of 1234 is:

10

Result: Thus shell program for finding the sum of digits of the given number has been executed successfully.

Ex.No:18 GREATEST AMONG THREE NUMBERSDate:

Aim:

To write a shell program for finding greatest among three numbers.

Algorithm:

1. Start the program.2. Read the three numbers a,b,c.3. Check whether a is greater than b and c.4. If yes then print a is big.

Performance 25

Record 15

Viva voce 10

Total 50

5. Else check whether b is greater than c.6. If yes then print b is big.7. Else print c is big.8. Stop the program.

GREATEST AMONG THREE NUMBERS

echo “enter a b c”read aread bread cif [ $a -gt $b ] && [ $a -gt $c ]thenecho “$a big”elif [ $b -gt $c ]thenecho “$b big”elseecho “$c big”fi

OUTPUT:

Enter a b c102030

C is big

Result: Thus shell program for finding greatest among three numbers has been executed successfully.

Ex.No: 19 FIRST N EVEN NUMBERSDate:

Aim:

To write a shell program for printing first N even numbers.

Algorithm:

1. Start the program.2. Read the number as n.3. Initialize i=2 and j=1.4. If yes then print a is big.

Performance 25

Record 15

Viva voce 10

Total 50

5. Up to j<n compute i=i+2 j=j+16. Print the first N even numbers.7. Stop the program.

FIRST N EVEN NUMBERS

echo "To Print the First N Even Numbers" echo "Enter the Number"read ni=2j=1echo “first $n even numbers are:”while [ $j -le $n ]doecho “$i”i=`expr $i + 2`j=`expr $j + 1`done

OUTPUT:

To Print the First N Even Numbers

Enter the Number5

First 5 even numbers are:246810

Result: Thus shell program for printing first N even numbers has been executed successfully.

Ex.No: 20 FIRST N ODD NUMBERSDate:

Aim:

To write a shell program for printing first N odd numbers.

Algorithm:

1. Start the program.2. Read the number as n.

Performance 25

Record 15

Viva voce 10

Total 50

3. Initialize i=1 and j=1.4. If yes then print a is big.5. up to j<n compute i=i+2 j=j+16. print the first N odd numbers.7. Stop the program.

FIRST N ODD NUMBERS

echo "To Print the First N Odd Numbers" echo "Enter the Number"read ni=1j=1echo “first $n odd numbers are:”while [ $j -le $n ]doecho “$i”i=`expr $i + 2`j=`expr $j + 1`done

OUTPUT:

To Print the First N Odd Numbers

Enter the Number5First 5 Odd numbers are:13579

Result: Thus shell program for printing first N odd numbers has been executed successfully.

Ex.No: 21 FACTORIAL OF FIRST N NUMBERSDate:

Aim:

To write a shell program for printing factorial of first n numbers.

Algorithm:

1. Start the program.

Performance 25

Record 15

Viva voce 10

Total 50

2. Read the number as num.3. Initialize i=1 and j=1.4. Upto j<num and i<j compute res=res*i i=i+16. Print the factorial.7. Stop the program.

FACTORIAL OF FIRST N NUMBERS

echo "Enter the Number"read numi=1j=1res=1if [ $j -eq 1 ]thenecho "The Factorial for the $j Number is="$jj=`expr $j + 1 `fiwhile [ $j -le $num ]dowhile [ $i -le $j ]

dores=`expr $res \* $i `i=`expr $i + 1 `doneecho "The Factorial for the $j Number is="$resres=1i=1j=`expr $j + 1 `done

OUTPUT:

Enter the Number4The Factorial for the 1 Number is=1

The Factorial for the 2 Number is=2

The Factorial for the 3 Number is=6

The Factorial for the 4 Number is=24

Result: Thus shell program for finding simple interest and compound interest has been executed successfully.

Ex.No: 22 FIRST N PRIME NUMBERSDate:

Aim:

To write a shell program for printing first n prime numbers.

Algorithm:

Performance 25

Record 15

Viva voce 10

Total 50

1. Start the program.2. Read the number as num1.3. Initialize i=2 and j=2 and k=0.4. Upto j<num1 num=j 5. Upto i<num check whether num%i is zero.6. If zero then k=1 and i=i+1.7. If k=0 then print number is prime.8. Stop the program.

FIRST N PRIME NUMBERS

echo "Enter a number: "read num1i=2j=2k=0while [ $j -lt $num1 ]donum=$jwhile [ $i -lt $num ]doif [ `expr $num % $i` -eq 0 ]thenk=1

fii=`expr $i + 1`doneif [ $k -eq 0 ]thenecho "$num is Prime Number"fij=`expr $j + 1`i=2k=0done

OUTPUT:

Enter a number10Prime numbers are:2357

Result: Thus shell program for printing first n prime numbers has been executed successfully.

Performance 25

Record 15

Viva voce 10

Total 50

C PROGRAMS

Ex.No:23 MATRIX ADDITIONS, MULTIPLICATION, TRANSPOSE

Date:

Aim:

To write a c program for addition, multiplication and transpose of given matrices.

Algorithm:

1. Start the program.2. If columns of A matrix are equal to rows of B matrix then matrices

can be added or multiplied else matrices cannot be added or multiplied.

3. To read 9 elements of two matrices.4. for(i=0;i<3;i++)

for(j=0;j<3;j++)c[i][j]=a[i][j]+b[i][j]

r[i][j]=0; for(k=0;k<3;k++) r[i][j]=r[i][j]+(p[i][j]*q[j][k]); q[i][j]=p[j][i];5. Print the matrix addition result as c[i][j].6. Print the matrix multiplication result as r[i][j].7. Print the matrix transpose result as q[i][j].8. Stop the program.

MATRIX ADDITION, MULTIPLICATION, TRANSPOSE

# include<stdio.h>#include<conio.h> void display(int [][3]);

void main() { int c; void func1(); void func2(); void func3(); clrscr(); printf("\n- : Matrix Manipulation Functions (for 3 X 3 Matrix) : -"); printf("\n-------------------------------------"); printf("\n Matrix Addition : 1"); printf("\n Matrix Multiplication : 2"); printf("\n Find Transpose Matrix : 3"); printf("\n Enter Your Choice : "); scanf("%d",&c); switch(c) { case 1: func1(); break; case 2: func2(); break; case 3: func3(); break; default: printf("\nInvalid Choice"); } getch(); }

void func1() { int x[3][3],y[3][3],z[3][3]; void getmatrix(int [][3]); void addition(int [][3],int [][3],int [][3]); clrscr(); printf(“\n enter 9 elements for matrix:1”); getmatrix(x); printf(“\n enter 9 elements for matrix:2”); getmatrix(y); addition(x,y,z); printf("\n - : Matrix 1: - \n"); display(x); printf("\n - : Matrix 2: - \n"); display(y); printf("\n - : Matrix Addition (Result): - \n"); display(z); }

void getmatrix(int t[][3]) { int i,j; for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("Enter element [%d][%d] : ",i,j); scanf("%d",&t[i][j]); } } }

void addition(int p[][3],int q[][3],int r[][3]) { int i,j; for(i=0;i<3;i++) { for(j=0;j<3;j++) r[i][j]=p[i][j]+q[i][j]; } }

void func2() { int x[3][3],y[3][3],z[3][3]; void getmatrix(int [][3]); void multiplication(int [][3],int [][3],int [][3]); clrscr(); printf(“\n enter 9 elements for matrix1:”); getmatrix(x); printf(“\n enter 9 elements for matrix2:”); getmatrix(y); multiplication(x,y,z); printf("\n - : Matrix 1: - \n"); display(x); printf("\n - : Matrix 2: - \n"); display(y); printf("\n - : Matrix Multiplication (Result): - \n"); display(z); }

void multiplication(int p[][3],int q[3][3],int r[3][3]) { int i,j,k; for(i=0;i<3;i++) { for(j=0;j<3;j++) { r[i][j]=0; for(k=0;k<3;k++) //condition i< total col of matrix2 r[i][j]=r[i][j]+(p[i][j]*q[j][k]); } }

}

void func3() { int x[3][3],y[3][3]; void getmatrix(int [][3]); void transpose(int [][3],int [][3]); clrscr();printf(“\n enter 9 elements for matrix: ”); getmatrix(x); transpose(x,y); printf("\n - : Matrix 1: - \n"); display(x); printf("\n - : Transpose Matrix : - \n"); display(y); }

void transpose(int p[][3],int q[][3]) { int i,j; for(i=0;i<3;i++) { for(j=0;j<3;j++) q[i][j]=p[j][i]; } } void display(int m[][3]) { int i,j; printf("\n\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) printf("%d ",m[i][j]); printf("\n"); } }

OUTPUT:

Matrix Manipulation Functions (for 3 * 3 matrix):-------------------------------------------------------------------

Matrix Addition : 1Matrix Multiplication : 2Matrix transpose : 3Enter your choice :3

Enter 9 elements for matrix:

Enter element [0][0]:1Enter element [0][1]:2Enter element [0][2]:3Enter element [1][0]:4Enter element [1][1]:5Enter element [1][2]:6Enter element [2][0]:7Enter element [2][1]:8Enter element [2][2]:9

Matrix is:

1 2 34 5 67 8 9

Transpose matrix is:

1 4 72 5 83 6 9

Result: Thus c program for addition, multiplication and transpose of the given matrices has been executed successfully.

Ex.No: 24 GREATEST OF N NUMBERS USING ARRAYSDate:

Performance 25

Record 15

Viva voce 10

Total 50

Aim:

To write a c program for finding greatest of n numbers using arrays.

Algorithm:

1. Start the program.2. Enter how many numbers.3. Read the numbers.4. Take maximum element as maximum(a,m).5. Comparing each element of the array with m.6. if a[i]>m then m=a[i].7. Print the greatest element of the array is m.8. Stop the program.

GREATEST OF N NUMBERS USING ARRAYS

#include<stdio.h>

#include<conio.h>

void main()

{

int maximum(int a[],int n);

int max,i,n;

int a[50];

clrscr();

printf("enter n :");

scanf("%d",&n);

printf("enter the numbers:");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

max=maximum(a,n);

printf("the largest number is %d",max);

}

int maximum(int a[],int n)

{

int i,m=0;

for(i=0;i<n;i++)

{

if(a[i]>m)

m=a[i];

}

getch();

return m;

}

OUTPUT:

Enter n: 5

Enter the numbers:1879004

The largest number is 90.

Result: Thus c program for finding greatest of n numbers using arrays has been executed successfully.

Ex.No:25 SORTING N NUMBERS USING POINTERS AND FUNCTIONS

Performance 25

Record 15

Viva voce 10

Total 50

Date:

Aim:

To write a c program for sorting n numbers using pointers.

Algorithm:

1. Start the program.2. Enter the number of elements in the array.3. Read the numbers.4. Swap the numbers using5. if(a[j]>a[j+1])

temp=a[j];a[j]=a[j+1];a[j+1]=temp;

6. Print the sorted elements are as a[i].7. Stop the program.

SORTING N NUMBERS USING POINTERS AND FUNCTIONS

#include<stdio.h>

#include<conio.h>

int *a[100],i,j,item;

void main()

{

void sort(),display();

int i;

clrscr();

printf(“\n enter number of elements in the array:”);

scanf(“%d”,&item);

printf(“\n enter %d numbers \n”,item);

for(i=0;i<item;++i)

scanf(“%d”,&a[i]);

sort();

display();

}

void sort()

{

int swap=1,*temp;

for(i=0;i<item && swap==1;++i)

{

swap=0;

for(j=0;j<item-(i+1);++j)

if(a[j]>a[j+1])

{

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

swap=1;

}

}

}

void display()

{

printf(“\n sorted elements are:”);

for(i=0;i<item;++i)

printf(“%d \n”,a[i]);

getch();

}

OUTPUT:

Enter number of elements in the array:

5

Enter 5 numbers

12

00

65

34

78

Sorted elements are:

0

12

34

65

78

Result: Thus c program for sorting n numbers using pointers has been executed successfully.

Performance 25

Record 15

Viva voce 10

Total 50

Ex.No:26 PRINT ARRAY ELEMENTS IN REVERSE ORDER

Date:

Aim:

To write a c program for printning array elements in reverse order.

Algorithm:

1. Start the program.2. Enter the number of elements in the array.3. Read the numbers.4. Print elements of array in original order by

for(i=0;i<n;i++)printf(“%d\n”,ptr[i]);

5. Print elements of array in reverse order by for(i=n-1;i>=0;i--)

printf(“%d\n”,ptr[i]);6. Stop the program.

PRINT ARRAY ELEMENTS IN REVERSE ORDER

#include<stdio.h>

#include<conio.h>

int main()

{

int *ptr,i,n;

clrscr();

printf(“enter no of elements:”);

scanf(“%d”,&n);

ptr=(int *)malloc(sizeof(int)*n);

if(ptr==NULL)

{

printf(“not enough memory”);

exit(1);

}

for(i=0;i<n;i++)

{

printf(“enter %d element:”,i+1);

scanf(“%d”,&ptr[i]);

}

printf(“array in original order\n”);

for(i=0;i<n;i++)

{

printf(“%d\n”,ptr[i]);

}

printf(“array in reverse order\n”);

for(i=n-1;i>=0;i--)

{

printf(“%d\n”,ptr[i]);

}

getch();

return 0;

}

OUTPUT:Enter no of elements:5

Enter 1 element:12

Enter 2 element:90

Enter 3 element:45

Enter 4 element:3

Enter 5 element:67

Array in original order:

12

90

45

3

67

Array in reverse order:

67

3

45

90

12

Performance 25

Record 15

Viva voce 10

Total 50

Result: Thus c program for printing array elements in reverse order has been executed successfully.

Ex.No:27 CONVERTING LOWER CASE CHARACTERS INTO

UPPER CASE EQUIVALENTSDate:

Aim: To write a c program for converting lower case characters into upper case equivalents.

Algorithm:

1. Start the program.2. Enter the string.3. Change the string into upper case by

for(i=0;str[i];i++)if(str[i]>96 && str[i]<123)str[i]-=32;printf(“%s”,str);

4. Stop the program.

CONVERTING LOWER CASE CHARACTERS INTOUPPER CASE EQUIVALENTS

#include<stdio.h>

#include<conio.h>

#include<string.h>

void upper(char[]);

int main()

{

char str[20];

clrscr();

printf(“\n enter string:”);

gets(str);

upper(str);

getch();

return 0;

}

void upper(char str[20])

{

int i;

printf(“%s in upper case is “,str);

for(i=0;str[i];i++)

{

if(str[i]>96 && str[i]<123)

str[i]-=32;

}

printf(“%s”,str);

}

OUTPUT:

Enter string:Hello World

Hello World in upper case is HELLO WORLD

Result: Thus c program for converting lower case characters into upper case equivalents has been executed successfully.

Performance 25

Record 15

Viva voce 10

Total 50

Ex.No:28 COPY THE CONTENTS OF ONE FILE INTO ANOTHER

Date:

Aim:

To write a c program for copying the contents of one file into another.

Algorithm:

1. Start the program.2. Read the source file name.3. Read the target file name.4. Open the source file in read mode.5. Open the target file in write mode.6. Copy the contents into target file by

c=getc(fp1);while(c!=EOF)putc(c,fp2);

7. Close the two files after copying.8. Stop the program.

COPY THE CONTENTS OF ONE FILE INTO ANOTHER

#include<stdio.h>

#include<conio.h>

int main()

{

FILE *fp1,*fp2;

int c;

char fname1[40],fname2[40];

clrscr();

printf(“\n\n\t\t To copy the contents of one file to another \n”);

printf(“\n-----------------------------------------------“);

printf(“\n\n enter the source file:”);

gets(fname1);

printf(“\n \n enter the target file:”);

gets(fname2);

fp1=fopen(fname1,”r”);

fp2=fopen(fname2,”w”);

if(fp1==NULL)

{

printf(“cannot open %s for reading \n”,fname1);

exit(1);

}

else if(fp2==NULL)

{

printf(“cannot open %s for reading \n”,fname2);

exit(1);

}

else

{

c=getc(fp1);

while(c!=EOF)

{

putc(c,fp2);

c=getc(fp1);

}

fclose(fp1);

fclose(fp2);

printf(“\n \n file successfully copied \n”);

getch();

}

}

OUTPUT:

To copy the contents of one file to another

Enter the source file:A.c

Enter the target file:B.c

File successfully copied

Performance 25

Record 15

Viva voce 10

Total 50

Result: Thus c program for copying the contents of one file into another has been executed successfully.

Ex.No: 29 PRINT THE NUMBER OF VOWELS IN GIVEN PARAGRAPHDate:

Aim:

To write a c program for printing the number of vowels in a given paragraph.

Algorithm:

1. Enter a string.2. Count the number of vowels by

if(str[i]==’A’ || str[i]==’a’ || str[i]==’E’ || str[i]==’e’ || str[i]==’I’ || str[i]==’i’ ||

str[i]==’O’ || str[i]==’o’ || str[i]==’U’ || str[i]==’u’)

vowels++3. Print the number of vowels in the given paragraph by

“vowels”.

PRINT THE NUMBER OF VOWELS IN GIVEN PARAGRAPH

#include<stdio.h>

#include<conio.h>

void main()

{

char str[50];

int vowels=0,i=0;

clrscr();

printf(“\n \n enter a string….:”);

gets(str);

while(str[i]!=’\0’)

{

if(str[i]==’A’ || str[i]==’a’ || str[i]==’E’ || str[i]==’e’ || str[i]==’I’ || str[i]==’i’ || str[i]==’O’ || str[i]==’o’ || str[i]==’U’ || str[i]==’u’)

vowels++;

i++;

}

printf(“\n \n \t total number of vowels is:%d”,vowels);

getch();

}

OUTPUT

Enter a string: hai students welcome to cp lab

Performance 25

Record 15

Viva voce 10

Total 50

Total number of vowels is: 9

Result: Thus c program for counting number of vowels in given paragraph has been executed successfully.

Ex.No:30 COMPUTING THE ROOTS OF A QUADRATIC EQUATION

Date:

Aim:

To write a c program for computing the roots of a quadratic equation.

Algorithm:

1. Start the program.2. Enter the values of a,b,c.3. Compute d=b*b-4*a*c4. Root r1=-b+sqrt(d)/2*a5. Root r2=-b-sqrt(d)/2*a6. If d<0 then roots are imaginary.7. If r1=r2 then roots are real and equal.8. Stop the program.

COMPUTING THE ROOTS OF A QUADRATIC EQUATION

#include<conio.h>

#include<math.h>

#include<conio.h>

void main()

{

float a,b,c,d,real,imag,r1,r2,n;

int k;

clrscr();

printf(“enter the values of a,b,c:”);

scanf(“%f%f%f”,&a,&b,&c);

if(a!=0)

{

d=b * b – 4 * a * c;

if(d<0)

k=1;

if(d==0)

k=2;

if(d>0)

k=3;

switch(k)

{

case 1:

printf(“\n roots are imaginary\n”);

real=-b / (2 * a);

d=-d;

n=pow((double)d,(double)0.5);

imag=n / (2 * a);

printf(“\n r1=%7.2f+j%7.2f”,real,imag);

printf(“\n r2=%7.2f-j%7.2f”,real,imag);

break;

case 2:

printf(“\n roots are real and equal\n”);

r1= -b / (2 * a);

printf(“\n r1=r2=%7.2f”,r1);

break;

case 3:

printf(“\n roots are real and unequal \n”);

r1=(- b + sqrt((double)d)) / (2 * a);

r2=(- b - sqrt((double)d)) / (2 * a);

printf(“\n r1=%7.2f”,r1);

printf(“\n r2=%7.2f”,r2);

break;

}

}

else

printf(“\n equation is linear”);

getch();

}

OUTPUT:

Enter the values of a, b, c:

1

2

1

Roots are real and equal

r1=r2=-1.00

Performance 25

Record 15

Viva voce 10

Total 50

Result: Thus c program for computing the roots of quadratic equation has been executed successfully.

Ex.No:31 SORT N NAMES ALPHABETICALLY USING POINTERS AND FUNCTIONS

Date:

Aim:

To write a c program for sorting n names alphabetically using pointers and functions.

Algorithm:

1. Start the program.2. Enter the number of names.3. Read the names.4. By using pointer and function reorder(int n,char *x[])

Sort the names by if(strcmp(x[item],x[i]>0)

temp=x[item]x[item]=x[i]x[i]=temp

5. Print the names in alphabetical order. 6. Stop the program.

SORT N NAMES ALPHABETICALLY USING POINTERS AND FUNCTIONS

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<conio.h>

void reorder(int n,char *x[]);

int main(){ int i,no_string; char *x[10]; clrscr(); printf(“enter the no of strings:”); scanf(“%d”,&no_string); printf(“\n enter the strings:”); for(i=0;i<no_string;i++) { x[i]=(char*) malloc (12*sizeof(char));

printf(“\n string %d:”,i+1);scanf(“%s,x[i]);

} printf(“\n the sorted strings are:”); reorder(i,x); for(i=0;i<no_string;i++) {

printtf(“\n string %d %s”,i+1,x[i]); } Return 0;}

void reorder(int n,char *x[]){ char *temp; int i,item; for(item=0;item<n-1;++item)

{for(i=item+1;i<n;++i){

if(strcmp(x[item],x[i])>0){

temp=x[item];x[item]=x[i];x[i]=temp;

}}

}return;}

OUTPUT:

Enter the number of strings:5

Enter the strings:

String 1: Gandhi

String 2: Nehru

String 3: Singh

String 4: Patel

String 5: Bose

The sorted strings are:

String 1: Bose

String 2: Gandhi

String 3: Nehru

String 4: Patel

String 5: Singh

Performance 25

Record 15

Viva voce 10

Total 50

Result: Thus c program for sorting n names alphabetically using pointers and functions has been executed successfully.