Tuesday, May 15, 2012

GE2155 (Computer Practice Lab-2)-- Lab Manual

STUDY OF UNIX OPERATING SYSTEM




Aim :

To study the basic concepts of unix operating system.



Operating system

An operating system (OS) is a set of software that manages computer hardware resources and provides common services for computer programs. The operating system is a vital component of the system software in a computer system. Application programs require an operating system to function.

Time-sharing operating systems schedule tasks for efficient use of the system and may also include accounting for cost allocation of processor time, mass storage, printing, and other resources.

For hardware functions such as input and output and memory allocation, the operating system acts as an intermediary between programs and the computer hardware,[1][2] although the application code is usually executed directly by the hardware and will frequently make a system call to an OS function or be interrupted by it. Operating systems can be found on almost any device that contains a computer—from cellular phones and video game consoles to supercomputers and web servers.

Examples of popular modern operating systems include Android, BSD, iOS, Linux, Mac OS X, Microsoft Windows, Windows Phone, and IBM z/OS. All these, except Windows and z/OS, share roots in UNIX.





















Types of Operating Systems

Real-time Operating Systems

A real-time operating system is a multitasking operating system that aims at executing real-time applications. Real-time operating systems often use specialized scheduling algorithms so that they can achieve a deterministic nature of behavior. The main objective of real-time operating systems is their quick and predictable response to events. They have an event-driven or time-sharing design and often aspects of both. An event-driven system switches between tasks based on their priorities or external events while time-sharing operating systems switch tasks based on clock interrupts.

Multi-user Operating Systems

A multi-user operating system allows multiple users to access a computer system concurrently. Time-sharing system can be classified as multi-user systems as they enable a multiple user access to a computer through the sharing of time. Single-user operating systems, as opposed to a multi-user operating system, are usable by a single user at a time. Being able to use multiple accounts on a Windows operating system does not make it a multi-user system. Rather, only the network administrator is the real user. But for a UNIX-like operating system, it is possible for two users to login at a time and this capability of the OS makes it a multi-user operating system.

Multi-tasking vs. Single-tasking Operating Systems

When only a single program is allowed to run at a time, the system is grouped under a single-tasking system. However, when the operating system allows the execution of multiple tasks at one time, it is classified as a multi-tasking operating system. Multi-tasking can be of two types: pre-emptive or co-operative. In pre-emptive multitasking, the operating system slices the CPU time and dedicates one slot to each of the programs. Unix-like operating systems such as Solaris and Linux support pre-emptive multitasking, as does AmigaOS. Cooperative multitasking is achieved by relying on each process to give time to the other processes in a defined manner. 16-bit versions of Microsoft Windows used cooperative multi-tasking. 32-bit versions, both Windows NT and Win9x, used pre-emptive multi-tasking. Mac OS prior to OS X used to support cooperative multitasking.

Distributed Operating Systems

A distributed operating system manages a group of independent computers and makes them appear to be a single computer. The development of networked computers that could be linked and communicate with each other gave rise to distributed computing. Distributed computations are carried out on more than one machine. When computers in a group work in cooperation, they make a distributed system.

Embedded Operating Systems

Embedded operating systems are designed to be used in embedded computer systems. They are designed to operate on small machines like PDAs with less autonomy. They are able to operate with a limited number of resources. They are very compact and extremely efficient by design. Windows CE and Minix 3 are some examples of embedded operating systems.

Functions of Operating systems

1. Program creation

2. Program execution

3. Access to Input/output devices

4. Controlled access to files

5. System access

6. Error detection and response

7. Interpreting the commands

8. Managing peripherals

9. Memory management

10. Processor management

11. Information management

12. Process communication

13. Networking

Services of Operating System:

1. Memory management

2. Process management

3. File management

4. I/O Management

5. Scheduling

6. Security managament

Unix architecture

A Unix architecture is a computer operating system system architecture that embodies the Unix philosophy. It may adhere to standards such as the Single UNIX Specification (SUS) or similar POSIX IEEE standard. No single published standard describes all Unix architecture computer operating systems - this is in part a legacy of the Unix wars.





Kernel

A Unix kernel — the core or key components of the operating system — consists of many kernel subsystems like process management, memory management, file management, device management and network management.

Each of the subsystems has some features:

1. Concurrency: As Unix is a multiprocessing OS, many processes run concurrently to improve the performance of the system.

2. Virtual memory (VM): Memory management subsystem implements the virtual memory concept and a user need not worry about the executable program size and the RAM size.

3. Paging: It is a technique to minimize the internal as well as the external fragmentation in the physical memory.

4. Virtual file system (VFS): A VFS is a file system used to help the user to hide the different file systems complexities. A user can use the same standard file system related calls to access different file systems.

The kernel provides these and other basic services: interrupt and trap handling, separation between user and system space, system calls, scheduling, timer and clock handling, file descriptor management.

The kernel is the essential center of a computer operating system, the core that provides basic services for all other parts of the operating system. A synonym is nucleus. A kernel can be contrasted with a shell, the outermost part of an operating system that interacts with user commands. Kernel and shell are terms used more frequently in Unix operating systems than in IBM mainframe or Microsoft Windows systems.

In computer science, the kernel is the central component of most computer operating system(OS). Its responsibilities include managing the system's resources (the communication between hardware and software components). As a basic component of an operating system, a kernel provides the lowest-level abstraction layer for the resources (especially memory, processors and I/O devices) that application software must control to perform its function. It typically makes these facilities available to application programs through inter process communication mechanisms and system calls.

These tasks are done differently by different kernels, depending on their design and implementation. While monolithic kernels will try to achieve these goals by executing all the code in the same address space to increase the performance of the system, microkernels run most of their services in user space, aiming to improve maintainability and modularity of the codebase. A range of possibilities exists between these two extremes.

Features

Some key features of the Unix architecture concept are:

1. Unix systems use a centralized operating system kernel which manages system and process activities.

2. All non-kernel software is organized into separate, kernel-managed processes.

3. Unix systems are preemptively multitasking: multiple processes can run at the same time, or within small time slices and nearly at the same time, and any process can be interrupted and moved out of execution by the kernel. This is known as thread management.

4. Files are stored on disk in a hierarchical file system, with a single top location throughout the system (root, or "/"), with both files and directories, subdirectories, sub-subdirectories, and so on below it.

5. With few exceptions, devices and some types of communications between processes are managed and visible as files or pseudo-files within the file system hierarchy. This is known as everything is a file. However, Linus Torvalds states that this is inaccurate and may be better rephrased as "everything is a stream of bytes".[1]

The UNIX operating system supports the following features and capabilities:

1. Multitasking and multiuser.

2. Kernel written in high-level language.

3. Programming interface.

4. Use of files as abstractions of devices and other objects.

5. Character-based default UI.

6. Built-in networking. (TCP/IP is standard)

7. Persistent system service processes called "daemons" and managed by init or inetd.

Unix shell

A Unix shell is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems. Users direct the operation of the computer by entering commands as text for a command line interpreter to execute or by creating text scripts of one or more such commands.

The most influential Unix shells have been the Bourne shell and the C shell. The Bourne shell, sh, was written by Stephen Bourne at AT&T as the original Unix command line interpreter; it introduced the basic features common to all the Unix shells, including piping, here documents, command substitution, variables, control structures for condition-testing and looping and filename wildcarding. The language, including the use of a reversed keyword to mark the end of a block, was influenced by ALGOL 68.[1]

The C shell, csh, was written by Bill Joy while a graduate student at University of California, Berkeley. The language, including the control structures and the expression grammar, was modeled on C. The C shell also introduced a large number of features for interactive work, including the history and editing mechanisms, aliases, directory stacks, tilde notation, cdpath, job control and path hashing. Both shells have been used as coding base and model for many derivative and work-alike shells with extended feature sets.

The most generic sense of the term shell means any program that users employ to type commands. A shell hides the details of the underlying operating system with the shell interface and manages the technical details of the operating system kernel interface, which is the lowest-level, or 'inner-most' component of most operating systems. In Unix-like operating systems users typically have many choices of command-line interpreters for interactive sessions. When a user logs in to the system, a shell program is automatically executed. The login shell may be customized for each user, typically in the passwd file, and can be customized via passwd -e, or on some systems via the chsh program. In addition, a user is typically allowed to execute another shell program interactively.

The Unix shell was unusual when it was introduced. It is both an interactive command language as well as a scripting programming language, and is used by the operating system as the facility to control (shell script) the execution of the system. Shells created for other operating systems than Unix, often provide similar functionality.

On systems with a windowing system, some users may never use the shell directly. On Unix systems, the shell is still the implementation language of system startup scripts, including the program that starts the windowing system, the programs that facilitate access to the Internet, and many other essential functions.

Graphical user interfaces for Unix, such as GNOME, KDE, and Xfce are often called visual or graphical shells.

Bourne shell

The Bourne shell was one of the major shells used in early versions of the Unix operating system and became a de facto standard. It was written by Stephen Bourne at Bell Labs and was first distributed with Version 7 Unix, circa 1977. Every Unix-like system has at least one shell compatible with the Bourne shell. The Bourne shell program name is sh and it is typically located in the Unix file system hierarchy at /bin/sh. On many systems, however, /bin/sh may be a symbolic link or hard link to a compatible, but more feature-rich shell than the Bourne shell. The POSIX standard specifies its standard shell as a strict subset of the Korn shell. From a user's perspective the Bourne shell was immediately recognized when active by its characteristic default command line prompt character, the dollar sign ($).

C shell

The C shell was developed by Bill Joy for the Berkeley Software Distribution, a line of Unix operating systems derived from Unix and developed at the University of California, Berkeley. It was originally derived from the 6th Edition Unix shell (Thompson shell). Its syntax is modeled after the C programming language. It is used primarily for interactive terminal use, but less frequently for scripting and operating system control. C shell has many interactive commands.

FILE SYSTEM



A file in a collection of letters and special characters and it may be program or a database or a simple letter etc.,



Features of file system:

1. Logical block of 512 bytes or multiplies

2. Arranged to form a hierarchical structure

3. Convenient to manage data



Files in UNIX

1. Ordinary files

2. Directory files

3. Special files

4. Standard files



File system layout



Boot

Block Super

Block Inode

Block Data

Block



i) Boot Block



 Generally occupies the first sector

 May contain strap code



ii) Super Block

 Contains information about the file system, such as the file size, available free space and other details

iii) Inode Block



 Contains a list of inodes.

 One inode in the root node.



iv) Data Block



 Contains file and administrative data.

 Allocated data can be logged to that block only.







Result:

Thus the basic concepts of unix operating system and its features was studied.

















Basic Unix Shell Commands



















Basic Unix Shell Commands





1. Working with files



1. Creating a file using cat command

2. Creating and editing a file using vi command

3. Display contents of a file



2. Working with directories





1. Current Working Directory

2. Create a directory

3. Removing a directory



4. Changing the working directory

5. Clearing the screen

6. Path





3. Playing with files



1. Copying a file

2. Removing a file

3. Moving a file

4. List files and directories

5. Directing output to a file

6. Counting number of words in a file

7. File types





4. File Permissions



1. Changing the file permissions



5. General Purpose Commands





1. Date

2. Echo

3. The unix calendar

4. Unix calculator

5. Expression

6. Who

7. Who am i

8. Finger

9. Id

10. Tty

11. Change the password





6. Command Grouping



1. The Semicolon(;)

2. The && operator(AND)

3. THE

operator(OR)



7. Filters



1. The head filter

2. The tail filter

3. The pg filter

4. More command

5. Grep command

6. Sorting the contents

7. Uniq

8. Adding line numbers

9. Selecting fields from a line(CUT)

10. Paste

11. Comparing files

12. Common and difference



BASIC UNIX SHELL COMMANDS

Aim:

To execute the basic unix shell commands in unix operating system.



Commands:



1.Working with files



Creating a file using cat command



Command cat

Syntax cat > filename

Description To create a file , type the contents . to end the file after the contents press “CTRL + d”



Creating and editing a file using vi command



Command vi

Syntax vi filename

Description To create a file,

Press “i – insert ” to type the contents,

Press “esc + :wq” to save and end the file.



Display contents of a file



Command cat

Syntax cat filename

cat file1 file2 > file 3

Description 1.To display the contents of a file specified

2.To load the contents of file1,file2 to file3



2.Working with directories





Current Working Directory



Command pwd

Syntax pwd

Description To know the current working directory



Create a directory



Command mkdir

Syntax mkdir directory name

Description To create a directory in a disk





Removing a directory



Command rmdir

Syntax rmdir directory name

Description To remove the directory from the disk



Changing the working directory



Command cd

Syntax cd directory name

Description To move from one directory to anorther directory



Clearing the screen



Command tput clear

Syntax tput clear

Description To clear the terminal screen



Path





Command path

Syntax path

Description To display the path of the operating system(sequence of directories)







3.Playing with files





Copying a file



Command cp

Syntax cp old_filename new_filename

Description To copy the contents of old_file to new_file.



Removing a file



Command rm

Syntax rm filename

Description To remove the filename specified from the disk.



Moving a file



Command mv

Syntax mv old_filename new_filename

Description To move the contents of old_file to new_file or rename the old_file as new_file.







List files and directories



Command ls

Syntax ls or ls directory_name

Description To list the files and directories in the disk as alphabetical order.



Directing output to a file



Command ls

Syntax ls > filename

Description Output of ls command is stored to disk file specified



Counting number of words in a file



Command wc

Syntax wc filename

Description To count the number of words, line and characters in a file

Format

nl nw nc filename



File types



Command file

Syntax file filename

Description To display the type of the file specified either ordinary or directory or device





4.File Permissions



Changing the file permissions



Command chmod

Syntax chmod category operation permission file(s)

Description To apply the permissions to the files either read or write or execute



Category Operations Permissions

u-users

g-group

o-others

a-all + assign

remove

= assign absolutely r –read

w-write

x-excute



Example: chmod u + w filename

Applied write permission to filename specified.







5.General Purpose Commands





Date



Command date

Syntax date

Description To display the current date with day of the week



Echo



Command echo

Syntax echo “Text”

Description To display the specified





The unix calendar



Command cal

Syntax cal month year or cal year

Description To display the calendar of the month with year specified or display all the months in a year



Unix calculator

Command bc

Syntax bc

Description To perform the arithmetical operations



Example:

bc

4+4 (enter)

8

Ctrl + d (to end the calculator)



Expression



Command expression

Syntax 1.expr operand operator operand (real integers)

2.echo operand operator operand
bc (floating point values)

Description To perform the arithmetical operations using expression



Who

Command who

Syntax who

Description To display data about all users, who are currently logged into the system







Who am i



Command Who am i

Syntax Who am i

Description To display data about current user, who are currently logged into the system ie., identity of the user.



Finger

Command finger

Syntax finger username

Description To display the information about the users, which includes login name, real name, home directory etc.,



Id

Command id

Syntax id

Description To display the numerical value that corresponds to your login name



Tty

Command tty

Syntax tty

Description To now the terminal name that we are using



Change the password





Command passwd

Syntax passwd

Description To change the password of the current user.



6.Command Grouping



The Semicolon(;)

Command Semicolon

Syntax Command1;Command2;Command3;…………..;Command n

Description It executes all the commands at time

Example:

date; cal 2002; echo Siva

It displays the date , calendar of year 2002 and text siva at a time



The && operator(AND)



Command AND

Syntax Command1 && Command2 && Command3 && ………….. && Command n

Description It execute all the commands after the successful execution of previous commands

Example:

date && cal 2002 && echo Siva

It displays the date, after the successful execution of date displays calendar of year 2002 and after the successful execution of cal displays text Siva at a time



The

operator(OR)



Command OR

Syntax Command1

Command2

Command3

…………..

Command n

Description It executes all the commands, if command1 fails also it continues command2 and goes on

Example:

date

cl 2002

echo Siva

It displays the date command, calendar syntax is wrong so, it doesn’t execute calendar and passes to echo command. If any syntax error in commands, it stops that command must and continues from next command.



7.Filters





The head filter



Command head

Syntax head filename

Description It displays top ten lines of contents in a filename



The tail filter



Command tail

Syntax tail filename

Description It displays last ten lines of contents in a filename



The pg filter



Command page

Syntax ls
pg

Description It shows the file page by page



More command



Command more

Syntax more filename

Description It displays all the information about the filename specified.











Grep command



Command Grep

Syntax grep [pattern or string] filename

Description It displays the lines of file which contains the pattern or string specified.



Sorting the contents



Command Sort

Syntax sort filename

Description To sort the contents of a file in alphabetical order.



Uniq

Command Uniq

Syntax uniq filename

Description Fetches one copy of the redundant records writing them to the standard output



Adding line numbers



Command nl

Syntax nl filename

Description nl filter adds the line numbers to a file.



Selecting fields from a line(CUT)



Command cut

Syntax cut –c filename

Description It cut the contents of column specified from the file

Example:

cut –c4 siva

It cuts the contents of column 4 from the file siva.

Paste



Command paste

Syntax paste filename

Description Used to paste the contents which is cut



Comparing files



Command compare

Syntax cmp file1 file2

Description Compares the file1 and file2 and displays the identical in all respects, so that any one of them can be deleted.







Common and difference





Command difference

Syntax diff file1 file2

Description Shows the difference between file1 and file2



Logout



Command logout

Syntax logout

Description To stop the jobs working on it and exit the unix editor.







Result:

Thus the basic unix shell commands were executed in UNIX operating system successfully and output was verified.















SHELL PROGRAMS





























List of Shell Programs

1. AREA AND CIRCUMFERENCE OF THE CIRCLE

2. SQUARE AND CUBE OF A NUMBER

3. SWAPPING OF TWO NUMBERS USING TWO VARIABLES

4. SWAPPING OF TWO NUMBERS USING THREE VARIABLES

5. ARITHMETIC OPERATIONS WITHOUT USING CASE STATEMENT

6. GROSS SALARY CALCULATION

7. USER LOGIN USING IF STATEMENT

8. BIGGEST AMONG TWO NUMBERS

9. BIGGEST AMONG THREE NUMBERS

10. ODD OR EVEN

11. ARITHMETIC OPERATIONS USING SWITCH CASE STATEMENT

12. POSITIVE OR NEGATIVE OR ZERO

13. TO PRINT N NATURAL NUMBERS

14. SUM OF N NATURAL NUMBERS USING WHILE LOOP

15. SUM OF DIGITS IN A GIVEN NUMBER

16. SUM OF N NATURAL NUMBERS USING UNTIL STATEMENT

17. SUM OF N NUMBERS USING FOR LOOP

18. FACTORIAL OF THE GIVEN NUMBER USING WHILE LOOP

19. FACTORIAL OF THE GIVEN NUMBER USING FOR LOOP

20. PRIME OR NOT

21. REVERSE THE GIVEN STRING

22. SUM OF N EVEN NUMBERS USING UNTIL STATEMENT

23. SHELL PROGRAM USING FUNCTION WITH GRADE



AREA AND CIRCUMFERENCE OF THE CIRCLE

AIM:

To write a shell program to find the area of the circle.

ALGORITHM:

1. Start the program.

2. Get the radius ‘r’ as input.

3. Calculate the area of the circle using A=3.14 * r *r.

4. Calculte Circumference of Crircle C=2*3.14*r

5. Print the area(A) and circumference(C) of the circle using echo command.

6. Stop the program.

PROGRAM:



echo "Enter the radius of the Circle"

read r

A=`echo 3.14 \* $r \* $r
bc`

C=`echo 2 \* 3.14 \* $r
bc`

echo "Area of the Circle=$A"

echo "Circumference of the Circle=$C"



OUTPUT:



Enter the radius of the Circle

2

Area of the Circle=12.56

Circumference of the Circle= 12.56



RESULT:

Thus the shell program for area and circumference of the circle was written, executed and output was verified.















SQUARE AND CUBE OF A NUMBER

AIM:

To write a shell program to find the area of the square and cube.

ALGORITHM:

1. Start the program.

2. Get the value of a as input.

3. Calculate the area of the square using ‘a *a’.

4. Calculate the area of the cube using `a*a*a`.

5. Print the area of the square and cube using echo command.

6. Stop the program.

PROGRAM:



echo "Enter the side of a"

read a

s=`expr $a \* $a`

c=`expr $a \* $a \* $a`

echo "Square of given number is $s"

echo "Cube of given number is $c"





OUTPUT:



Enter the side of a

4

Square of given number is 16

Cube of given number is 64



RESULT:

Thus the shell program for square and cube a number was written, executed and output was verified.















SWAPPING OF TWO NUMBERS USING TWO VARIABLES

AIM:

To write a shell program to swap the two numbers using two variables.

ALGORITHM:

1. Start the program.

2. Get the two values a, b as input.

3. Print the value of a and b before swapping.

4. Calculate a+b and assign it to a.

5. Calculate a-b and assign it to b.

6. Calculate a-b and assign it to a.

7. Print the value of a, b after swapping.

8. Stop the program.

PROGRAM:-



echo "Enter the two values"

read a b

echo "Before swapping"

echo "A=$a B=$b"

a=`expr $a + $b`

b=`expr $a - $b`

a=`expr $a - $b`

echo "After swapping"

echo "A=$a B=$b"



OUTPUT:-



Enter the two values

5 2

Before swapping

A=5 B=2

After swapping

A=2 B=5



RESULT:

Thus the shell program for swapping of two numbers using two variables was written, executed and output was verified.





SWAPPING OF TWO NUMBERS USING THREE VARIABLES

AIM:

To write a shell program to swap the two numbers using three variables.

ALGORITHM:

1. Start the program.

2. Get the two values a, b as input.

3. Print the value of a, b before swapping.

4. Assign value of a to c.

5. Assign value of b to a.

6. Assign value of c to a.

7. Print the value of a, b after swapping using echo command.

8. Stop the program.

PROGRAM:



echo "Enter the two number"

read a b

echo "Before swapping"

echo "A=$a B=$b"

c=$a

a=$b

b=$c

echo "After swapping"

echo "A=$a B=$b"





OUTPUT:



Enter the two number

5 7

Before swapping

A=5 B=7

After swapping

A=7 B=5



RESULT:

Thus the shell program for swapping of two numbers using three variables was written, executed and output was verified.







ARITHMETIC OPERATIONS WITHOUT USING CASE STATEMENT

AIM:

To write a shell program to perform the arithmetic operations without using case statement.

ALGORITHM:

1. Start the program.

2. Get the two values a, b as input.

3. Perform addition using add = a+b

4. Perform subtraction using sub = a-b

5. Perform multiplication using mul=a*b

6. Perform division using div=a/b

7. Print the value of add, sub, mul and div.

8. Stop the program.

PROGRAM:-



echo "Enter the value of a:"

read a

echo "Enter the value of b:"

read b

add=`expr $a "+" $b`

sub=`expr $a "-" $b`

mul=`expr $a "*" $b`

div=`expr $a "/" $b`

echo "The sum of the number is $add"

echo "The subtraction of two number is $sub"

echo "The multiplication of two number is $mul"

echo "The division of two number is $div"



OUTPUT:



Enter the value of a:

6

Enter the value of b:

3

The sum of the number is 9

The subtraction of two number is 3

The multiplication of two number is 18

The division of two number is 2



RESULT:

Thus the shell program for arithmetic operations without using case statement was written, executed and output was verified.





GROSS SALARY CALCULATION

AIM:

To write a shell program to calculate the gross salary for ta as 10% of basicsalary and hra as 20% of basicsalary.

ALGORITHM:

1. Start the program.

2. Get basicpay as input.

3. Calculate ta=basicpay*10/100.

4. Calculate hra=basicpay*20/100.

5. Calculate grosssalary=basicpay+ta+hra.

6. Print the gross salary.

7. Stop the program.

PROGRAM:-



echo "Enter the basic salary:"

read b

hra=`echo $b \* 0.04
bc`

da=`echo $b \* 0.05
bc`

t=`echo $hra + $da + $b
bc`

echo "The amount of HRA is $hra"

echo "The amount of DA is $da"

echo "The Basic salary is $b"

echo "The Gross salary is $t"



OUTPUT:-



Enter the basic salary:

5000

The amount of HRA is 200.00

The amount of DA is 250.00

The Basic salary is 5000

The Gross salary is 5450.00



RESULT:

Thus the shell program for gross salary calculation was written, executed and output was verified.







USER LOGIN USING IF STATEMENT

AIM:

To write a shell program to check the user login using if statement.

ALGORITHM:

1. Start the program.

2. Get the username as input.

3. logname command is used to find the current user login name and assign it to c.

4. Check whether the c and username is equal using if statement.

5. If it is true, then print the “welcome user”.

6. Otherwise, print the “not correct”

7. Stop the program.

PROGRAM:-



echo "Enter user name"

read user

c=`logname`

if [ $c=$user ] then

then

echo "welcome user"

else

echo “ not correct user”

fi



OUTPUT:-





Enter user name

PSR

welcome user



RESULT:

Thus the shell program for check the user login using if statement was written, executed and output was verified.









BIGGEST AMONG TWO NUMBERS

AIM:

To write a shell program to find the biggest number among two numbers.

ALGORITHM:

1. Start the program.

2. Get the two values a, b as input.

3. If a>b, then print a is big.

4. Otherwise, print b is big.

5. Stop the program.

PROGRAM:-



echo Enter three numbers:

read a b

if [ $a -gt $b ]

then

echo "A is big"

else

echo "B is big"

fi



OUTPUT:-



Enter three numbers:

6 5

A is big



Enter three numbers:

5 6

B is big



RESULT:

Thus the shell program for biggest among two numbers were written, executed and output was verified.









BIGGEST AMONG THREE NUMBERS

AIM:

To write a shell program to find the biggest number among three numbers.

ALGORITHM:

1. Start the program.

2. Get the two values a, b and c as input.

3. If a>b and a>c, then print a is big.

4. Otherwise, check the condition b>c.

5. If it is true, print b is big.

6. Otherwise, print c isbig.

7. Stop the program.

PROGRAM:-



echo "Enter three numbers"

read a b c

if [ $a -gt $b -a $a -gt $c ]

then

echo "A is big"

elif [ $b -gt $c ]

then

echo "B is big"

else

echo "C is big"

fi



OUTPUT:-



Enter three numbers

6 5 4

A is big Enter three numbers

5 6 4

B is big



Enter three numbers

4 5 6

C is big







RESULT:

Thus the shell program for biggest among three numbers were written, executed and output was verified.







ODD OR EVEN

AIM:

To write a shell program to find the given number is odd or even.

ALGORITHM:

1. Start the program.

2. Get the two values a, b as input.

3. Calculate r%2 and assign it to c.

4. If c = 0, then print “Even number”

5. Otherwise, print “Odd Number”

6. Stop the program.

PROGRAM:-



echo "Enter the number"

read r

c=`expr $r % 2`

if [ $c -eq 0 ]

then

echo “Even”

else

echo “odd”

fi



OUTPUT:-



Enter the number

2

Even

Enter the number

3

Odd



RESULT:

Thus the shell program for odd or even was written, executed and output was verified.











ARITHMETIC OPERATIONS USING SWITCH CASE STATEMENT

AIM:

To write a shell program to perform the arithmetic operation using switch case statement.

ALGORITHM:

1. Start the program.

2. Get a, b and choice as input.

3. If select choice 1, then perform the addition x=a+b.

4. If select choice 2, then perform the subtraction x=a-b.

5. If select choice 3, then perform the multiplication x=a*b.

6. If select choice 4, then perform the division x=a/b.

7. If any one of the 4 option is not selected, then print the invalid choice.

8. Stop the program.

PROGRAM:



echo "Enter two numbers"

read a b

echo "Enter 1 for addition"

echo "Enter 2 for subtraction"

echo "Enter 3 for multiplication"

echo "Enter 4 for division"

echo "Enter your choice"

read choice

case "$choice" in

1)x=`expr $a + $b`

echo "The addition of $a and $b is $x";;

2)x=`expr $a - $b`

echo "The subtraction of $a and $b is $x";;

3)x=`expr $a \* $b`

echo "The multiplication of $a and $b is $x";;

4)x=`expr $a / $b`

echo "The division of $a and $b is $x";;

*) echo "Invalid choice"

exit;;

esac



OUTPUT:



Enter two numbers

5 9

Enter 1 for addition

Enter 2 for subtraction

Enter 3 for multiplication

Enter 4 for division

Enter your choice

1

The addition of 5 and 9 is 14



RESULT:

Thus the shell program for arithmetic operation using switch case statement was written, executed and output was verified.











































POSITIVE OR NEGATIVE OR ZERO

AIM:

To write a shell program to find the given number is positive or negative or zero.

ALGORITHM:

1. Start the program.

2. Get a as input.

3. If a>0, then print “the given no. is positive”.

4. Else check a<0, then print “the given no. is negative”

5. Otherwise, print “the given no. is zero”.

6. Stop the program.

PROGRAM:-

echo "Enter a number:"

read a

if [ $a -gt 0 ]

then

echo "The given number is Positive"

elif [ $a -lt 0 ]

then

echo "The given number is Negative"

else

echo "The given number is Zero"

fi

OUTPUT:



Enter a number:

5

The given number is Positive

Enter a number:

-5

The given number is Negative

Enter a number:

0

The given number is Zero

RESULT:

Thus the shell program for finding the given number is positive, negative or zero was written, executed and output was verified.













TO PRINT N NATURAL NUMBERS

AIM:

To write a shell program to print the N natural numbers.

ALGORITHM:

1. Start the program.

2. Get n as input.

3. Initialize i=1.

4. Check the condition i

5. Print i value.

6. Increment i value by 1.

7. Repeat Step 4 to 6 until the condition becomes false.

8. Print the N numbers.

9. Stop the program.

PROGRAM:-



echo "upper limit"

read n

i=1

while [ $i -le $n ]

do

echo "$i"

i=`expr $i + 1`

done



OUTPUT:-



upper limit

5

1

2

3

4

5



RESULT:

Thus the shell program to print the N natural numbers was written, executed and output was verified.





SUM OF N NATURAL NUMBERS USING WHILE LOOP

AIM:

To write a shell program to find the sum of N numbers using while loop.

ALGORITHM:

1. Start the program.

2. Get n as input.

3. Initialize i=1 and sum=0.

4. Check the condition i

5. Calculate sum=sum+i.

6. Increment i value by 1.

7. Repeat Step 4 to 6 until the condition becomes false.

8. Print the sum of N numbers.

9. Stop the program.

PROGRAM:-



echo "Enter the limit"

read n

i=1

sum=0

while [ $i -le $n ]

do

sum=`expr $sum + $i`

i=`expr $i + 1`

done

echo "The sum of $n numbers is $sum"



OUTPUT:-



Enter the limit

10

The sum of 10 numbers is 55



RESULT:

Thus the shell program for sum of N numbers was written, executed and output was verified.







SUM OF DIGITS IN A GIVEN NUMBER

AIM:

To write a shell program to find the sum of digits in a given number.

ALGORITHM:

1. Start the program.

2. Get n as input.

3. Initialize sum=0.

4. Check the condition n>0 using while loop.

5. Calculate n%10 and assign it to a.

6. Calculate sum=sum+a and assign it to sum.

7. Calculate n/10 and assign it to n.

8. Repeat Step 4 to 7 until the condition becomes false.

9. Print the sum of digits in a given number.

10. Stop the program.

PROGRAM:



echo "Enter the number"

read n

sum=0

while [ $n -gt 0 ]

do

a=`expr $n % 10`

sum=`expr $sum + $a`

n=`expr $n / 10`

done

echo "sum of digits in the given number is $sum"





OUTPUT:



Enter the number

123

sum of digits in the given number is 6



RESULT:

Thus the shell program for sum of digits in a given number was written, executed and output was verified.





SUM OF N NATURAL NUMBERS USING UNTIL STATEMENT

AIM:

To write a shell program to find the sum of N numbers using until loop.

ALGORITHM:

1. Start the program.

2. Get n as input.

3. Initialize i=1 and sum=0.

4. Check the condition i>n using until loop.

5. Calculate sum=sum+i.

6. Increment i value by 1.

7. Repeat Step 4 to 6 until the condition becomes false.

8. Print the sum of N numbers.

9. Stop the program.

PROGRAM:-



echo "Enter the limit"

read n

i=1

sum=0

until [ $i -gt $n ]

do

sum=`expr $sum + $i`

i=`expr $i + 1`

done

echo "The sum of $n numbers is $sum"



OUTPUT:-



Enter the limit

6

The sum of 6 numbers is 21



RESULT:

Thus the shell program for sum of N numbers using until statement was written, executed and output was verified.







SUM OF N NUMBERS USING FOR LOOP

AIM:

To write a shell program to find the sum of N numbers using for loop.

ALGORITHM:

1. Start the program.

2. Initialize sum=0.

3. Using for loop initialize I in 1 2 3 4 5.

4. Calculate sum=sum+i.

5. Loop is executed for 5 times.

6. Print the sum of N numbers.

7. Stop the program.

PROGRAM:



sum=0

for i in 1 2 3 4 5

do

sum=`expr $sum + $i`

done

echo "The sum of number in the list is $sum"





OUTPUT:



The sum of number in the list is 15



RESULT:

Thus the shell program for sum of N numbers using for loop was written, executed and output was verified.















FACTORIAL OF THE GIVEN NUMBER USING WHILE LOOP

AIM:

To write a shell program to find the factorial of the given number using while loop.

ALGORITHM:

1. Start the program.

2. Get n as input.

3. Initialize i=1 and fact=1.

4. Check the condition i

5. Calculate f=f*i.

6. Increment i value by 1.

7. Repeat Step 4 to 6.

8. Print the factorial of the given number.

9. Stop the program.

PROGRAM:



echo "Enter a number"

read n

i=1

fact=1

while [ $i -le $n ]

do

fact=`expr $fact \* $i`

i=`expr $i + 1`

done

echo "Factorial value of $n is $fact"





OUTPUT:



Enter a number

5

Factorial value of 5 is 120



RESULT:

Thus the shell program for factorial of the given number using while loop was written, executed and output was verified.







FACTORIAL OF THE GIVEN NUMBER USING FOR LOOP

AIM:

To write a shell program to find the factorial of the given number using for loop.

ALGORITHM:

1. Start the program.

2. Initialize sum=0.

3. Using for loop initialize I in 1 2 3 4 5.

4. Calculate f=f*i.

5. Loop is executed for 5 times.

6. Print the factorial of the given number.

7. Stop the program.

PROGRAM:



echo "Enter the value"

read n

f=1

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

do

f=`expr $f "*" $i`

done

echo "Factorial value : $f"





OUTPUT:-



Enter the value

5

Factorial value : 120



RESULT:

Thus the shell program for factorial of the given number using for loop was written, executed and output was verified.











PRIME OR NOT

AIM:

To write a shell program to find the given number is prime or not.

ALGORITHM:

1. Start the program.

2. Get n as input.

3. Initialize i=2 and f=0.

4. Check the condition i

5. Calculate n % i and assign it to c.

6. If c=0, then assign f=1.

7. Otherwise, increment i value by 1.

8. Repeat Step 4 to 7.

9. If f=0, then print “the given no. is prime”.

10. Otherwise, print “the given no. is not prime.

11. Stop the program.

PROGRAM:



echo "Enter the number"

read n

i=2

f=0

while [ $i -lt $n ]

do

c=`expr $n % $i`

if [ $c -eq 0 ]

then

f=1

break

else

i=`expr $i + 1`

fi

done

if [ $f -eq 0 ]

then

echo "Prime"

else

echo "Not prime"

fi



OUTPUT:



Enter the number

5

Prime



Enter the number

4

Not prime



RESULT:

Thus the shell program for finding the given number is prime or not was written, executed and output was verified.









































REVERSE THE GIVEN STRING

AIM:

To write a shell program to reverse the given string.

ALGORITHM:

1. Start the program.

2. Get str as input.

3. Find the length of the string using wc-c command and assign it to len.

4. Check the condition len>0 using while loop.

5. Cut the last column of the string and assign it to temp.

6. Concatenate the rev and temp variable and assign it to rev.

7. Decrement the len value by 1.

8. Repeat Step 4 to 8.

9. Print the reversed string.

10. Stop the program.

PROGRAM:-



echo "Enter the string"

read str

len=`echo $str
wc -c`

while [ $len -gt 0 ]

do

temp=`echo $str
cut -c $len`

rev=`echo $rev$temp`

len=`expr $len - 1`

done

echo "The reversed String is $rev"



OUTPUT:



Enter the string

unix

The reversed String is xinu



RESULT:

Thus the shell program for reverse a given string was written, executed and output was verified.







SUM OF N EVEN NUMBERS USING UNTIL STATEMENT

AIM:

To write a shell program to find the sum of N even numbers using until loop.

ALGORITHM:

1. Start the program.

2. Get n as input.

3. Initialize i=2 and sum=0.

4. Check the condition i>n using until loop.

5. Calculate sum=sum+i.

6. Increment i value by 2.

7. Repeat Step 4 to 6 until the condition becomes false.

8. Print the sum of N even numbers.

9. Stop the program.

PROGRAM:



echo "Enter the limit"

read n

i=2

sum=0

until [ $i -gt $n ]

do

sum=`expr $sum + $i`

i=`expr $i + 2`

done

echo "The sum of $n numbers is $sum"





OUTPUT:



Enter the limit

9

The sum of 9 numbers is 20



RESULT:

Thus the shell program for sum of N even numbers using until statement was written, executed and output was verified.







SHELL PROGRAM USING FUNCTION WITH GRADE



AIM

To write a Shell program to print the grade of the students in a class using function



ALGORITHM

Step1: Display "Enter the mark details of a student"

Step2: Display “Enter the number of students"

Step3: Read the value of n

Step4: Assign i=1

Step5: Perform the following operations until n=0

Step5.1: Read the values of m1,m2,m3,m4,m5

Step5.2: Call the function stud to calculate total and average, GOTO Step

Step5.3: Call the function disp to display the total and average, GOTO Step

Step5.4: Call the function grade to process and display the grade, GOTO Step

Step5.5: Calculate i=i+1

Step5.6: Calculate n=n-1

Step6: In stud function,

Step6.1: Calculate tot = m1+m2+m3+m4+m5

Step6.2: Calculate avg=tot/5 and GOTO Step 5.3

Step7: In disp function,

Step7.1: Display tot and avg values, GOTO Step 5.4

Step8: In grade function,

Step8.1: Check if m1.m2,m3,m4,m5 >= 50

Step8.2: Display “Pass”

Step8.2.1: Check if avg >= 75

Step8.2.2: Display “First Class”

Step8.2.3: Else if avg >= 50 and avg <75

Step8.2.4: Display “Second Class”

Step8.3: Else Display”Fail”, GOTO Step 5

Step9: Stop the Program



PROGRAM:



echo "Enter the mark details of a student"

echo "Enter the number of students"

read n

disp() /*Display function definition */

{

echo "Total = $tot"

echo "Average = $avg"

}

stud() /*Student function definition */

{

tot=`expr $m1 + $m2 + $m3 + $m4 + $m5`

avg=`echo $tot / 5
bc`

}

grade() /*Grade function definition */

{

if [ $m1 -ge 50 -a $m2 -ge 50 -a $m3 -ge 50 -a $m4 -ge 50 -a $m5 -ge 50 ] then

echo "Pass"

if [ $avg -ge 75 ] then

echo "First class"

else if [ $avg -ge 50 -a $avg -lt 75 ] then

echo "Second Class"

fi

fi

else

echo "Fail"

fi

}

i=1

until [ $n -eq 0 ]

do

echo "$i. student mark details"

echo "Maths mark"

read m1

echo "Computer Mark"

read m2

echo "Chemistry Mark"

read m3

echo "Physics Mark"

read m4

echo "English Mark"

read m5

stud /*Stud function Call*/

disp /*display function call*/



echo "Grade of the student : $i"



grade /*Grade function call */

i=`expr $i + 1`

n=`expr $n - 1`

done



Output:



[11ee003@mcalinux ~]$ sh ecefun1.sh

Enter the mark details of a student

Enter the number of students

2

1. student mark details

Maths mark

98

Computer Mark

96

Chemistry Mark

95

Physics Mark

93

English Mark

98

Total = 480

Average = 96

Grade of the student : 1

Pass

First class



2. student mark details

Maths mark

85

Computer Mark

65

Chemistry Mark

32

Physics Mark

35

English Mark

49

Total = 266

Average = 53

Grade of the student : 2

Fail



RESULT

Thus the Shell program to print the grade of the students in a class using function was written and executed successfully, output was verified.















C PROGRAMS



























List of C Programs

1. FUNCTION WITH ARGUMENTS AND NO RETURN VALUES

2. FUNCTION WITHOUT ARGUMENTS AND NO RETURN VALUE

3. FUNCTION WITHOUT ARGUMENTS AND RETURN VALUE

4. FUNCTION WITH ARGUMENTS AND RETURN VALUES

5. FIBONACCI SERIES USING RECURSION

6. PROGRAM FOR ACCESSING THE VARIABLES THROUGH POINTER

7. PROGRAM TO FIND THE FACTORIAL USING RECURSION

8. PROGRAM FOR SORTING USING FUNCTION

9. LEAP YEAR OR NOT

10. PROGRAM TO PERFORM READING AND WRITING OPERATION

11. PROGRAM TO FIND THE VALUE OF X POWER N



FUNCTION WITH ARGUMENTS AND NO RETURN VALUES



Aim:

To Write a C program to perform Function with arguments and without Return values in unix editor.



Algorithm:



Step1: Start the program

Step2: Declare the user-defined function details with arguments(a, n)

Step3: In main function,

Step3.1: Declare the variables name, id

Step3.2: Read the values of name and id

Step3.3: Call the function details with arguments

Step 3.3.1: In user-defined function details,

Print the values passed from called function

Step 4: Stop the Program



PROGRAM:



#include

void details(char a[],int n);

main()

{

char name[25];

int id;

printf("enter the name:\n");

scanf("%s",name);

printf("enter the id:\n");

scanf("%d",&id);

details(name,id);

}

void details(char sname[],int sid)

{

printf("student details\n");

printf("******* *******\n");

printf("student name:%s\n",sname);

printf("student id:%d",sid);

}













Output:

[lakshmi@mcalinux ~]$ cc function.c

[lakshmi@mcalinux ~]$ ./a.out

enter the name:

siva

enter the id:

27



Result:

Thus the C program to perform Function with arguments and without Return values in unix editor was written, executed successfully and output was verified.









































































FUNCTION WITHOUT ARGUMENTS AND NO RETURN VALUE



Aim:

To Write a C program to perform Function without arguments and without Return values in unix editor.



Algorithm:



Step1: Start the program

Step2: Declare the user-defined function name with out arguments

Step3: In main function,

Step 3.1: Call the user-defined function name

Step 3.2: In User-defined name function,

Step 3.2.1: Declare the variables name1, sid

Step 3.2.2: Read the values of name1 and sid

Step 3.2.3: Print the values of name1 and sid

Step4: Stop the program.



Program:



#include

void name();

main()

{

name();

}

void name()

{

char name[25];

int sid;

printf("enter the student name:");

scanf("%s",name);

printf("\n enter student id:");

scanf("%d",&sid);

printf("student details\n");

printf("********************\n");

printf("student name:%s\n",name);

printf("student id:%d",sid);

}





















Output:



[lakshmi@mcalinux ~]$ cc function1.c

[lakshmi@mcalinux ~]$ ./a.out

enter the student name: George

enter student id: 05



STUDENT DETAILS

******************

student name: George

student id: 5





Result:

Thus the C program to perform Function without arguments and without Return values in unix editor was written, executed successfully and output was verified.

































































FUNCTION WITHOUT ARGUMENTS AND RETURN VALUE

Aim:

To Write a C program to perform Function without arguments and with Return values in unix editor.



Algorithm:



Step1: Start the Program

Step2: Declare the user-defined function mark () without arguments.

Step3: In main function,

Step3.1: Declare the variables total, avg

Step3.2: Call the mark () function, GOTO Step4

Step3.3: Display the total value return from called function

Step3.4: Calculate

avg=total/5

Step3.5: Display the value of avg

Step4: In user-defined function mark()

Step4.1: Declare the variables name[25],id,m1,m2,m3,m4,m5,total and avg

Step4.2: Read the values of name, id, m1, m2, m3, m4, m5

Step4.3: Calculate

Total=m1+m2+m3+m4+m5

Step4.4: Return the total value to calling function (main)

Step5: Stop the program



Program:



#include

int mark();

main()

{

int total;

float avg;

total=mark();

printf("Total = %d\n",total);

avg=total/5;

printf("Average = %f\n",avg);

}

int mark()

{

char name[25];

int id,m1,m2,m3,m4,m5,total;

float avg;

printf("Enter the student name :\n");

scanf("%s",&name);

printf("\n Enter the student id :\n");

scanf("%d",&id);

printf("\n Enter the five subject marks : \n");

scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);

total=m1+m2+m3+m4+m5;

return(total);

}



Output



[lakshmi@mcalinux ~]$ cc fwoar.

[lakshmi@mcalinux ~]$ ./a.out



Enter the student name :

Stephen

Enter the student id :

12345

Enter the five subject marks:

98

97

95

76

78

Total = 444

Average = 88.000000



Result:

Thus the C program to perform Function without arguments and with Return values in unix editor was written, executed successfully and output was verified.











































FUNCTION WITH ARGUMENTS AND RETURN VALUES

Aim:

To Write a C program to perform Function with arguments and with Return values in unix editor.



Algorithm:



Step1: Start the program

Step2: Declare the user-defined function details with arguments (m1, m2, m3)

Step3: Declare the variables name, id, m1, m2, m3, total

Step4: Read the values of name, id, m1, m2, m3

Step5: Call the user-defined function details( m1,m2,m3), GOTO Step7

Step6: Display the name, id & total value from user-defined function return.

Step7: In user-defined function details( m1,m2,m3),

Step7.1: Assign tot=0 & m1,m2, m3 as arguments

Step7.2: Calculate

tot = m1+m2+m3

Step7.3: return the tot value to calling function.

Step8: Stop the program



Program:



#include

int details(int m1,int m2,int m3);

main()

{

char name[25];

int id,m1,m2,m3,total;

printf("enter the name:\n");

scanf("%s",name);

printf("enter the id:\n");

scanf("%d",&id);

printf("enter 3 marks\n");

scanf("%d%d%d",&m1,&m2,&m3);

total=details(m1,m2,m3);

printf("student details\n");

printf("******************");

printf("\nstudent name:%s\n",name);

printf("student id:%d\n",id);

printf( "total:%d\n",total);

}

int details(m1,m2,m3)

{

int tot=0;

tot=m1+m2+m3;

return tot;

}



Output:

[lakshmi@mcalinux ~]$ cc fun.c

[lakshmi@mcalinux ~]$ ./a.out

enter the name:

raja

enter the id:

15

enter 3 marks

89

96

56

student details

******************

student name:raja

student id:15

total:241



Result:

Thus the C program to perform Function with arguments and with Return values in unix editor was written, executed successfully and output was verified.









































FIBONACCI SERIES USING RECURSION



Aim:

To Write a C program to print Fibonacci series until n terms using recursion in unix editor.



Algorithm:



Step1: Start the program

Step2: Declare the variables n, a, b and assign a=-1, b=1

Step3: Declare a function fibo (n, a, b) with arguments

Step4: Read the value of n

Step5: Call the function fibo (n, a, b), GOTO Step 6

Step6: In user-defined function fibo (x, y, z),

Step6.1: Declare w & x, y, z as arguments

Step6.2: If x=0 , exit;

Step6.3: else

Step6.3.1 calculate w=y + z

Step6.3.2 display w

Step6.3.3 assign y=z & z=w

Step6.3.4 decrement x by 1

Step6.4 : Call the fibo(x, y, z) GOTO Step 6 again till x reaches 0

Step7: Stop the program



Program:



#include

void main()

{

int n,a=-1,b=1;

void fibo(int n,int a,int b);/* Function Fibo declared */

printf("Fibonacci Series \n");

Printf("Enter the value to print number of terms in series\n");

scanf("%d",&n);

fibo(n,a,b);/* Function Fibo Called */

}

void fibo(int x,int y,int z)/* Function Fibo defined */

{

int w;

if(x==0)

exit(0);

else

w=y+z;

printf("%d \n”,w);

y=z;

z=w;

fibo(--x,y,z);

}



Output:

[lakshmi@mcalinux ~]$ cc fibo.c

[lakshmi@mcalinux ~]$ ./a.out

Fibonacci Series

Enter the value to print number of terms in series

10

0

1

1

2

3

5

8

13

21

34





Result:

Thus the C program to Fibonacci series until n terms using recursion in unix editor was written, executed successfully and output was verified.

























































PROGRAM FOR ACCESSING THE VARIABLES THROUGH POINTER



Aim:

To Write a C program to access the variables through pointer in unix editor.



Algorithm:



Step1: Start the program

Step2: Declare the variables a, b, and a pointer variable *ptr and assign a=5,b=10

Step3: Assign address of “a” in pointer as ptr =&a

Step4: Display the values of a and b

Step5: Assign the value of b=*ptr

Step6: Display the value of ptr

Step7: Display the address of a

Step8: Display the value of *ptr

Step9: Stop the program.



Program:



#include

main()

{

int a=5,b=10,*ptr;

ptr=&a;

printf("enter the initial value a=%d and b=%d\n",a,b);

b=*ptr;

printf("the changed values are a=%d and b=%d\n",a,b);

printf("the value is %d\n",ptr);

printf("the value of address of a is %d\n",&a);

printf("the value of *ptr is %d\n",*ptr);

}



Output:



[lakshmi@mcalinux ~]$ cc pointer.c

[lakshmi@mcalinux ~]$ ./a.out

enter the initial value a=5 and b=10

the changed values are a=5 and b=5

the value is -1079661272

the value of address of a is -1079661272

the value of *ptr is 5



Result:

Thus the C program to perform accessing the variables through pointer in unix editor was written, executed successfully and output was verified.





PROGRAM TO FIND THE FACTORIAL USING RECURSION



Aim:

To Write a C program to find factorial of a given number using recursion in unix editor.

Algorithm:

Step1: Start the program

Step2: Declare the function fact(num) and variables num, fac

Step3: Read the value of num

Step4: Assign the fact(num) to fac, GOTO Step 6. /*Function Call*/

Step5: Display the fac value return from fact user-defined function.

Step6: In user-defined fact(x) function, num value passed to argument x

Step6.1: If x<=1 then

Display fact value as 1

Step6.2: Else

Calculate x*fact(x-1) Call fact function GOTO Step6

again till x reaches 0 ,using recursion and return the fact value.

Step7: Stop the program.



Program:



#include

int fact(int);

main()

{

int num,fac;

printf("enter a number:\n");

scanf("%d",&num);

fac=fact(num);

printf("the factorial of %d is%d",num,fac);

}

int fact(int x)

{

if(x<=1)

return 1;

else

return(x*fact(x-1));

}



Output:

[lakshmi@mcalinux ~]$ cc fact.c

[lakshmi@mcalinux ~]$ ./a.out

enter a number:

5

the factorial of 5 is 120



Result:

Thus the C program to find factorial of a given number using recursion in unix editor was written, executed successfully and output was verified.

PROGRAM FOR SORTING USING FUNCTION



Aim:

To Write a C program to perform sorting an array integers in unix editor.



Algorithm:



Step1: Start the program

Step2: Declare the user-defined function sort(a, n) and variables are a[100],n, i, j

Step3: Read the value of n

Step4: Using for loop,

Step4.1: Assign i=0

Step4.2: if i

Step4.3: Calculate i=i+1,GOTO Step4.1

Setp5: Using for loop,

Step5.1: Assign i=0

Step5.2: if i

Step5.3: Calculate i=i+1,GOTO Step5.1

Step6: Call the user-defined function sort(a,n), GOTO Step 7.

Step7: In user-defined sort(a,n),

Step7.1: Declare the variables of i,j,temp=0

Step7.2: Using for loop,

Step7.2.1: Assign i=0

Step7.2.2: If i

Step7.2.3: Using for loop,

Step7.2.3.1: Assign j=i

Step7.2.3.2: if j

Step7.2.3.2.1 If (a[i] < a[j])

Assign temp=a[i]

a[i]=a[j]

a[j]=temp

Step7.2.3.3 Calculate j=j+1 GOTO Step7.2.3

Step7.2.3 Calculate i=i+1 GOTO Step7.2

Step8: Using for loop,

Step8.1: Assign i=0

Step8.2: if i

Step8.3: Calculate i=i+1 GOTO Step8

Step9: Stop the program



Program:



#include

void sort(int a[],int n);

main()

{

int a[100],n,i,j;

printf("enter the size of array"

scanf("%d",&n);

printf("enter the elements\n");

for(i=0;i

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

printf("before sorting\n");

for(i=0;i

printf("\t%d",a[i]);

sort(a,n);

}

void sort(int a[],int n)

{

int i,j,temp=0;

for(i=0;i

{

for(j=i;j

{

if(a[i]>a[j])

{

temp=a[i];

a[i]=a[j];

a[j]=temp;

}

}

}

printf("\nafter sorting\n");

for(i=0;i

printf("\t%d",a[i]);

}

Output

[lakshmi@mcalinux ~]$ cc sorting.c

[lakshmi@mcalinux ~]$ ./a.out

enter the size of array

3

enter the elements

87

34

69

before sorting

87 34 69

after sorting

34 69 87





Result:

Thus the C program to perform Sorting an array integers in unix editor was written, executed successfully and output was verified.











LEAP YEAR OR NOT



Aim:

To Write a C program to find the given year is leap year or not using function in unix editor.



Algorithm:



Step1: Start the program

Step2: Declare a function leap with an argument and assign year =0

Step3: Read the year value

Step4: While year > 0

Step4.1: Call the function leap(y),GOTO Step 5 in if statement check y as 0

Display “Given year is leap year”

Step4.2: else

Display “Given year is not leap year”

Step5: In leap function,

Step5.1: calculate y%4 , return value to called function.

Step6: Stop the program



Program:



#include

#include

int leap(int);

main()

{

int year=0;

printf("Enter a year");

scanf("%d",&year);

while(year>0)

{

if(leap(year))

printf("%d is a leap year",year);

else

printf("%d is not a leap year",year);

exit(0);

}

int leap(int y)

{

return((y%4)==0);

}















Output:



[lakshmi@mcalinux ~]$ cc leap.c

[lakshmi@mcalinux ~]$ ./a.out

Enter a year2004

2004 is a leap year



Enter a year2005

2005 is not a leap year



Result:

Thus the C program to to find the given year is leap year or not using function in unix editor was written, executed successfully and output was verified.









































































PROGRAM TO PERFORM READING AND WRITING OPERATION



Aim:

To Write a C program to perform reading and writng operatins in a file in unix editor.



Algorithm:



Step1: Start the program

Step2: Declare the variables empno, ename[25], deptname[35] & pointer(*ptr) variable in FILE

Step3: To write contents in a file, open the file in write mode

Step4: Read the values of empno, ename, deptname

Step5: Write the read values in file using fprintf

Step6: Close the file

Step7: To read contents in a file, open the file in read mode

Step8: Read the values of empno, ename, deptname using fscanf from file

Step9: Display the values of empno, ename, deptname

Step10: Close the file

Step11: Stop the program



Program:



#include

main()

{

int empno;

char ename[25],deptname[35];

FILE*ptr;

ptr=fopen("emp1.c","w");

printf("Enter employee name,nemployee number&dept:\n")

scanf("%s\t%d\t%s",ename,&empno,deptname);

fprintf(ptr,"%s\t%d\t%s",ename,empno,deptname);

fclose(ptr);

ptr=fopen("emp1.c","r");

fscanf(ptr,"%s%d%s",ename,&empno,deptname);

printf("\n employee name:%s",ename);

printf("\n employee number:%d",empno);

printf("\n department name:%s",deptname);

}



Output:



[lakshmi@mcalinux ~]$ cc read.c

[lakshmi@mcalinux ~]$ ./a.out

Enter employee name, employee number&dept:

Jessica

19

IT



employee name: Jessica

employee number: 19

department name: IT





Result:

Thus the C program to to perform reading and writing operations in a file in unix editor was written, executed successfully and output was verified.



















































































PROGRAM TO FIND THE VALUE OF X POWER N



Aim:

To Write a C program to find the value of x power n in unix editor.



Algorithm:



Step1: Start the program

Step2: Declare the user-defined function power(x ,n) with arguments.

Step3: Declare the variables x, n

Step4: Read the values of x & n

Step5: To display x to the power n, call power(x, n) user-defined function

Step5.1: Declare i and assign p=1

Step5.2 using for loop, assign i=1

If i <=n,

Calculate p = p * x

i = i + 1

GOTO Step 5.2

Step5.3: Return the value of p

Step6: Stop the Program



Program:



#include

int power(int x,int n);

main()

{

int x;

int n;

printf("enter the values of x and n\t");

scanf("%d%d",&x,&n);

printf("%d to the power of %d is %d",x,n,power(x,n));

}

int power(int x,int n)

{

int p=1;int i;

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

p*=x;

return(p);

}



OUTPUT

enter the values of x and n 5

2

5 to the power of 2 is 25



Result:

Thus the C program to to find the value of x power n in unix editor was written, executed successfully and output was verified.

Procedures



 To type shell program in unix editor

1. Open the telnet and open the file by vi filename.sh

2. Press “I” to insert

3. After type the contents press “esc” and “:wq” to save and exit.

4. To run the file type sh filename.sh , if any error, clear it and run again



 To type C program in unix editor

1. Open the telnet and open the file by vi filename.c

2. Press “I” to insert

3. After type the contents press “esc” and “:wq” to save and exit.

4. To compile the file type cc filename.c , if any error, clear it and run using ./a.out siva





1 comment:

Followers